예제 #1
0
        private static List <DTOs.Result <DTOs.BatchSet> > GetSourceBatches(IRSAPIClient proxy)
        {
            DTOs.Query <DTOs.BatchSet> query = new DTOs.Query <DTOs.BatchSet>();
            query.Fields = DTOs.FieldValue.AllFields;

            DTOs.QueryResultSet <DTOs.BatchSet> resultSet = new DTOs.QueryResultSet <DTOs.BatchSet>();
            try
            {
                resultSet = proxy.Repositories.BatchSet.Query(query, 0);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception when querying for batches: {message}", ex);
                return(null);
            }

            if (resultSet.Success)
            {
                if (resultSet.Results.Count > 0)
                {
                    _logger.LogInformation("{0} batch sets found in {1}", resultSet.Results.Count, proxy.APIOptions.WorkspaceID);
                    return(resultSet.Results);
                }
                else
                {
                    _logger.LogWarning("Query was successful but no batches exist.");
                    return(null);
                }
            }
            else
            {
                _logger.LogError("Unsuccessful query for batches: {message}", resultSet.Results[0].Message);
                return(null);
            }
        }
예제 #2
0
        public override Response Execute()
        {
            Response retVal = new Response
            {
                Success = true,
                Message = string.Empty
            };

            _logger = Helper.GetLoggerFactory().GetLogger().ForContext <PreLoadEvenHandler>();

            try
            {
                defaultUser = $"This comment will created by this user: {Helper.GetAuthenticationManager().UserInfo.FullName}";
                if (ActiveArtifact.IsNew)
                {
                    _logger.LogError("Enter in the if sentece");
                    ActiveArtifact.Fields[CREATED_BY_FIELD_GUID.ToString()].Value.Value = defaultUser;
                    ActiveArtifact.Fields[CREATED_ON_FIELD_GUID.ToString()].Value.Value = defaultDate;
                }
                else
                {
                    _logger.LogError("do not enter in the if sentence");
                    ActiveArtifact.Fields[CREATED_BY_FIELD_GUID.ToString()].Value.Value = $"This comment was created by: {ActiveArtifact.Fields[CREATED_BY_FIELD_GUID.ToString()].Value.Value}";
                }
            }
            catch (Exception e)
            {
                retVal.Success = false;
                retVal.Message = e.ToString();
            }
            return(retVal);
        }
        public async Task ExecuteAsync()
        {
            var sqlQueryHelper   = new SqlQueryHelper();
            var resourceGroupIds = GetResourceGroupIDs();

            _logger = Helper.GetLoggerFactory().GetLogger();
            var rsapiApiOptions = new APIOptions {
                WorkspaceID = -1
            };
            var rsapiClient = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.CurrentUser);

            rsapiClient.APIOptions = rsapiApiOptions;
            var rsapiGroupRepository = new RSAPIiRepositoryGroup(rsapiClient);
            var artifactQueries      = new ArtifactQueries();

            var job = new ImportWorkerJob(AgentID, Helper, sqlQueryHelper, artifactQueries, DateTime.Now, rsapiGroupRepository, resourceGroupIds, _logger, rsapiApiOptions, new SerializationHelper());

            job.OnMessage += MessageRaised;

            try
            {
                RaiseMessage("Enter Agent", 10);
                await job.ExecuteAsync();

                RaiseMessage("Exit Agent", 10);
            }
            catch (Exception ex)
            {
                //Raise an error on the agents tab and event viewer
                RaiseError(ex.ToString(), ex.ToString());
                _logger.LogError(ex, $"{Constant.Names.ApplicationName} - {ex}");

                //Add the error to our custom Errors table
                sqlQueryHelper.InsertRowIntoImportErrorLogAsync(Helper.GetDBContext(-1), job.WorkspaceArtifactId, Constant.Tables.ExportWorkerQueue, job.TableRowId, job.AgentId, ex.ToString()).Wait();

                //Add the error to the Relativity Errors tab
                //this second try catch is in case we have a problem connecting to the RSAPI
                try
                {
                    ErrorQueries.WriteError(Helper.GetServicesManager(), ExecutionIdentity.System, job.WorkspaceArtifactId, ex);
                }
                catch (Exception rsapiException)
                {
                    RaiseError(rsapiException.ToString(), rsapiException.ToString());
                    _logger.LogError(rsapiException, $"{Constant.Names.ApplicationName} - {rsapiException}");
                }
            }
            finally
            {
                rsapiClient.Dispose();
            }
        }
        public override void Execute()
        {
            RaiseMessage("Enter Agent", 10);

            try
            {
                _logger = Helper.GetLoggerFactory().GetLogger();
                IServicesMgr servicesMgr   = Helper.GetServicesManager();
                IDBContext   eddsDbContext = Helper.GetDBContext(-1);

                RaiseMessage("Querying for workspaces where the application is installed.", 10);
                DataTable workspacesDataTable = SqlHelper.RetrieveApplicationWorkspaces(eddsDbContext, Constants.Guids.Application);

                if (workspacesDataTable == null || workspacesDataTable.Rows.Count <= 0)
                {
                    return;
                }

                RaiseMessage($"Workspaces found({workspacesDataTable.Rows.Count})", 10);
                foreach (DataRow currentWorkspaceDataRow in workspacesDataTable.Rows)
                {
                    int workspaceArtifactId = (int)currentWorkspaceDataRow["ArtifactID"];
                    ProcessWorkspace(servicesMgr, workspaceArtifactId);
                }

                RaiseMessage("Exit Agent", 10);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{Constants.Names.APPLICATION} - An error occured in the Agent.", ex);
                RaiseMessage("An error occured in the Agent. Check Error Logs.", 10);
            }
        }
예제 #5
0
        /// <summary>
        /// Agent logic goes here
        /// </summary>
        public override void Execute()
        {
            IAPILog logger = Helper.GetLoggerFactory().GetLogger();

            try
            {
                //Get a dbContext for the workspace database
                int workspaceArtifactId = Helpers.Constants.WORKSPACE_ID;

                //Setting up an RSAPI Client
                using (IRSAPIClient rsapiClient = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.CurrentUser))
                {
                    //Set the proxy to use the current workspace
                    rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;

                    var counter = 0;
                    while (counter < 10)
                    {
                        var imageRDO = new RDO();
                        imageRDO.ArtifactTypeGuids.Add(Helpers.Constants.IMAGE_OBJECT_GUID);
                        imageRDO.Fields.Add(new FieldValue(Helpers.Constants.IMAGE_NAME_FIELD_GUID, DateTime.Now.ToLongTimeString() + " " + counter.ToString()));
                        rsapiClient.Repositories.RDO.Create(imageRDO);
                        counter++;
                    }
                }

                logger.LogVerbose("Log information throughout execution.");
            }
            catch (Exception ex)
            {
                //Your Agent caught an exception
                logger.LogError(ex, "There was an exception.");
                RaiseError(ex.Message, ex.Message);
            }
        }
        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;
            }));
        }
        // GET: Home
        public ActionResult Index()
        {
            IAPILog logger = Relativity.CustomPages.ConnectionHelper.Helper().GetLoggerFactory().GetLogger();

            try
            {
                //Gets the user ID.
                int userArtifactId = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.ArtifactID;
                //Gets the user ID to use for auditing purposes.
                int userAuditArtifactId = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.AuditArtifactID;
                //Gets the user workspace artifact ID to use for auditing purposes.
                int userAuditWorkspaceUserArtifactId = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.AuditWorkspaceUserArtifactID;
                //Gets the email address of the current user.
                string userEmailAddress = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.EmailAddress;
                //Gets the first name of the current user.
                string firstName = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.FirstName;
                //Gets the last name of the current user.
                string lastName = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.LastName;
                //Gets the full name of the current user.
                string fullName = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.FullName;
                //Gets the current user workspace artifact ID.
                int currentUserWorkspaceArtifactId = Relativity.CustomPages.ConnectionHelper.Helper().GetAuthenticationManager().UserInfo.WorkspaceUserArtifactID;

                //Get GUID for an artifact
                int  testArtifactId        = 1234567;
                Guid guidForTestArtifactId = Relativity.CustomPages.ConnectionHelper.Helper().GetGuid(currentUserWorkspaceArtifactId, testArtifactId);

                //Get a dbContext for the EDDS database
                IDBContext eddsDbContext = Relativity.CustomPages.ConnectionHelper.Helper().GetDBContext(-1);

                //Get a dbContext for the workspace database
                IDBContext workspaceDbContext = Relativity.CustomPages.ConnectionHelper.Helper().GetDBContext(currentUserWorkspaceArtifactId);

                //The Object Manager is the newest and preferred way to interact with Relativity instead of the Relativity Services API(RSAPI).
                //The RSAPI will be scheduled for depreciation after the Object Manager reaches feature party with it.
                using (IObjectManager objectManager = Relativity.CustomPages.ConnectionHelper.Helper().GetServicesManager().CreateProxy <IObjectManager>(ExecutionIdentity.CurrentUser))
                {
                }

                //Setting up an RSAPI Client
                using (IRSAPIClient rsapiClient = Relativity.CustomPages.ConnectionHelper.Helper().GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.CurrentUser))
                {
                    //Set the proxy to use the current workspace
                    rsapiClient.APIOptions.WorkspaceID = currentUserWorkspaceArtifactId;

                    //Add code for working with RSAPIClient
                }

                logger.LogVerbose("Log information throughout execution.");
            }
            catch (Exception ex)
            {
                //Your custom page caught an exception
                logger.LogError(ex, "There was an exception.");
            }

            return(View());
        }
예제 #8
0
        /// <summary>
        /// Agent logic goes here
        /// </summary>
        public override void Execute()
        {
            IAPILog logger = Helper.GetLoggerFactory().GetLogger();

            try
            {
                // Update Security Protocol
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                //Get the current Agent artifactID
                int agentArtifactId = AgentID;

                //Get a dbContext for the EDDS database
                IDBContext eddsDbContext = Helper.GetDBContext(-1);

                //Get a dbContext for the workspace database
                //int workspaceArtifactId = 01010101; // Update it with the real
                //IDBContext workspaceDbContext = Helper.GetDBContext(workspaceArtifactId);

                //Get GUID for an artifact
                //int testArtifactId = 10101010;
                //Guid guidForTestArtifactId = Helper.GetGuid(workspaceArtifactId, testArtifactId);

                //Display a message in Agents Tab and Windows Event Viewer
                RaiseMessage("The current time is: " + DateTime.Now.ToLongTimeString(), 1);

                //The Object Manager is the newest and preferred way to interact with Relativity instead of the Relativity Services API(RSAPI).
                //The RSAPI will be scheduled for depreciation after the Object Manager reaches feature party with it.
                using (IWorkspaceName workspaceName = this.Helper.GetServicesManager().CreateProxy <IWorkspaceName>(ExecutionIdentity.CurrentUser))
                {
                    String name = workspaceName.GetWorkspaceNameAsync(1017759).Result.Name;
                    RaiseMessage("The worksapce name is" + name, 1);
                }

                //Setting up an RSAPI Client
                using (IRSAPIClient rsapiClient = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.CurrentUser))
                {
                    //Set the proxy to use the current workspace
                    //rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;

                    //Add code for working with RSAPIClient
                }

                logger.LogVerbose("Log information throughout execution.");
            }
            catch (Exception ex)
            {
                //Your Agent caught an exception
                logger.LogError(ex, "There was an exception.");
                RaiseError(ex.Message, ex.Message);
            }
        }
예제 #9
0
        public async Task ExecuteAsync()
        {
            ISqlQueryHelper     sqlQueryHelper   = new SqlQueryHelper();
            IEnumerable <Int32> resourceGroupIds = GetResourceGroupIDs();

            _logger = Helper.GetLoggerFactory().GetLogger();
            IArtifactQueries artifactQueries = new ArtifactQueries();

            //Setup RSAPI repositories
            APIOptions rsapiApiOptions = new APIOptions
            {
                WorkspaceID = -1
            };
            IRSAPIClient rsapiClient = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.CurrentUser);

            rsapiClient.APIOptions = rsapiApiOptions;
            IRsapiRepositoryGroup rsapiRepositoryGroup = new RSAPIiRepositoryGroup(rsapiClient);
            ILoginProfileManager  loginProfileManager  = Helper.GetServicesManager().CreateProxy <ILoginProfileManager>(ExecutionIdentity.CurrentUser);
            IAuthenticationHelper authenticationHelper = new AuthenticationHelper(loginProfileManager);
            ISerializationHelper  serializationHelper  = new SerializationHelper();

            ExportWorkerJob job = new ExportWorkerJob(
                agentId: AgentID,
                agentHelper: Helper,
                sqlQueryHelper: sqlQueryHelper,
                processedOnDateTime: DateTime.Now,
                resourceGroupIds: resourceGroupIds,
                logger: _logger,
                artifactQueries: artifactQueries,
                rsapiApiOptions: rsapiApiOptions,
                rsapiRepositoryGroup: rsapiRepositoryGroup,
                authenticationHelper: authenticationHelper,
                serializationHelper: serializationHelper);

            job.OnMessage += MessageRaised;

            try
            {
                RaiseMessage("Enter Agent", 10);
                await job.ExecuteAsync();

                RaiseMessage("Exit Agent", 10);
            }
            catch (Exception ex)
            {
                //Raise an error on the agents tab and event viewer
                RaiseError(ex.ToString(), ex.ToString());
                _logger.LogError(ex, $"{Constant.Names.ApplicationName} - {ex}");

                //Add the error to our custom Errors table
                sqlQueryHelper.InsertRowIntoExportErrorLogAsync(Helper.GetDBContext(-1), job.WorkspaceArtifactId, Constant.Tables.ExportWorkerQueue, job.TableRowId, job.AgentId, ex.ToString()).Wait();

                //Add the error to the Relativity Errors tab
                //this second try catch is in case we have a problem connecting to the RSAPI
                try
                {
                    ErrorQueries.WriteError(Helper.GetServicesManager(), ExecutionIdentity.System, job.WorkspaceArtifactId, ex);
                }
                catch (Exception rsapiException)
                {
                    RaiseError(rsapiException.ToString(), rsapiException.ToString());
                    _logger.LogError(rsapiException, $"{Constant.Names.ApplicationName} - {rsapiException}");
                }

                //Set the status in the queue to error
                sqlQueryHelper.UpdateStatusInExportWorkerQueueAsync(Helper.GetDBContext(-1), Constant.Status.Queue.ERROR, job.BatchTableName).Wait();
            }
            finally
            {
                rsapiClient.Dispose();
            }
        }
예제 #10
0
 public void LogError(Exception ex, string message)
 {
     _logger.LogError(ex, message);
 }
예제 #11
0
        public Invoice ConvertAnalyzeResultToInvoice(AnalyzeResult result, IHelper helper)
        {
            Invoice       invoice = new Invoice();
            List <string> values  = new List <string>();
            string        field;

            try
            {
                Dictionary <string, string> keyValues = new Dictionary <string, string>();

                foreach (ExtractedPage page in result.Pages)
                {
                    foreach (ExtractedKeyValuePair pair in page.KeyValuePairs)
                    {
                        string key = pair.Key[0].Text.Replace(" ", "_").Replace("(", "_").Replace(")", "_").Trim();
                        switch (key)
                        {
                        case "To:":
                            values     = pair.Value.Select(p => p.Text).ToList();
                            field      = string.Join(" ", values).Trim();
                            invoice.To = field;
                            values.Clear();
                            break;

                        case "From:":
                            values       = pair.Value.Select(p => p.Text).ToList();
                            field        = string.Join(" ", values).Trim();
                            invoice.From = field;
                            values.Clear();
                            break;

                        case "Due_Date:":
                            values          = pair.Value.Select(p => p.Text).ToList();
                            field           = string.Join(" ", values).Trim();
                            invoice.DueDate = DateTime.Parse(field);
                            values.Clear();
                            break;

                        case "Date_of_Issue:":
                            values = pair.Value.Select(p => p.Text).ToList();
                            field  = string.Join(" ", values).Trim();
                            invoice.DateOfIssue = DateTime.Parse(field);
                            values.Clear();
                            break;

                        case "Total_Amount_Due":
                            values = pair.Value.Select(p => p.Text).ToList();
                            field  = string.Join(" ", values).Trim();
                            invoice.TotalAmountDue = field;
                            values.Clear();
                            break;

                        default:
                            break;
                        }
                    }

                    //getting invoice line items here
                    foreach (ExtractedTable table in page.Tables)
                    {
                        int       columnCount = 0;
                        DataTable tbl         = new DataTable();
                        foreach (ExtractedTableColumn column in table.Columns)
                        {
                            tbl.Columns.Add(table.Columns[columnCount].Header[0].Text, typeof(string));
                            if (columnCount == 0)
                            {
                                for (int i = 0; i < column.Entries.Count; ++i)
                                {
                                    tbl.Rows.Add(column.Entries[i][0].Text);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < column.Entries.Count; ++i)
                                {
                                    tbl.Rows[i][table.Columns[columnCount].Header[0].Text] = column.Entries[i][0].Text;
                                    tbl.AcceptChanges();
                                }
                            }
                            columnCount += 1;
                        }

                        List <InvoiceLineItem> listItems = new List <InvoiceLineItem>();

                        const int descriptionColumnIndex = 0;
                        const int rateColumnIndex        = 1;
                        const int quantityColumnIndex    = 2;
                        const int lineTotalColumnIndex   = 3;
                        listItems = tbl.Select().Select(row =>
                        {
                            InvoiceLineItem lineItem = new InvoiceLineItem();
                            lineItem.Description     = row[descriptionColumnIndex].ToString();
                            lineItem.Rate            = SanitizeCurrency(row[rateColumnIndex].ToString());
                            lineItem.Quantity        = Convert.ToInt32(row[quantityColumnIndex].ToString()) as int? ?? 0;
                            lineItem.LineTotal       = SanitizeCurrency(row[lineTotalColumnIndex].ToString());
                            return(lineItem);
                        }).ToList();
                        invoice.LineItems = listItems;
                    }
                }
            }
            catch (Exception ex)
            {
                IAPILog logger = helper?.GetLoggerFactory()?.GetLogger()?.ForContext <Invoice>();
                logger?.LogError(ex, "Error converting AnalyzeResult to Invoice");
            }

            return(invoice);
        }
        public override Response Execute()
        {
            _logger = this.Helper.GetLoggerFactory().GetLogger().ForContext <PreSaveEventHandlerComment>();
            Response retVal = new Response();

            retVal.Success = true;
            retVal.Message = string.Empty;



            // Console.WriteLine(output);

            //string output = null;
            try
            {
                String comment = (String)this.ActiveArtifact.Fields[COMMENT_FIEL_GUID.ToString()].Value.Value;
                string user    = (String)this.ActiveArtifact.Fields[SYSTEM_CREATED_BY_FIELD.ToString()].Value.Value;



                if (!(ActiveArtifact.Fields[RELATED_COMMENT_FIELD.ToString()] == null))
                {
                    using (kCura.Relativity.Client.IRSAPIClient client =
                               this.Helper.GetServicesManager().CreateProxy <kCura.Relativity.Client.IRSAPIClient>(Relativity.API.ExecutionIdentity.System))
                    {
                        client.APIOptions.WorkspaceID = this.Helper.GetActiveCaseID();
                        Service.RSAPIService.CommentRSAPIService commentRSAPIService = new Service.RSAPIService.CommentRSAPIService(client);
                        Service.SqlService.CommentSqlService     commentSqlService   = new Service.SqlService.CommentSqlService(this.Helper.GetDBContext(Helper.GetActiveCaseID()));
                        int parentCommentId = (int)this.ActiveArtifact.Fields[RELATED_COMMENT_FIELD.ToString()].Value.Value;
                        Data.Entities.Comment parentComment = new Data.Entities.Comment(parentCommentId);
                        parentComment = commentRSAPIService.Get(parentCommentId);
                        List <Data.Entities.Comment> commentsChild = commentSqlService.GetCommentsChild(parentComment.ArtifactId);
                        parentComment.CommentChilds = commentsChild;
                        int user1 = parentComment.CreatedBy.ArtifactId;
                        int user2 = this.Helper.GetAuthenticationManager().UserInfo.ArtifactID;

                        if (commentsChild.Count.Equals(0))
                        {
                            if (user1.Equals(user2))
                            {
                                throw new StartConversation();
                            }
                        }
                    }
                }



                if (String.IsNullOrWhiteSpace(comment))
                {
                    _logger.LogError($"the comment field was not fill up ");
                    throw new FieldMissingException("Comment");
                }
                if (!ActiveArtifact.IsNew)
                {
                    using (kCura.Relativity.Client.IRSAPIClient client =
                               this.Helper.GetServicesManager().CreateProxy <kCura.Relativity.Client.IRSAPIClient>(ExecutionIdentity.System))
                    {
                        client.APIOptions.WorkspaceID = this.Helper.GetActiveCaseID();
                        Service.RSAPIService.CommentRSAPIService commentRSAPIService = new Service.RSAPIService.CommentRSAPIService(client);
                        Data.Entities.Comment currentComment = new Data.Entities.Comment(ActiveArtifact.ArtifactID);
                        currentComment = commentRSAPIService.Get(ActiveArtifact.ArtifactID);
                        int commentUserId = currentComment.CreatedBy.ArtifactId;
                        int currentUserId = this.Helper.GetAuthenticationManager().UserInfo.ArtifactID;

                        if (!commentUserId.Equals(currentUserId))
                        {
                            throw new DontEditAnotherComment();
                        }
                    }
                }


                Boolean          typeSelected = false;
                ChoiceCollection typeField    = (ChoiceCollection)this.ActiveArtifact.Fields[TYPE_FIELD_GUID.ToString()].Value.Value;

                foreach (Choice typeChoice in typeField)
                {
                    if (typeChoice.IsSelected)
                    {
                        typeSelected = true;
                        break;
                    }
                }

                if (!typeSelected)
                {
                    throw new FieldMissingException("Comment Type");
                }
            }
            catch (FieldMissingException fielMissingEx)
            {
                retVal.Success = false;
                retVal.Message = fielMissingEx.Message;
            }


            catch (Exception e)
            {
                retVal.Success = false;
                retVal.Message = e.Message;
            }
            return(retVal);
        }
예제 #13
0
        public override void Execute()
        {
            IAPILog logger = Helper.GetLoggerFactory().GetLogger();

            try
            {
                /* Adding message so time of last check-in updates */
                RaiseMessage("Managing the agents.", 10);

                /* Resource Pool ArtifactID is hard coded for now (Default pool)
                 * Will eventually make this accessible in the UI */
                int poolId = 1015040;

                /* Agent Server Adjustment factor.
                 * Will eventually make this accessible in the UI */
                int adjFactor = 10;

                /* This switch tells Agent Agent to not create any agents on a server containing the dtSearch search agent.
                 * Will eventually make this accessible in the UI*/
                bool ignoreSearchServer = true;

                /*Use API to create/delete agents instead of manually creating in SQL*/
                bool useApiCreate = true;
                bool useApiDelete = true;

                /* Making stuff */
                logger.LogVerbose("Creating new {objectName}", "Agent Helper");
                IAgentHelper agentHelper = Helper;

                logger.LogVerbose("Creating new {objectName}", "EDDS DB Context");
                IDBContext eddsDbContext = agentHelper.GetDBContext(-1);

                logger.LogVerbose("Creating new {objectName}", "Environment Helper");
                EnvironmentHelper environment = new EnvironmentHelper(eddsDbContext);

                logger.LogVerbose("Creating new {objectName}", "Desired Agents List");
                List <AgentsDesired> desiredAgentsList = new GetAgentsDesiredList(agentHelper, environment, poolId, IsOffHours()).AgentsPerServerObjectList;

                logger.LogVerbose("Creating new {objectName}", "Compared List");
                List <AgentsDesired> comparedList = new CompareDesiredAgentsToExisting(desiredAgentsList, poolId, environment, logger).Compare();

                logger.LogVerbose("Creating new {objectName}", "List Helper");
                AgentsDesiredListHelper listHelper = new AgentsDesiredListHelper(comparedList);

                logger.LogVerbose("Creating new {objectName}", "Create List");
                List <AgentsDesired> createList = listHelper.GetAgentCreateList();

                logger.LogVerbose("Creating new {objectName}", "Delete List");
                List <AgentsDesired> deleteList = listHelper.GetAgentDeleteList();

                logger.LogVerbose("Creating new {objectName}", "Spots Per Server List");
                List <SpotsPerServer> spotsPerServerList = new GetSpotsPerServerList(eddsDbContext, environment, adjFactor, poolId, ignoreSearchServer).SpotsPerServerList;

                logger.LogVerbose("Creating {objectName}", "Agent Create");
                ICreateAgent createAgent = new CreateAgentSql(eddsDbContext, environment);
                if (useApiCreate)
                {
                    createAgent = new CreateAgentApi(eddsDbContext, environment, agentHelper);
                }

                logger.LogVerbose("Creating {objectName}", "Agent Delete");
                IDeleteAgent deleteAgent = new DeleteAgent(eddsDbContext);
                if (useApiDelete)
                {
                    deleteAgent = new DeleteAgentApi(eddsDbContext, agentHelper);
                }


                /* Log createList, deleteList, and spotsPerServerList contents */
                string createListString         = "";
                string deleteListString         = "";
                string spotsPerServerListString = "";

                foreach (AgentsDesired cL in createList)
                {
                    createListString += string.Format("{0} - {1} - {2}\r\n", cL.Guid, cL.Count, cL.RespectsResourcePool);
                }

                foreach (AgentsDesired dL in deleteList)
                {
                    deleteListString += string.Format("{0} - {1} - {2}\r\n", dL.Guid, dL.Count, dL.RespectsResourcePool);
                }

                foreach (SpotsPerServer sP in spotsPerServerList)
                {
                    spotsPerServerListString += string.Format("{0} - {1}\r\n", sP.AgentServerArtifactId, sP.Spots);
                }

                logger.LogDebug("Delete List : {deleteList}", deleteListString);
                logger.LogDebug("Create List: {createList}", createListString);
                logger.LogDebug("Spots Per Server List = {spotsPerServerList}", spotsPerServerListString);


                /* Create */
                RunAgentCreate agentCreate = new RunAgentCreate(eddsDbContext, environment, createAgent, createList, spotsPerServerList, logger);
                logger.LogVerbose("Running {objectName}", "Agent Create");
                agentCreate.Run();
                logger.LogVerbose("Completed {objectName}", "Agent Create");


                /* Delete */
                RunAgentDelete agentDelete = new RunAgentDelete(eddsDbContext, environment, deleteAgent, poolId, deleteList, logger);
                logger.LogVerbose("Running {objectName}", "Agent Delete");
                agentDelete.Run();
                logger.LogVerbose("Completed {objectName}", "Agent Delete");
            }
            catch (Exception ex)
            {
                RaiseError(ex.Message, ex.StackTrace);
                logger.LogError("Exception during agent Execute(): {ex}", ex);
                RaiseMessage("There has been an error. See log for more details", 1);
            }
        }
예제 #14
0
        public override Response Execute()
        {
            //Get the logger from the helper and set the ForContext to this class.
            _logger = Helper.GetLoggerFactory().GetLogger().ForContext <WorkspaceCreate>();

            // construct a response object with default values
            retVal.Message = String.Empty;
            retVal.Success = true;

            try
            {
                // get the current workspace artifact ID
                int currentWorkspaceID = Helper.GetActiveCaseID();

                // get the current workspace database context
                IDBContext workspaceDBContext = Helper.GetDBContext(currentWorkspaceID);

                // query for template workspace artifactID
                int templateWorkspaceID = GetTemplateCase(workspaceDBContext);

                using (IRSAPIClient proxy = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.System))
                {
                    // query for template workspace
                    DTOs.Workspace template = FindWorkspaceArtifactID(templateWorkspaceID, proxy);

                    if (template != null)
                    {
                        Folder._templateRootFolder = template.RootFolderID;
                    }
                    else
                    {
                        retVal.Success = false;
                        retVal.Message = "Template workspace not found; unable to replicate folder structure.";
                        return(retVal);
                    }

                    // query for target workspace
                    DTOs.Workspace target = FindWorkspaceArtifactID(currentWorkspaceID, proxy);

                    if (target != null)
                    {
                        Folder._targetRootFolder = target.RootFolderID;
                    }
                    else
                    {
                        retVal.Success = false;
                        retVal.Message = "Target workspace not found; unable to replicate folder structure.";
                        _logger.LogError("Target workspace not found; unable to replicate folder structure.");
                        return(retVal);
                    }

                    proxy.APIOptions.WorkspaceID = templateWorkspaceID;

                    // get folders from template workspace
                    List <DTOs.Result <DTOs.Folder> > source = Program.GetSourceFolders(proxy);

                    if (source == null)
                    {
                        retVal.Success = false;
                        retVal.Message = "Query for folders in template workspace was unsuccessful.";
                        _logger.LogError("Query for folders in template workspace was unsuccessful.");
                        return(retVal);
                    }
                    else if (source.Count == 1)
                    {
                        retVal.Success = false;
                        retVal.Message = "No folders found in template workspace.";
                        _logger.LogError("No folders found in template workspace.");
                        return(retVal);
                    }

                    proxy.APIOptions.WorkspaceID = currentWorkspaceID;

                    // create folders
                    Folder.CreateFolders(source, proxy);
                }
            }
            catch (Exception ex)
            {
                // catch an exception if it occurs, log it, and return a response with success = false.
                retVal.Success = false;
                retVal.Message = ex.ToString();
            }

            return(retVal);
        }