Example #1
0
        public async Task GetProjectSettingsExecutor_DataExists(ProjectSettingsType settingsType)
        {
            var settings = string.Empty;

            var projectRepo     = new Mock <IProjectRepository>();
            var projectSettings = new ProjectSettings {
                ProjectUid = _projectUid.ToString(), Settings = settings, ProjectSettingsType = settingsType, UserID = _userUid.ToString()
            };

            projectRepo.Setup(ps => ps.GetProjectSettings(It.IsAny <string>(), _userUid.ToString(), settingsType)).ReturnsAsync(projectSettings);

            var projectList      = CreateProjectListModel(_customerTrn, _projectTrn);
            var cwsProjectClient = new Mock <ICwsProjectClient>();

            cwsProjectClient.Setup(ps => ps.GetProjectsForCustomer(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <bool>(), It.IsAny <CwsProjectType?>(), It.IsAny <ProjectStatus?>(), It.IsAny <bool>(), It.IsAny <IHeaderDictionary>())).ReturnsAsync(projectList);

            var configStore             = ServiceProvider.GetRequiredService <IConfigurationStore>();
            var logger                  = ServiceProvider.GetRequiredService <ILoggerFactory>();
            var serviceExceptionHandler = ServiceProvider.GetRequiredService <IServiceExceptionHandler>();

            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(_projectUid.ToString(), settings, settingsType);

            var executor = RequestExecutorContainerFactory.Build <GetProjectSettingsExecutor>
                               (logger, configStore, serviceExceptionHandler,
                               _customerUid.ToString(), _userUid.ToString(),
                               projectRepo: projectRepo.Object, cwsProjectClient: cwsProjectClient.Object);
            var result = await executor.ProcessAsync(projectSettingsRequest) as ProjectSettingsResult;

            Assert.NotNull(result);
            Assert.Equal(_projectUid.ToString(), result.ProjectUid);
            Assert.Null(result.Settings);
            Assert.Equal(settingsType, result.ProjectSettingsType);
        }
Example #2
0
        public async Task GetProjectSettingsExecutor_NoSettingsExists(ProjectSettingsType settingsType)
        {
            var customerUid      = Guid.NewGuid().ToString();
            var userId           = Guid.NewGuid().ToString();
            var userEmailAddress = "*****@*****.**";

            var project = await ExecutorTestFixture.CreateCustomerProject(customerUid);

            Assert.NotNull(project);

            var settings = string.Empty;
            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(project.Id, settings, settingsType);

            var executor =
                RequestExecutorContainerFactory.Build <GetProjectSettingsExecutor>
                    (ExecutorTestFixture.Logger, ExecutorTestFixture.ConfigStore, ExecutorTestFixture.ServiceExceptionHandler,
                    customerUid, userId, userEmailAddress, ExecutorTestFixture.CustomHeaders(customerUid),
                    projectRepo: ExecutorTestFixture.ProjectRepo, cwsProjectClient: ExecutorTestFixture.CwsProjectClient);
            var projectSettingsResult = await executor.ProcessAsync(projectSettingsRequest) as ProjectSettingsResult;

            Assert.NotNull(projectSettingsResult);
            Assert.Equal(project.Id, projectSettingsResult.ProjectUid);
            Assert.Null(projectSettingsResult.Settings);
            Assert.Equal(settingsType, projectSettingsResult.ProjectSettingsType);
        }
Example #3
0
 /// <summary>
 /// Constructor with parameters
 /// </summary>
 public ProjectSettingsResult(
     string projectUid, JObject settings, ProjectSettingsType projectSettingsType)
 {
     ProjectUid          = projectUid;
     ProjectSettingsType = projectSettingsType;
     Settings            = settings;
 }
Example #4
0
        public async Task UpsertProjectSettingsExecutor(ProjectSettingsType settingsType)
        {
            var settings = settingsType != ProjectSettingsType.ImportedFiles ? @"{firstValue: 10, lastValue: 20}" : @"[{firstValue: 10, lastValue: 20}, {firstValue: 20, lastValue: 40}]";

            var projectRepo     = new Mock <IProjectRepository>();
            var projectSettings = new ProjectSettings {
                ProjectUid = _projectUid.ToString(), Settings = settings, ProjectSettingsType = settingsType, UserID = _userUid.ToString()
            };

            projectRepo.Setup(ps => ps.GetProjectSettings(It.IsAny <string>(), _userUid.ToString(), settingsType)).ReturnsAsync(projectSettings);
            projectRepo.Setup(ps => ps.StoreEvent(It.IsAny <UpdateProjectSettingsEvent>())).ReturnsAsync(1);

            var projectList      = CreateProjectListModel(_customerTrn, _projectTrn);
            var cwsProjectClient = new Mock <ICwsProjectClient>();

            cwsProjectClient.Setup(ps => ps.GetProjectsForCustomer(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <bool>(), It.IsAny <CwsProjectType?>(), It.IsAny <ProjectStatus?>(), It.IsAny <bool>(), It.IsAny <IHeaderDictionary>())).ReturnsAsync(projectList);

            var configStore             = ServiceProvider.GetRequiredService <IConfigurationStore>();
            var logger                  = ServiceProvider.GetRequiredService <ILoggerFactory>();
            var serviceExceptionHandler = ServiceProvider.GetRequiredService <IServiceExceptionHandler>();

            var productivity3dV2ProxyCompaction = new Mock <IProductivity3dV2ProxyCompaction>();

            productivity3dV2ProxyCompaction.Setup(r => r.ValidateProjectSettings(It.IsAny <ProjectSettingsRequest>(),
                                                                                 It.IsAny <HeaderDictionary>())).ReturnsAsync(new BaseMasterDataResult());

            var executor = RequestExecutorContainerFactory.Build <UpsertProjectSettingsExecutor>
                               (logger, configStore, serviceExceptionHandler,
                               _customerUid.ToString(), _userUid.ToString(), null, null,
                               productivity3dV2ProxyCompaction: productivity3dV2ProxyCompaction.Object,
                               projectRepo: projectRepo.Object, cwsProjectClient: cwsProjectClient.Object);
            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(_projectUid.ToString(), settings, settingsType);
            var result = await executor.ProcessAsync(projectSettingsRequest) as ProjectSettingsResult;

            Assert.NotNull(result);
            Assert.Equal(_projectUid.ToString(), result.ProjectUid);
            Assert.NotNull(result.Settings);
            Assert.Equal(settingsType, result.ProjectSettingsType);

            if (settingsType == ProjectSettingsType.Targets || settingsType == ProjectSettingsType.Colors)
            {
                var tempSettings = JsonConvert.DeserializeObject <JObject>(settings);

                Assert.Equal(tempSettings["firstValue"], result.Settings["firstValue"]);
                Assert.Equal(tempSettings["lastValue"], result.Settings["lastValue"]);
            }
            else
            {
                var tempObj     = JsonConvert.DeserializeObject <JArray>(settings);
                var tempJObject = new JObject {
                    ["importedFiles"] = tempObj
                };

                Assert.Equal(tempJObject["importedFiles"][0]["firstValue"], result.Settings["importedFiles"][0]["firstValue"]);
                Assert.Equal(tempJObject["importedFiles"][0]["lastValue"], result.Settings["importedFiles"][0]["lastValue"]);
                Assert.Equal(tempJObject["importedFiles"][1]["firstValue"], result.Settings["importedFiles"][1]["firstValue"]);
                Assert.Equal(tempJObject["importedFiles"][1]["lastValue"], result.Settings["importedFiles"][1]["lastValue"]);
            }
        }
Example #5
0
        public void UpsertProjectSettingsExecutor_InvalidProjectSettings(ProjectSettingsType settingsType)
        {
            var projectUid             = Guid.NewGuid().ToString();
            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(projectUid, null, settingsType);
            var ex = Assert.Throws <ServiceException>(() => projectSettingsRequest.Validate());

            Assert.NotEqual(-1, ex.GetContent.IndexOf("2073", StringComparison.Ordinal));
            Assert.NotEqual(-1, ex.GetContent.IndexOf("ProjectSettings cannot be null.", StringComparison.Ordinal));
        }
Example #6
0
        public void GetProjectSettingsExecutor_InvalidProjectUid(ProjectSettingsType settingsType)
        {
            var projectUid             = string.Empty;
            var settings               = string.Empty;
            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(projectUid, settings, settingsType);
            var ex = Assert.Throws <ServiceException>(() => projectSettingsRequest.Validate());

            Assert.NotEqual(-1, ex.GetContent.IndexOf("2005", StringComparison.Ordinal));
            Assert.NotEqual(-1, ex.GetContent.IndexOf("Missing ProjectUID.", StringComparison.Ordinal));
        }
Example #7
0
 /// <summary>
 /// At this stage 2 types
 /// </summary>
 /// <param name="projectUid"></param>
 /// <param name="userId"></param>
 /// <param name="projectSettingsType"></param>
 /// <returns></returns>
 public async Task <ProjectSettings> GetProjectSettings(string projectUid, string userId,
                                                        ProjectSettingsType projectSettingsType)
 {
     return((await QueryWithAsyncPolicy <ProjectSettings>(@"SELECT 
         fk_ProjectUID AS ProjectUid, fk_ProjectSettingsTypeID AS ProjectSettingsType, Settings, UserID, LastActionedUTC
       FROM ProjectSettings
       WHERE fk_ProjectUID = @ProjectUid
         AND UserID = @UserID
         AND fk_ProjectSettingsTypeID = @ProjectSettingsType
       ORDER BY fk_ProjectUID, UserID, fk_ProjectSettingsTypeID",
                                                          new { ProjectUid = projectUid, UserID = userId, ProjectSettingsType = projectSettingsType }))
            .FirstOrDefault());
 }
Example #8
0
        public async Task UpsertProjectSettingsExecutor_Exists(ProjectSettingsType settingsType)
        {
            var customerUid      = Guid.NewGuid().ToString();
            var userId           = Guid.NewGuid().ToString();
            var userEmailAddress = "*****@*****.**";
            var settings         = "blah";
            var settingsUpdated  = settingsType != ProjectSettingsType.ImportedFiles ? @"{firstValue: 10, lastValue: 20}" : @"[{firstValue: 10, lastValue: 20}, {firstValue: 20, lastValue: 40}]";

            var project = await ExecutorTestFixture.CreateCustomerProject(customerUid);

            Assert.NotNull(project);

            var isCreatedOk = ExecutorTestFixture.CreateProjectSettings(project.Id, userId, settings, settingsType);

            Assert.True(isCreatedOk, "created projectSettings");

            var projectSettingsRequest =
                ProjectSettingsRequest.CreateProjectSettingsRequest(project.Id, settingsUpdated, settingsType);

            var executor = RequestExecutorContainerFactory.Build <UpsertProjectSettingsExecutor>
                               (ExecutorTestFixture.Logger, ExecutorTestFixture.ConfigStore, ExecutorTestFixture.ServiceExceptionHandler,
                               customerUid, userId, userEmailAddress, ExecutorTestFixture.CustomHeaders(customerUid),
                               productivity3dV2ProxyCompaction: ExecutorTestFixture.Productivity3dV2ProxyCompaction,
                               projectRepo: ExecutorTestFixture.ProjectRepo, cwsProjectClient: ExecutorTestFixture.CwsProjectClient);
            var result = await executor.ProcessAsync(projectSettingsRequest) as ProjectSettingsResult;

            Assert.NotNull(result);
            Assert.Equal(project.Id, result.ProjectUid);
            Assert.Equal(settingsType, result.ProjectSettingsType);

            if (settingsType == ProjectSettingsType.Targets || settingsType == ProjectSettingsType.Colors)
            {
                var tempSettings = JsonConvert.DeserializeObject <JObject>(settingsUpdated);

                Assert.Equal(tempSettings["firstValue"], result.Settings["firstValue"]);
                Assert.Equal(tempSettings["lastValue"], result.Settings["lastValue"]);
            }
            else
            {
                var tempObj     = JsonConvert.DeserializeObject <JArray>(settingsUpdated);
                var tempJObject = new JObject {
                    ["importedFiles"] = tempObj
                };

                Assert.Equal(tempJObject["importedFiles"][0]["firstValue"], result.Settings["importedFiles"][0]["firstValue"]);
                Assert.Equal(tempJObject["importedFiles"][0]["lastValue"], result.Settings["importedFiles"][0]["lastValue"]);
                Assert.Equal(tempJObject["importedFiles"][1]["firstValue"], result.Settings["importedFiles"][1]["firstValue"]);
                Assert.Equal(tempJObject["importedFiles"][1]["lastValue"], result.Settings["importedFiles"][1]["lastValue"]);
            }
        }
Example #9
0
        public static bool CreateProjectSettings(string projectUid, string userId, string settings, ProjectSettingsType settingsType)
        {
            var actionUtc = new DateTime(2017, 1, 1, 2, 30, 3);
            var createProjectSettingsEvent = new UpdateProjectSettingsEvent()
            {
                ProjectUID          = new Guid(projectUid),
                UserID              = userId,
                Settings            = settings,
                ProjectSettingsType = settingsType,
                ActionUTC           = actionUtc
            };

            Console.WriteLine($"Create project settings event created");
            Console.WriteLine(
                $"UpdateProjectSettingsEvent ={JsonConvert.SerializeObject(createProjectSettingsEvent)}))')");

            var projectEvent    = createProjectSettingsEvent;
            var projectSettings = new ProjectSettings
            {
                ProjectUid          = projectEvent.ProjectUID.ToString(),
                ProjectSettingsType = projectEvent.ProjectSettingsType,
                Settings            = projectEvent.Settings,
                UserID          = projectEvent.UserID,
                LastActionedUtc = projectEvent.ActionUTC
            };

            Console.WriteLine(
                $"projectSettings after cast/convert ={JsonConvert.SerializeObject(projectSettings)}))')");
            ProjectRepo.StoreEvent(createProjectSettingsEvent).Wait();
            var g = ProjectRepo.GetProjectSettings(projectUid, userId, settingsType); g.Wait();

            return(g.Result != null ? true : false);
        }
Example #10
0
        /// <summary>
        /// Validates the Settings for the project.
        /// </summary>
        public async Task <BaseMasterDataResult> ValidateProjectSettings(Guid projectUid, string projectSettings, ProjectSettingsType settingsType, IHeaderDictionary customHeaders = null)
        {
            log.LogDebug($"{nameof(ValidateProjectSettings)} 2) projectUid: {projectUid} settings type: {settingsType}");
            var queryParams = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("projectUid", projectUid.ToString()),
                new KeyValuePair <string, string>("projectSettings", JsonConvert.SerializeObject(projectSettings)),
                new KeyValuePair <string, string>("settingsType", settingsType.ToString())
            };
            var response = await GetMasterDataItemServiceDiscoveryNoCache <BaseMasterDataResult>("/validatesettings", customHeaders, queryParams);

            log.LogDebug($"{nameof(ValidateProjectSettings)} 2) response: {(response == null ? null : JsonConvert.SerializeObject(response).Truncate(LogMaxChar))}");
            return(response);
        }
Example #11
0
        public async Task GetProjectSettingsExecutor_InvalidCustomerProjectRelationship(ProjectSettingsType settingsType)
        {
            var customerUidOfProject = Guid.NewGuid().ToString();
            var customerUidSomeOther = Guid.NewGuid().ToString();
            var userId           = Guid.NewGuid().ToString();
            var userEmailAddress = "*****@*****.**";
            var settings         = string.Empty;

            var project = await ExecutorTestFixture.CreateCustomerProject(customerUidOfProject);

            Assert.NotNull(project);

            var projectSettingsRequest = ProjectSettingsRequest.CreateProjectSettingsRequest(project.Id, settings, settingsType);

            var executor =
                RequestExecutorContainerFactory.Build <GetProjectSettingsExecutor>
                    (ExecutorTestFixture.Logger, ExecutorTestFixture.ConfigStore, ExecutorTestFixture.ServiceExceptionHandler,
                    customerUidSomeOther, userId, userEmailAddress, ExecutorTestFixture.CustomHeaders(customerUidOfProject),
                    projectRepo: ExecutorTestFixture.ProjectRepo, cwsProjectClient: ExecutorTestFixture.CwsProjectClient);
            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await executor.ProcessAsync(projectSettingsRequest)).ConfigureAwait(false);

            Assert.NotEqual(-1, ex.GetContent.IndexOf("2001", StringComparison.Ordinal));
            Assert.NotEqual(-1, ex.GetContent.IndexOf("No access to the project for a customer or the project does not exist.", StringComparison.Ordinal));
        }
Example #12
0
        private async Task <T> GetProjectSettings <T>(string projectUid, string userId, IHeaderDictionary customHeaders, ProjectSettingsType settingsType,
                                                      IServiceExceptionHandler serviceExceptionHandler) where T : IValidatable, IDefaultSettings, new()
        {
            T ps = default;

            var uri = string.Empty;

            switch (settingsType)
            {
            case ProjectSettingsType.Targets:
                uri = $"/projectsettings/{projectUid}";
                break;

            case ProjectSettingsType.Colors:
                uri = $"/projectcolors/{projectUid}";
                break;

            default:
                throw new ServiceException(HttpStatusCode.BadRequest, new ContractExecutionResult(-10, "Unsupported project settings type."));
            }

            var result = await GetMasterDataItemServiceDiscovery <ProjectSettingsResult>(uri, $"{projectUid}{settingsType}", userId, customHeaders);

            if (result.Code == ContractExecutionStatesEnum.ExecutedSuccessfully)
            {
                var jsonSettings = result.Settings;
                if (jsonSettings != null)
                {
                    try
                    {
                        ps = jsonSettings.ToObject <T>();
                        if (settingsType == ProjectSettingsType.Colors)
                        {
                            (ps as CompactionProjectSettingsColors).UpdateCmvDetailsColorsIfRequired();
                        }
                        ps.Validate(serviceExceptionHandler);
                    }
                    catch (Exception ex)
                    {
                        log.LogInformation(
                            $"JObject conversion to Project Settings validation failure for projectUid {projectUid}. Error is {ex.Message}");
                    }
                }
                else
                {
                    log.LogDebug($"No Project Settings for projectUid {projectUid}. Using defaults.");
                }
            }
            else
            {
                log.LogWarning($"Failed to get project settings, using default values: {result.Code}, {result.Message}");
            }

            if (ps == null)
            {
                ps = new T();
                ps.Defaults();
            }
            return(ps);
        }
Example #13
0
 /// <summary>
 /// Create instance of ProjectSettingsRequest
 /// </summary>
 public static ProjectSettingsRequest CreateProjectSettingsRequest(string projectUid, string settings, ProjectSettingsType projectSettingsType)
 {
     return(new ProjectSettingsRequest
     {
         projectUid = projectUid,
         Settings = settings,
         ProjectSettingsType = projectSettingsType
     });
 }
Example #14
0
 /// <summary>
 /// Creates an instance of the ProjectSettingsRequest class and populate it.
 /// </summary>
 /// <param name="projectUid"></param>
 /// <param name="settings"></param>
 /// <param name="projectSettingsType"></param>
 /// <returns>An instance of the ProjectSettingsRequest class.</returns>
 public ProjectSettingsRequest CreateProjectSettingsRequest(string projectUid, string settings, ProjectSettingsType projectSettingsType)
 {
     return(ProjectSettingsRequest.CreateProjectSettingsRequest(projectUid, settings, projectSettingsType));
 }
Example #15
0
        private async Task <ProjectSettingsResult> GetProjectSettingsForType(string projectUid, ProjectSettingsType settingsType)
        {
            if (string.IsNullOrEmpty(projectUid))
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 68);
            }
            LogCustomerDetails("GetProjectSettings", projectUid);

            var projectSettingsRequest = _requestFactory.Create <ProjectSettingsRequestHelper>(r => r
                                                                                               .CustomerUid(CustomerUid))
                                         .CreateProjectSettingsRequest(projectUid, string.Empty, settingsType);

            projectSettingsRequest.Validate();

            var result = (await WithServiceExceptionTryExecuteAsync(() =>
                                                                    RequestExecutorContainerFactory
                                                                    .Build <GetProjectSettingsExecutor>(LoggerFactory, ConfigStore, ServiceExceptionHandler,
                                                                                                        CustomerUid, UserId, headers: customHeaders,
                                                                                                        projectRepo: ProjectRepo, cwsProjectClient: CwsProjectClient)
                                                                    .ProcessAsync(projectSettingsRequest)
                                                                    )) as ProjectSettingsResult;

            Logger.LogResult(this.ToString(), projectUid, result);
            return(result);
        }