Example #1
0
        public static void UpdateJobField(IServicesMgr servicesMgr, int workspaceArtifactId, int jobArtifactId, Guid fieldGuid, object fieldValue)
        {
            try
            {
                using (IRSAPIClient rsapiClient = servicesMgr.CreateProxy <IRSAPIClient>(ExecutionIdentity.System))
                {
                    rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;
                    RDO jobRdo = new RDO(jobArtifactId);
                    jobRdo.ArtifactTypeGuids.Add(Constants.Guids.ObjectType.InstanceMetricsJob);
                    jobRdo.Fields.Add(new FieldValue(fieldGuid, fieldValue));

                    try
                    {
                        rsapiClient.Repositories.RDO.UpdateSingle(jobRdo);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"{Constants.ErrorMessages.UPDATE_APPLICATION_JOB_STATUS_ERROR}. UpdateSingle. [{nameof(workspaceArtifactId)}= {workspaceArtifactId}, {nameof(jobArtifactId)}= {jobArtifactId}, {nameof(fieldGuid)}= {fieldGuid}, {nameof(fieldValue)}= {fieldValue}]", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorMessages.UPDATE_APPLICATION_JOB_STATUS_ERROR, ex);
            }
        }
        /// <summary>
        /// Check to see if passed in credentials via Header Authentication is valid
        /// </summary>
        /// <param name="serviceManager"></param>
        /// <returns></returns>
        public async Task <string> RequestAuthTokenAsync(IServicesMgr serviceManager)
        {
            string retVal = null;

            using (IRSAPIClient rsapiClient = serviceManager.CreateProxy <IRSAPIClient>(ExecutionIdentity.System))
            {
                try
                {
                    rsapiClient.APIOptions = new APIOptions {
                        WorkspaceID = -1
                    };
                    var readResult =
                        await Task.Run(() => rsapiClient.GenerateRelativityAuthenticationToken(rsapiClient.APIOptions));

                    if (readResult.Success)
                    {
                        retVal = readResult.Artifact.getFieldByName("AuthenticationToken").ToString();
                    }
                    else
                    {
                        _logHelper.LogError($"DAPI - {nameof(RequestAuthTokenAsync)} - Unable to receive authorization token");
                    }
                }
                catch (Exception ex)
                {
                    _logHelper.LogError(ex,
                                        $"DAPI - {nameof(RequestAuthTokenAsync)} - Error while requesting authorization token: {ex}");
                }
            }

            return(retVal);
        }
        public static Int32 Query_For_Saved_SearchID(string savedSearchName, IRSAPIClient _client)
        {
            int searchArtifactId = 0;

            var query = new Query
            {
                ArtifactTypeID = (Int32)ArtifactType.Search,
                Condition      = new TextCondition("Name", TextConditionEnum.Like, savedSearchName)
            };
            QueryResult result = null;

            try
            {
                result = _client.Query(_client.APIOptions, query);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: {0}", ex.Message);
            }

            if (result != null)
            {
                searchArtifactId = result.QueryArtifacts[0].ArtifactID;
            }

            return(searchArtifactId);
        }
Example #4
0
        protected RelativityFile GetFile(int fileFieldArtifactId, int ourFileContainerInstanceArtifactId)
        {
            using (IRSAPIClient proxyToWorkspace = CreateProxy())
            {
                try
                {
                    var fileRequest = new FileRequest(proxyToWorkspace.APIOptions);
                    fileRequest.Target.FieldId          = fileFieldArtifactId;
                    fileRequest.Target.ObjectArtifactId = ourFileContainerInstanceArtifactId;

                    RelativityFile returnValue;
                    var            fileData = invokeWithRetryService.InvokeWithRetry(() => proxyToWorkspace.Download(fileRequest));

                    using (MemoryStream ms = (MemoryStream)fileData.Value)
                    {
                        FileValue    fileValue    = new FileValue(null, ms.ToArray());
                        FileMetadata fileMetadata = fileData.Key.Metadata;

                        returnValue = new RelativityFile(fileFieldArtifactId, fileValue, fileMetadata);
                    }

                    return(returnValue);
                }
                catch (Exception ex)
                {
                    throw new ProxyOperationFailedException("Failed in method: " + System.Reflection.MethodInfo.GetCurrentMethod(), ex);
                }
            }
        }
Example #5
0
        public static Int32 ImportApplication(IRSAPIClient client, Int32 workspaceId, bool forceFlag, string filePath, string applicationName, int appArtifactID = -1)
        {
            int artifactID = 0;

            ImportApplication(client, workspaceId, forceFlag, filePath, appArtifactID);

            Console.WriteLine("Querying for Application artifact id....");
            var query = new Query <kCura.Relativity.Client.DTOs.RelativityApplication>();

            query.Fields.Add(new FieldValue(RelativityApplicationFieldNames.Name));
            query.Condition = new TextCondition(RelativityApplicationFieldNames.Name, TextConditionEnum.EqualTo, applicationName);
            var queryResultSet = client.Repositories.RelativityApplication.Query(query);

            if (queryResultSet != null)
            {
                var result = queryResultSet.Results.FirstOrDefault();
                if (result == null || result.Artifact == null)
                {
                    throw new ApplicationInstallException($"Could not find application with name {applicationName}.");
                }
                artifactID = result.Artifact.ArtifactID;
                Console.WriteLine("Application artifactid is " + artifactID);
            }

            Console.WriteLine("Exiting Import Application method.....");
            return(artifactID);
        }
Example #6
0
        private static int FindClientArtifactId(IRSAPIClient rsapiClient, string group)
        {
            int artifactId = 0;

            TextCondition clientCondition = new TextCondition(ClientFieldNames.Name, TextConditionEnum.EqualTo, group);

            Query <Client> queryClient = new Query <Client>
            {
                Condition = clientCondition,
                Fields    = FieldValue.AllFields
            };

            try
            {
                QueryResultSet <Client> resultSetClient = rsapiClient.Repositories.Client.Query(queryClient, 0);

                if (resultSetClient.Success && resultSetClient.Results.Count == 1)
                {
                    artifactId = resultSetClient.Results.FirstOrDefault().Artifact.ArtifactID;
                }
                else
                {
                    Console.WriteLine("The Query operation failed.{0}{1}", Environment.NewLine, resultSetClient.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
            return(artifactId);
        }
Example #7
0
        public KeyValuePair <byte[], kCura.Relativity.Client.FileMetadata> DownloadDocumentNative(int documentId)
        {
            kCura.Relativity.Client.DTOs.Document doc = new kCura.Relativity.Client.DTOs.Document(documentId);
            byte[] documentBytes;

            KeyValuePair <DownloadResponse, Stream> documentNativeResponse = new KeyValuePair <DownloadResponse, Stream>();

            using (IRSAPIClient proxy = CreateProxy())
            {
                try
                {
                    documentNativeResponse = invokeWithRetryService.InvokeWithRetry(() => proxy.Repositories.Document.DownloadNative(doc));
                }
                catch (Exception ex)
                {
                    throw new ProxyOperationFailedException("Failed in method: " + System.Reflection.MethodInfo.GetCurrentMethod(), ex);
                }
            }

            using (MemoryStream ms = (MemoryStream)documentNativeResponse.Value)
            {
                documentBytes = ms.ToArray();
            }

            return(new KeyValuePair <byte[], FileMetadata>(documentBytes, documentNativeResponse.Key.Metadata));
        }
Example #8
0
        public static int CreateDocumentFieldArticleTitle(IRSAPIClient proxy, int workspaceId)
        {
            Field createField = new Field()
            {
                Name               = "Article Title",
                FieldTypeID        = FieldType.LongText,
                IsRequired         = false,
                Unicode            = true,
                OpenToAssociations = true,
                Linked             = false,
                AllowSortTally     = true,
                Wrapping           = true,
                AllowGroupBy       = true,
                AllowPivot         = true,
                IgnoreWarnings     = true,
                IncludeInTextIndex = false,
                AvailableInViewer  = false,
                AllowHTML          = false,
                Width              = "123",
                ObjectType         = new ObjectType
                {
                    DescriptorArtifactTypeID = 10
                }
            };

            proxy.APIOptions.WorkspaceID = workspaceId;
            int artifactIdCreatedField = proxy.Repositories.Field.CreateSingle(createField);

            return(artifactIdCreatedField);
        }
Example #9
0
        public static bool Delete_Group(IRSAPIClient client, int artifactId)
        {
            var clientID = client.APIOptions.WorkspaceID;

            client.APIOptions.WorkspaceID = -1;
            Group groupToDelete = new Group(artifactId);
            WriteResultSet <Group> resultSet = new WriteResultSet <Group>();

            try
            {
                resultSet = client.Repositories.Group.Delete(groupToDelete);

                if (!resultSet.Success || resultSet.Results.Count == 0)
                {
                    throw new Exception("Group not found in Relativity");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Group deletion threw an exception" + e);
                return(false);
            }

            client.APIOptions.WorkspaceID = clientID;
            return(true);
        }
Example #10
0
        static DTOs.Folder CreateFolder(DTOs.Folder source, int parent, IRSAPIClient client)
        {
            source.Name           = source.Name;
            source.ParentArtifact = new DTOs.Artifact(parent);

            DTOs.WriteResultSet <DTOs.Folder> results;

            try
            {
                results = client.Repositories.Folder.Create(source);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("An error occurred: {0}", ex.Message);
                return(null);
            }

            if (!results.Success)
            {
                //Console.WriteLine("Error: " + results.Results.FirstOrDefault().Message);
                return(null);
            }
            else
            {
                //Console.Write("{0} folder created successfully.\r\n", source.Name);
                return(results.Results.FirstOrDefault().Artifact);
            }
        }
        private void SetupRsapiHelper()
        {
            try
            {
                APIOptions rsapiApiOptions = new APIOptions
                {
                    WorkspaceID = -1
                };

                IRSAPIClient rsapiClient = Helper.GetServicesManager().CreateProxy <IRSAPIClient>(ExecutionIdentity.System);
                rsapiClient.APIOptions = rsapiApiOptions;
                IGenericRepository <RDO>       rdoRepository       = rsapiClient.Repositories.RDO;
                IGenericRepository <Choice>    choiceRepository    = rsapiClient.Repositories.Choice;
                IGenericRepository <Workspace> workspaceRepository = rsapiClient.Repositories.Workspace;
                IGenericRepository <kCura.Relativity.Client.DTOs.User> userRepository = rsapiClient.Repositories.User;
                IGenericRepository <Group> groupRepository = rsapiClient.Repositories.Group;

                _rsapiHelper = new RsapiHelper(
                    rsapiApiOptions: rsapiApiOptions,
                    rdoRepository: rdoRepository,
                    choiceRepository: choiceRepository,
                    workspaceRepository: workspaceRepository,
                    userRepository: userRepository,
                    groupRepository: groupRepository);
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorMessages.RSAPI_HELPER_SETUP_ERROR, ex);
            }
        }
Example #12
0
        public static void CreateFolders(List <DTOs.Result <DTOs.Folder> > folders, IRSAPIClient client)
        {
            // store all top-level folders
            List <DTOs.Result <DTOs.Folder> > topLevel = folders.FindAll(x => x.Artifact.ParentArtifact.ArtifactID == _templateRootFolder);

            // create all top-level folders
            foreach (DTOs.Result <DTOs.Folder> f in topLevel)
            {
                DTOs.Folder current   = f.Artifact;
                DTOs.Folder newFolder = CreateFolder(f.Artifact, (int)_targetRootFolder, client);
                if (newFolder != null)
                {
                    // add to running total of created folders
                    _createdFolders.Add(current);
                    // remove from list of folders to create
                    folders.Remove(f);
                    // if there are more folders to create, recurse
                    if (folders.Count > 0)
                    {
                        CheckForChildren(current, newFolder, folders, client);
                    }
                }
                else
                {
                    WorkspaceCreate.retVal.Message = String.Format("Error occurred creating folder {0}", f.Artifact.Name);
                }
            }

            //_logger.LogDebug(String.Format("\r\n{0} total folders created.", _createdFolders.Count));
        }
Example #13
0
        public void Execute_TestFixtureSetup()
        {
            //Setup for testing
            //Setup for testing
            TestHelper helper = new TestHelper();

            servicesManager = helper.GetServicesManager();

            // implement_IHelper
            //create client
            _client        = helper.GetServicesManager().GetProxy <IRSAPIClient>(ConfigurationHelper.ADMIN_USERNAME, ConfigurationHelper.DEFAULT_PASSWORD);
            _eddsDbContext = helper.GetDBContext(-1);

            //Create workspace
            _workspaceId = CreateWorkspace.CreateWorkspaceAsync(_workspaceName, ConfigurationHelper.TEST_WORKSPACE_TEMPLATE_NAME, servicesManager, ConfigurationHelper.ADMIN_USERNAME, ConfigurationHelper.DEFAULT_PASSWORD).Result;
            dbContext    = helper.GetDBContext(_workspaceId);
            _client.APIOptions.WorkspaceID = _workspaceId;

            _rootFolderArtifactId = APIHelpers.GetRootFolderArtifactID(_client, _workspaceName);

            //Import Application containing script, fields, and choices
            Relativity.Test.Helpers.Application.ApplicationHelpers.ImportApplication(_client, _workspaceId, true, FilepathData);

            //Import custodians
            var custodians = GetCustodiansDatatable();

            var identityFieldArtifactId = GetArtifactIDOfCustodianField("Full Name", _workspaceId, _client);

            ImportAPIHelpers.ImportObjects(_workspaceId, "Custodian", identityFieldArtifactId, custodians, String.Empty);

            //Import Documents
            var documents = GetDocumentDataTable(_rootFolderArtifactId, _workspaceId);

            ImportAPIHelpers.CreateDocuments(_workspaceId, _rootFolderArtifactId, documents);
        }
Example #14
0
        public static Int32 GetFieldArtifactID(String fieldname, Int32 workspaceID, IRSAPIClient _client)
        {
            int fieldArtifactId = 0;
            var query           = new Query
            {
                ArtifactTypeID = (Int32)ArtifactType.Field,
                Condition      = new TextCondition("Name", TextConditionEnum.Like, fieldname)
            };
            QueryResult result = null;

            try
            {
                result = _client.Query(_client.APIOptions, query);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: {0}", ex.Message);
            }

            if (result != null)
            {
                fieldArtifactId = result.QueryArtifacts[0].ArtifactID;
            }

            return(fieldArtifactId);
        }
        /// <summary>
        /// This creates the YAML file in the specified dir and uploads it
        /// </summary>
        /// <param name="result"></param>
        private void UploadYamlFileToResources(ParseSqlResult result)
        {
            File.WriteAllText(_yamlFullFilePath, result.Yaml);

            using (IRSAPIClient rsapiClient = GetServiceFactory().CreateProxy <IRSAPIClient>())
            {
                ResourceFileRequest rfRequest = new ResourceFileRequest();

                rfRequest.FullFilePath = _yamlFullFilePath;
                rfRequest.AppGuid      = new Guid(DefaultAppGuid);
                rfRequest.FileName     = Path.GetFileName(_yamlFullFilePath);

                try
                {
                    rsapiClient.PushResourceFiles(rsapiClient.APIOptions, new List <ResourceFileRequest>()
                    {
                        rfRequest
                    });
                    Console.WriteLine($"{nameof(UploadYamlFileToResources)} - Local YAML file ({_yamlFullFilePath}) - was uploaded successfully");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{nameof(UploadYamlFileToResources)} - Could not upload ({_yamlFullFilePath}) - Exception: {ex.Message}");
                }
            }
        }
 public ImagingHelper(IImagingProfileManager imagingProfileManager, IImagingSetManager imagingSetManager, IImagingJobManager imagingJobManager, IRSAPIClient rsapiClient)
 {
     ImagingProfileManager = imagingProfileManager;
     ImagingSetManager     = imagingSetManager;
     ImagingJobManager     = imagingJobManager;
     RsapiClient           = rsapiClient;
 }
Example #17
0
        private static int FindGroupArtifactId(IRSAPIClient rsapiClient, string group)
        {
            int artifactId = 0;

            TextCondition groupCondition = new TextCondition(GroupFieldNames.Name, TextConditionEnum.EqualTo, group);

            Query <Group> queryGroup = new Query <Group>
            {
                Condition = groupCondition
            };

            queryGroup.Fields.Add(new FieldValue(ArtifactQueryFieldNames.ArtifactID));

            try
            {
                QueryResultSet <Group> resultSetGroup = rsapiClient.Repositories.Group.Query(queryGroup, 0);

                if (resultSetGroup.Success && resultSetGroup.Results.Count == 1)
                {
                    artifactId = resultSetGroup.Results.FirstOrDefault().Artifact.ArtifactID;
                }
                else
                {
                    Console.WriteLine("The Query operation failed.{0}{1}", Environment.NewLine, resultSetGroup.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
            return(artifactId);
        }
        public bool DeleteUploadedRequestsFromRelativity(IRSAPIClient proxy, int workspaceID, List <WikitivityUploadsAgent.SingleRequestObject> listOfCompletedUploads)
        {
            proxy.APIOptions.WorkspaceID = workspaceID;

            bool success = false;

            try
            {
                List <Document> DocsToDelete = new List <Document>();
                foreach (var singleDoc in listOfCompletedUploads)
                {
                    DocsToDelete.Add(new Document(singleDoc.ArtifactID));
                }

                var DeleteResultSet = proxy.Repositories.Document.Delete(DocsToDelete);
                if (DeleteResultSet.Success)
                {
                    success = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An error an occurred when deleting completed requests", ex);
            }

            return(success);
        }
Example #19
0
        private static int FindChoiceArtifactId(IRSAPIClient rsapiClient, int choiceType, string value)
        {
            int artifactId = 0;

            WholeNumberCondition choiceTypeCondition                = new WholeNumberCondition(ChoiceFieldNames.ChoiceTypeID, NumericConditionEnum.EqualTo, (int)choiceType);
            TextCondition        choiceNameCondition                = new TextCondition(ChoiceFieldNames.Name, TextConditionEnum.EqualTo, value);
            CompositeCondition   choiceCompositeCondition           = new CompositeCondition(choiceTypeCondition, CompositeConditionEnum.And, choiceNameCondition);
            Query <kCura.Relativity.Client.DTOs.Choice> choiceQuery = new Query <kCura.Relativity.Client.DTOs.Choice>(
                new List <FieldValue>
            {
                new FieldValue(ArtifactQueryFieldNames.ArtifactID)
            },
                choiceCompositeCondition,
                new List <Sort>());

            try
            {
                QueryResultSet <kCura.Relativity.Client.DTOs.Choice> choiceQueryResult = rsapiClient.Repositories.Choice.Query(choiceQuery);

                if (choiceQueryResult.Success && choiceQueryResult.Results.Count == 1)
                {
                    artifactId = choiceQueryResult.Results.FirstOrDefault().Artifact.ArtifactID;
                }
                else
                {
                    Console.WriteLine("The choice could not be found.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
            return(artifactId);
        }
Example #20
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);
            }
        }
Example #21
0
        protected List <RDO> GetRdos <T>(Condition queryCondition = null)
            where T : BaseDto
        {
            Query <RDO> query = new Query <RDO>()
            {
                ArtifactTypeGuid = BaseDto.GetObjectTypeGuid <T>(),
                Condition        = queryCondition
            };

            query.Fields = FieldValue.AllFields;

            QueryResultSet <RDO> results;

            using (IRSAPIClient proxyToWorkspace = CreateProxy())
            {
                try
                {
                    results = invokeWithRetryService.InvokeWithRetry(() => proxyToWorkspace.Repositories.RDO.Query(query));
                }
                catch (Exception ex)
                {
                    throw new ProxyOperationFailedException("Failed in method: " + System.Reflection.MethodInfo.GetCurrentMethod(), ex);
                }
            }

            if (results.Success == false)
            {
                throw new ArgumentException(results.Message);
            }

            return(results.Results.Select <Result <RDO>, RDO>(result => result.Artifact as RDO).ToList());
        }
        public Version GetCurrentApplicationVersion(int workspaceArtifactId, Guid applicationGuid)
        {
            try
            {
                using (IRSAPIClient rsapiClient = GetRsapiClient())
                {
                    rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;
                    RelativityApplication relativityApplication;

                    try
                    {
                        relativityApplication = rsapiClient.Repositories.RelativityApplication.ReadSingle(applicationGuid);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"{Constants.ErrorMessages.QueryApplicationVersionError}. ReadSingle.", ex);
                    }

                    Version relativityApplicationVersion = new Version(relativityApplication.Version);
                    return(relativityApplicationVersion);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorMessages.QueryApplicationVersionError, ex);
            }
        }
Example #23
0
 public SearchHelper(IKeywordSearchManager keywordSearchManager, IdtSearchManager dtSearchManager, IDtSearchIndexManager dtSearchIndexManager, IRSAPIClient rsapiClient)
 {
     KeywordSearchManager = keywordSearchManager;
     DtSearchManager      = dtSearchManager;
     DtSearchIndexManager = dtSearchIndexManager;
     RsapiClient          = rsapiClient;
 }
        public void InstallApplication(int workspaceArtifactId, FileInfo rapFilePath)
        {
            try
            {
                using (IRSAPIClient rsapiClient = GetRsapiClient())
                {
                    rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;
                    List <int>        appsToOverride    = new List <int>();
                    const bool        forceFlag         = true;
                    AppInstallRequest appInstallRequest = new AppInstallRequest(appsToOverride, forceFlag)
                    {
                        FullFilePath = rapFilePath.FullName
                    };

                    appsToOverride.Add(1043043); //todo: testing

                    try
                    {
                        rsapiClient.InstallApplication(rsapiClient.APIOptions, appInstallRequest);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"{Constants.ErrorMessages.InstallApplicationError}. InstallApplication.", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorMessages.InstallApplicationError, ex);
            }
        }
        public static int Create_Group(IRSAPIClient client, String name)
        {
            var clientID = client.APIOptions.WorkspaceID;

            client.APIOptions.WorkspaceID = -1;
            Group newGroup = new Group();

            newGroup.Name = name;
            WriteResultSet <kCura.Relativity.Client.DTOs.Group> resultSet = new WriteResultSet <Group>();

            try
            {
                resultSet = client.Repositories.Group.Create(newGroup);
                if (!resultSet.Success || resultSet.Results.Count == 0)
                {
                    throw new Exception("Group was not found");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured while trying to create a new group" + e);
            }
            var groupartid = resultSet.Results[0].Artifact.ArtifactID;

            client.APIOptions.WorkspaceID = clientID;
            return(groupartid);
        }
        /// <summary>
        /// Retrieves User info by email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private DTOs.User GetUser(string email)
        {
            DTOs.User user;

            Condition userQueryCondition = new TextCondition(UserFieldNames.EmailAddress, TextConditionEnum.EqualTo, email);

            Query <DTOs.User> userQuery = new Query <DTOs.User>(FieldValue.AllFields, userQueryCondition, new List <Sort>());

            QueryResultSet <DTOs.User> resultSet = null;

            using (IRSAPIClient rsapiClient = GetServiceFactory().CreateProxy <IRSAPIClient>())
            {
                rsapiClient.APIOptions = new APIOptions {
                    WorkspaceID = -1
                };

                resultSet = rsapiClient.Repositories.User.Query(userQuery);

                if (resultSet.Success && resultSet.TotalCount > 0)
                {
                    user = resultSet.Results.First().Artifact;
                }
                else
                {
                    throw new Exception($"Could not find user {email}");
                }
            }

            return(user);
        }
        /// <summary>
        /// Will retrieve the data as a string from the YAML file to be parsed later
        /// </summary>
        /// <param name="serviceManager"></param>
        /// <param name="yamlFileArtifactID"></param>
        /// <param name="authToken"></param>
        /// <returns></returns>
        private async Task <string> DownloadYamlData(IServicesMgr serviceManager, int yamlFileArtifactID, string authToken)
        {
            string yamlData = "";

            using (IRSAPIClient rsapiClient = serviceManager.CreateProxy <IRSAPIClient>(ExecutionIdentity.System))
            {
                var domain             = rsapiClient.EndpointUri.Host;
                var urlWIthoutProtocol = String.Format(Constants.URLs.ResourceFileDownload,
                                                       domain,
                                                       yamlFileArtifactID,
                                                       authToken);

                try
                {
                    //https vs http
                    var yamlFileUrl =
                        ((HttpContext.Current.Request.IsSecureConnection) ? Constants.Protocols.Https : Constants.Protocols.Http) +
                        urlWIthoutProtocol;
                    yamlData = await DownloadYamlFileAsync(new Uri(yamlFileUrl));
                }
                catch (Exception ex)
                {
                    _logHelper.LogError(ex, $"DAPI - {nameof(DownloadYamlData)} - Error attempting to download Yaml file: {ex}");
                }
            }

            return(yamlData);
        }
        /// <summary>
        /// Adds the user to the DynamicAPI Group for permissions
        /// </summary>
        /// <param name="groupId"></param>
        private void AddAdminUserToGroup(int groupId)
        {
            using (IRSAPIClient rsapiClient = GetServiceFactory().CreateProxy <IRSAPIClient>())
            {
                DTOs.User user = GetUser(_userName);
                user.Groups.Add(new Group(groupId));
                WriteResultSet <DTOs.User> userUpdateResults = null;

                try
                {
                    userUpdateResults = rsapiClient.Repositories.User.Update(user);

                    if (userUpdateResults.Success)
                    {
                        Console.WriteLine($"Added user to DynamicAPI Group");
                    }
                    else
                    {
                        Console.WriteLine($"Unable to add user to DynamicAPI Group: {userUpdateResults.Message}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An error occurred updating the user: {ex.Message}");
                }
            }
        }
Example #29
0
        static bool?VerifyEmptyTarget(IRSAPIClient client)
        {
            // build the query / condition
            DTOs.Query <DTOs.Folder> query = new DTOs.Query <DTOs.Folder>();

            // query for the folders
            DTOs.QueryResultSet <DTOs.Folder> resultSet = new DTOs.QueryResultSet <DTOs.Folder>();
            try
            {
                resultSet = client.Repositories.Folder.Query(query, 0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Exception:\r\n{0}\r\n{1}", ex.Message, ex.InnerException));
                return(null);
            }

            // check for success
            if (resultSet.Success)
            {
                if (resultSet.Results.Count == 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                Console.WriteLine("Query was not successful.");
                return(null);
            }
        }
Example #30
0
        public static RDO RetrieveJob(IServicesMgr servicesMgr, int workspaceArtifactId, int jobArtifactId)
        {
            RDO jobRdo;

            try
            {
                using (IRSAPIClient rsapiClient = servicesMgr.CreateProxy <IRSAPIClient>(ExecutionIdentity.System))
                {
                    rsapiClient.APIOptions.WorkspaceID = workspaceArtifactId;
                    try
                    {
                        jobRdo = rsapiClient.Repositories.RDO.ReadSingle(jobArtifactId);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"{Constants.ErrorMessages.RETRIEVE_APPLICATION_JOB_ERROR}. ReadSingle. [{nameof(workspaceArtifactId)}= {workspaceArtifactId}, {nameof(jobArtifactId)}= {jobArtifactId}]", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.ErrorMessages.RETRIEVE_APPLICATION_JOB_ERROR, ex);
            }
            return(jobRdo);
        }