Esempio n. 1
0
        public async Task CS_CoordinateSystemControllerPostSuccessful()
        {
            byte[] csFileContent = { 0, 1, 2, 3, 4, 5, 6, 7 };

            var request = new CoordinateSystemFile(PD_MODEL_ID, csFileContent, "dummy.dc");

            // Create the mock PDSClient with successful result...
            var mockRaptorClient = new Mock <IASNodeClient>();
            var mockLogger       = new Mock <ILoggerFactory>();
            var mockConfigStore  = new Mock <IConfigurationStore>();

            var raptorResult = TASNodeErrorStatus.asneOK;

            TCoordinateSystemSettings csSettings;

            mockRaptorClient.Setup(prj => prj.PassSelectedCoordinateSystemFile(
                                       new MemoryStream(request.CSFileContent),
                                       request.CSFileName,
                                       request.ProjectId ?? VelociraptorConstants.NO_PROJECT_ID, out csSettings)).Returns(raptorResult);

            // Create an executor...
            var executor = RequestExecutorContainerFactory.Build <CoordinateSystemExecutorPost>(mockLogger.Object, mockRaptorClient.Object, configStore: mockConfigStore.Object);

            var result = await executor.ProcessAsync(request);

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Message == ContractExecutionResult.DefaultMessage, result.Message);
        }
Esempio n. 2
0
        public void ProjectStatisticsExecutor_Raptor_Success()
        {
            var excludedSurveyedSurfaceUids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            var excludedSurveyedSurfaceIds  = new long[] { 444, 777, 888 };
            var request = new ProjectStatisticsMultiRequest(Guid.NewGuid(), 123, excludedSurveyedSurfaceUids, excludedSurveyedSurfaceIds);

            var statistics = new TICDataModelStatistics
            {
                StartTime         = DateTime.UtcNow.AddDays(-5),
                EndTime           = DateTime.UtcNow.AddDays(-1),
                CellSize          = 32.5,
                IndexOriginOffset = 10,
                Extents           = new T3DBoundingWorldExtent(10, 500, 0, 20, 510, 0)
            };

            var raptorClient = new Mock <IASNodeClient>();

            raptorClient
            .Setup(x => x.GetDataModelStatistics(request.ProjectId, It.IsAny <TSurveyedSurfaceID[]>(), out statistics))
            .Returns(true);

            var configStore = new Mock <IConfigurationStore>();

            configStore.Setup(x => x.GetValueBool("ENABLE_TREX_GATEWAY_PROJECTSTATISTICS")).Returns(false);

            var executor = RequestExecutorContainerFactory
                           .Build <ProjectStatisticsExecutor>(logger, raptorClient.Object, configStore: configStore.Object);
            var result = executor.ProcessAsync(request).Result as ProjectStatisticsResult;

            Assert.IsNotNull(result, "Result should not be null");
            Assert.AreEqual(statistics.CellSize, result.cellSize, "Wrong CellSize");
            Assert.AreEqual(statistics.Extents.MaxX, result.extents.MaxX, "Wrong MaxX extent");
        }
Esempio n. 3
0
        public async Task <CompactionCmvDetailedResult> GetCmvDetails(
            [FromQuery] Guid projectUid,
            [FromQuery] Guid?filterUid)
        {
            Log.LogInformation("GetCmvDetails: " + Request.QueryString);

            var request = await GetCmvRequest(projectUid, filterUid, true);

            request.Validate();

            try
            {
                var result1 = await RequestExecutorContainerFactory.Build <DetailedCMVExecutor>(LoggerFactory,
#if RAPTOR
                                                                                                RaptorClient,
#endif
                                                                                                configStore : ConfigStore, trexCompactionDataProxy : TRexCompactionDataProxy, customHeaders : CustomHeaders,
                                                                                                userId : GetUserId(), fileImportProxy : FileImportProxy)
                              .ProcessAsync(request) as CMVDetailedResult;

                if (result1 != null && result1.ConstantTargetCmv == -1)
                {
                    var result2 = await RequestExecutorContainerFactory.Build <SummaryCMVExecutor>(LoggerFactory,
#if RAPTOR
                                                                                                   RaptorClient,
#endif
                                                                                                   configStore : ConfigStore, trexCompactionDataProxy : TRexCompactionDataProxy, customHeaders : CustomHeaders,
                                                                                                   userId : GetUserId(), fileImportProxy : FileImportProxy)
                                  .ProcessAsync(request) as CMVSummaryResult;

                    if (result2 != null && result2.HasData())
                    {
                        result1.ConstantTargetCmv   = result2.ConstantTargetCmv;
                        result1.IsTargetCmvConstant = result2.IsTargetCmvConstant;
                    }
                }

                var returnResult = new CompactionCmvDetailedResult(result1, request.CmvSettings);

                Log.LogInformation("GetCmvDetails result: " + JsonConvert.SerializeObject(returnResult));

                return(returnResult);
            }
            catch (ServiceException exception)
            {
#if RAPTOR
                var statusCode = (TASNodeErrorStatus)exception.GetResult.Code == TASNodeErrorStatus.asneFailedToRequestDatamodelStatistics ? HttpStatusCode.NoContent : HttpStatusCode.BadRequest;

                throw new ServiceException(statusCode,
                                           new ContractExecutionResult(exception.GetResult.Code, exception.GetResult.Message));
#else
                throw new ServiceException(HttpStatusCode.BadRequest,
                                           new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError, exception.Message));
#endif
            }
            finally
            {
                Log.LogInformation("GetCmvDetails returned: " + Response.StatusCode);
            }
        }
Esempio n. 4
0
        public async Task CompactionCellDatumExecutor_TRex_NoCoords()
        {
            var expectedResult = new CompactionCellDatumResult(DisplayMode.Height, CellDatumReturnCode.ValueFound, 5.23,
                                                               DateTime.UtcNow.AddHours(-4.5), 12345, 9876);

            var tRexProxy = new Mock <ITRexCompactionDataProxy>();

            tRexProxy.Setup(x => x.SendDataPostRequest <CompactionCellDatumResult, CellDatumTRexRequest>(
                                It.IsAny <CellDatumTRexRequest>(),
                                It.IsAny <string>(),
                                It.IsAny <IDictionary <string, string> >(), false))
            .ReturnsAsync(expectedResult);

            var configStore = new Mock <IConfigurationStore>();

            configStore.Setup(x => x.GetValueBool("ENABLE_TREX_GATEWAY_CELL_DATUM")).Returns(true);

            var executor = RequestExecutorContainerFactory
                           .Build <CompactionCellDatumExecutor>(logger, configStore: configStore.Object, trexCompactionDataProxy: tRexProxy.Object);

            var request =
                new CellDatumRequest(0, Guid.NewGuid(), expectedResult.displayMode, null, new Point(expectedResult.northing, expectedResult.easting), null, null, null);

            var ex = await Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request));

            Assert.AreEqual(HttpStatusCode.BadRequest, ex.Code);
            Assert.AreEqual("No WGS84 coordinates provided", ex.GetResult.Message);
        }
Esempio n. 5
0
        public void CompactionCellDatumExecutorSuccessNoNECoordinates()
        {
            var request =
                new CellDatumRequest(0, null, DisplayMode.CCV, new WGSPoint(0.84, -1.75), null, null, null, null);

            TCellProductionData data = new TCellProductionData
            {
                DisplayMode = (int)request.DisplayMode,
                Value       = 500,
                ReturnCode  = 0
            };

            var raptorClient = new Mock <IASNodeClient>();
            var configStore  = new Mock <IConfigurationStore>();

            raptorClient.Setup(x => x.GetCellProductionData(
                                   request.ProjectId.Value,
                                   (int)RaptorConverters.convertDisplayMode(request.DisplayMode),
                                   request.GridPoint != null ? request.GridPoint.x : 0.0,
                                   request.GridPoint != null ? request.GridPoint.y : 0.0,
                                   It.IsAny <TWGS84Point>(),
                                   request.LLPoint == null,
                                   It.IsAny <TICFilterSettings>(),
                                   It.IsAny <TICLiftBuildSettings>(),
                                   It.IsAny <TVLPDDesignDescriptor>(),
                                   out data))
            .Returns(true);

            var executor = RequestExecutorContainerFactory
                           .Build <CompactionCellDatumExecutor>(logger, raptorClient.Object, configStore: configStore.Object);

            Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request), "On Cell Datum request. Failed to process coordinate conversion request.");
        }
Esempio n. 6
0
        public async Task <ContractExecutionResult> GetDesignBoundaries([FromQuery] Guid projectUid, [FromQuery] double?tolerance)
        {
            Log.LogInformation($"{nameof(GetDesignBoundaries)}: " + Request.QueryString);

            var projectId = await((RaptorPrincipal)User).GetLegacyProjectId(projectUid);

            tolerance ??= DesignBoundariesRequest.BOUNDARY_POINTS_INTERVAL;

            var request = new DesignBoundariesRequest(projectId, projectUid, tolerance.Value);

            request.Validate();

            var fileList = await FileImportProxy.GetFiles(projectUid.ToString(), GetUserId(), Request.Headers.GetCustomHeaders());

            fileList = fileList?.Where(f => f.ImportedFileType == ImportedFileType.DesignSurface && f.IsActivated).ToList();

            return(await RequestExecutorContainerFactory.Build <DesignExecutor>(
                       LoggerFactory,
                       configStore : ConfigStore,
                       fileList : fileList,
                       trexCompactionDataProxy : TRexCompactionDataProxy,
                       userId : GetUserId(),
                       fileImportProxy : FileImportProxy)
                   .ProcessAsync(request));
        }
Esempio n. 7
0
        public async Task UpdatePreferenceKeyExecutor_MissingKeyUID()
        {
            const string keyName = "some key";
            var          keyUid  = Guid.NewGuid();

            var prefKeyDatabase = new PrefKeyDataModel
            {
                KeyName          = keyName,
                PreferenceKeyUID = keyUid.ToString(),
                PreferenceKeyID  = 12345
            };

            mockPrefRepo.Setup(p => p.GetPreferenceKey(null, keyName))
            .ReturnsAsync((PrefKeyDataModel)null);

            var prefEvent = new UpdatePreferenceKeyEvent
            {
                PreferenceKeyName = "some other key",
                PreferenceKeyUID  = keyUid
            };

            mockPrefRepo.Setup(p => p.StoreEvent(prefEvent))
            .ReturnsAsync(0);

            var executor = RequestExecutorContainerFactory.Build <UpdatePreferenceKeyExecutor>
                               (Logger, ServiceExceptionHandler, mockPrefRepo.Object);
            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await executor.ProcessAsync(prefEvent));

            Assert.Equal(HttpStatusCode.InternalServerError, ex.Code);
            var result = ex.GetResult;

            Assert.Equal(2003, result.Code);
            Assert.Equal("Unable to update preference key. ", result.Message);
        }
Esempio n. 8
0
        public async Task <CoordinateSystemSettings> Post([FromBody] CoordinateSystemFile request)
        {
            request.Validate();

            return(await RequestExecutorContainerFactory.Build <CoordinateSystemExecutorPost>(logger,
                                                                                              configStore : configStore, trexCompactionDataProxy : trexCompactionDataProxy, customHeaders : CustomHeaders).ProcessAsync(request) as CoordinateSystemSettings);
        }
Esempio n. 9
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);
        }
Esempio n. 10
0
        private async Task PairUpAssetIdentifiers(ProjectIDs projectIds, List <AssetOnDesignPeriod> assetOnDesignPeriods)
        {
            if (assetOnDesignPeriods == null || assetOnDesignPeriods.Count == 0)
            {
                return;
            }

            if (await RequestExecutorContainerFactory.Build <GetMachineIdsExecutor>(loggerFactory,
#if RAPTOR
                                                                                    raptorClient,
#endif
                                                                                    configStore: configStore, trexCompactionDataProxy: trexCompactionDataProxy,
                                                                                    customHeaders: customHeaders, customerUid: customerUid,
                                                                                    userId: userId, fileImportProxy: fileImportProxy)
                .ProcessAsync(projectIds) is MachineExecutionResult machineExecutionResult && machineExecutionResult.MachineStatuses.Count > 0)
            {
                foreach (var assetMatch in machineExecutionResult.MachineStatuses)
                {
                    foreach (var assetOnDesignPeriod in assetOnDesignPeriods.FindAll(a => a.AssetUid == assetMatch.AssetUid))
                    {
                        assetOnDesignPeriod.MachineId = assetMatch.AssetId;
                    }
                }
            }
        }
Esempio n. 11
0
        public async Task <CoordinateConversionResult> Post([FromBody] CoordinateConversionRequest request)
        {
            request.Validate();

            return(await RequestExecutorContainerFactory.Build <CoordinateConversionExecutor>(logger,
                                                                                              configStore : configStore, trexCompactionDataProxy : trexCompactionDataProxy, customHeaders : CustomHeaders).ProcessAsync(request) as CoordinateConversionResult);
        }
Esempio n. 12
0
        private async Task <CompactionProfileResult <CompactionProfileVertex> > MockGetProfile(DesignProfile designProfile)
        {
            var raptorClient = new Mock <IASNodeClient>();
            var configStore  = new Mock <IConfigurationStore>();

            var ms = new MemoryStream();
            //No serialization so do it by hand
            BinaryWriter writer = new BinaryWriter(ms);

            writer.Write(BitConverter.GetBytes(designProfile.vertices.Count));
            foreach (var vertex in designProfile.vertices)
            {
                writer.Write(BitConverter.GetBytes(vertex.station));
                writer.Write(BitConverter.GetBytes(vertex.elevation));
            }
            writer.Write(BitConverter.GetBytes(designProfile.GridDistanceBetweenProfilePoints));
            ms.Position = 0;
            raptorClient
            .Setup(x => x.GetDesignProfile(It.IsAny <TDesignProfilerServiceRPCVerb_CalculateDesignProfile_Args>()))
            .Returns(ms);

            var request = new CompactionProfileDesignRequest(
                1234, null, null, null, -1, null, new ProfileGridPoints(), new ProfileLLPoints(), ValidationConstants3D.MIN_STATION, ValidationConstants3D.MIN_STATION);

            var executor = RequestExecutorContainerFactory
                           .Build <CompactionDesignProfileExecutor>(logger, raptorClient.Object, configStore: configStore.Object);
            var result = await executor.ProcessAsync(request) as CompactionProfileResult <CompactionProfileVertex>;

            return(result);
        }
Esempio n. 13
0
        /// <summary>
        /// Sets activated state for imported files.
        /// </summary>
        protected async Task <IEnumerable <Guid> > SetFileActivatedState(string projectUid, Dictionary <Guid, bool> fileUids)
        {
            Logger.LogDebug($"SetFileActivatedState: projectUid={projectUid}, {fileUids.Keys.Count} files with changed state");

            var deactivatedFileList = await ImportedFileRequestDatabaseHelper.GetImportedFileProjectSettings(projectUid, UserId, ProjectRepo).ConfigureAwait(false) ?? new List <ActivatedFileDescriptor>();

            Logger.LogDebug($"SetFileActivatedState: originally {deactivatedFileList.Count} deactivated files");

            var missingUids = new List <Guid>();

            foreach (var key in fileUids.Keys)
            {
                //fileUids contains only uids of files whose state has changed.
                //In the project settings we store only deactivated files.
                //Therefore if the value is true remove from the list else add to the list
                if (fileUids[key])
                {
                    var item = deactivatedFileList.SingleOrDefault(d => d.ImportedFileUid == key.ToString());
                    if (item != null)
                    {
                        deactivatedFileList.Remove(item);
                    }
                    else
                    {
                        missingUids.Add(key);
                        Logger.LogInformation($"SetFileActivatedState: ImportFile '{key}' not found in project settings.");
                    }
                }
                else
                {
                    deactivatedFileList.Add(new ActivatedFileDescriptor {
                        ImportedFileUid = key.ToString(), IsActivated = false
                    });
                }
            }

            Logger.LogDebug($"SetFileActivatedState: now {deactivatedFileList.Count} deactivated files, {missingUids.Count} missingUids");

            var projectSettingsRequest =
                _requestFactory.Create <ProjectSettingsRequestHelper>(r => r
                                                                      .CustomerUid(CustomerUid))
                .CreateProjectSettingsRequest(projectUid, JsonConvert.SerializeObject(deactivatedFileList), ProjectSettingsType.ImportedFiles);

            projectSettingsRequest.Validate();

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

            var changedUids = fileUids.Keys.Except(missingUids);

            Logger.LogDebug($"SetFileActivatedState: {changedUids.Count()} changedUids");

            return(changedUids);
        }
Esempio n. 14
0
        public void CS_CoordinateSystemControllerPostFailed()
        {
            byte[] csFileContent = { 0, 1, 2, 3, 4, 5, 6, 7 };

            var request = new CoordinateSystemFile(PD_MODEL_ID, csFileContent, "dummy.dc");

            // Create the mock PDSClient with unsuccessful result...
            var mockRaptorClient = new Mock <IASNodeClient>();
            var mockLogger       = new Mock <ILoggerFactory>();
            var mockConfigStore  = new Mock <IConfigurationStore>();

            var raptorResult = TASNodeErrorStatus.asneCouldNotConvertCSDFile;

            TCoordinateSystemSettings csSettings;

            mockRaptorClient.Setup(prj => prj.PassSelectedCoordinateSystemFile(
                                       It.IsAny <MemoryStream>(),
                                       request.CSFileName,
                                       request.ProjectId ?? VelociraptorConstants.NO_PROJECT_ID, out csSettings)).Returns(raptorResult);

            // Create an executor...
            var executor = RequestExecutorContainerFactory.Build <CoordinateSystemExecutorPost>(mockLogger.Object, mockRaptorClient.Object, configStore: mockConfigStore.Object);

            Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request));
        }
Esempio n. 15
0
        public async Task UpsertProjectSettingsExecutor_InvalidCustomerProjectRelationship(ProjectSettingsType settingsType)
        {
            var customerUidOfProject = Guid.NewGuid().ToString();
            var customerUidSomeOther = Guid.NewGuid().ToString();
            var userId           = Guid.NewGuid().ToString();
            var userEmailAddress = "*****@*****.**";
            var settings         = "blah";
            var settingsUpdated  = "blah Is Updated";

            var project = await ExecutorTestFixture.CreateCustomerProject(customerUidOfProject);

            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,
                               customerUidSomeOther, userId, userEmailAddress, ExecutorTestFixture.CustomHeaders(customerUidOfProject),
                               productivity3dV2ProxyCompaction: ExecutorTestFixture.Productivity3dV2ProxyCompaction,
                               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));
        }
Esempio n. 16
0
        public async Task <ProjectSettingsResult> UpsertProjectSettings([FromBody] ProjectSettingsRequest request)
        {
            if (string.IsNullOrEmpty(request?.projectUid))
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 68);
            }
            LogCustomerDetails("UpsertProjectSettings", request?.projectUid);
            Logger.LogDebug($"UpsertProjectSettings: {JsonConvert.SerializeObject(request)}");

            request.ProjectSettingsType = ProjectSettingsType.Targets;

            var projectSettingsRequest = _requestFactory.Create <ProjectSettingsRequestHelper>(r => r
                                                                                               .CustomerUid(CustomerUid))
                                         .CreateProjectSettingsRequest(request.projectUid, request.Settings, request.ProjectSettingsType);

            projectSettingsRequest.Validate();

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

            await NotifyChanges(UserId, request.projectUid);

            Logger.LogResult(this.ToString(), JsonConvert.SerializeObject(request), result);
            return(result);
        }
Esempio n. 17
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);
        }
Esempio n. 18
0
        public async Task ProjectChangedExecutor_MetadataChanged_Project(NotificationType notificationType)
        {
            var projectUid = Guid.NewGuid();
            var projectTrn = TRNHelper.MakeTRN(projectUid, TRNHelper.TRN_ACCOUNT);

            var notificationHubClient = new Mock <INotificationHubClient>();

            notificationHubClient.Setup(n => n.Notify(It.IsAny <Notification>())).Returns(Task.CompletedTask);

            var request = new ProjectChangeNotificationDto
            {
                AccountTrn                  = null,
                ProjectTrn                  = projectTrn,
                NotificationType            = notificationType,
                CoordinateSystemFileName    = null,
                CoordinateSystemFileContent = null
            };
            var executor = RequestExecutorContainerFactory.Build <ProjectChangedExecutor>
                               (_loggerFactory, _configStore, ServiceExceptionHandler,
                               _customerUid.ToString(), _userUid.ToString(), null, _customHeaders, notificationHubClient: notificationHubClient.Object);
            var result = await executor.ProcessAsync(request);

            Assert.Equal(ContractExecutionStatesEnum.ExecutedSuccessfully, result.Code);
            Assert.Equal(ContractExecutionResult.DefaultMessage, result.Message);
        }
Esempio n. 19
0
        public async Task UpdatePreferenceKeyExecutor_DuplicateKeyName()
        {
            const string keyName = "some key";

            var prefKeyDatabase = new PrefKeyDataModel
            {
                KeyName          = keyName,
                PreferenceKeyUID = Guid.NewGuid().ToString(),
                PreferenceKeyID  = 12345
            };

            mockPrefRepo.Setup(p => p.GetPreferenceKey(null, keyName))
            .ReturnsAsync(prefKeyDatabase);

            var prefEvent = new UpdatePreferenceKeyEvent
            {
                PreferenceKeyName = keyName,
                PreferenceKeyUID  = Guid.NewGuid()
            };

            var executor = RequestExecutorContainerFactory.Build <UpdatePreferenceKeyExecutor>
                               (Logger, ServiceExceptionHandler, mockPrefRepo.Object);
            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await executor.ProcessAsync(prefEvent));

            Assert.Equal(HttpStatusCode.BadRequest, ex.Code);
            var result = ex.GetResult;

            Assert.Equal(2004, result.Code);
            Assert.Equal($"Duplicate preference key name. {keyName}", result.Message);
        }
Esempio n. 20
0
        public async Task CompactionReportStationOffsetExecutor_TRex_NoResult()
        {
            var projectUid         = Guid.NewGuid();
            var alignmentDesignUid = Guid.NewGuid();
            var userPreferences    = new UserPreferenceData {
                Language = "en-US"
            };
            var request = CompactionReportStationOffsetRequest.CreateRequest(
                0, projectUid, null, 0, null, false, true, true, true, true, false,
                null, new DesignDescriptor(-1,
                                           FileDescriptor.CreateFileDescriptor(string.Empty, string.Empty, projectUid.ToString(),
                                                                               "theFilename.svl"), -1, alignmentDesignUid), 0, 0, 0, null, userPreferences, "New Zealand Standard Time");

            var mockConfigStore = new Mock <IConfigurationStore>();

#if RAPTOR
            mockConfigStore.Setup(x => x.GetValueBool("ENABLE_TREX_GATEWAY_STATIONOFFSET")).Returns(true);
#endif

            var exception = new ServiceException(HttpStatusCode.InternalServerError,
                                                 new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, $"StationOffset report failed somehow. ProjectUid: { projectUid }"));
            var tRexProxy = new Mock <ITRexCompactionDataProxy>();
            tRexProxy.Setup(x => x.SendDataPostRequestWithStreamResponse(It.IsAny <CompactionReportStationOffsetTRexRequest>(), It.IsAny <string>(), It.IsAny <IHeaderDictionary>())).Throws(exception);
            var executor = RequestExecutorContainerFactory
                           .Build <CompactionReportStationOffsetExecutor>(_logger, configStore: mockConfigStore.Object, trexCompactionDataProxy: tRexProxy.Object);
            var result = await Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request));

            Assert.AreEqual(HttpStatusCode.InternalServerError, result.Code);
            Assert.AreEqual(ContractExecutionStatesEnum.InternalProcessingError, result.GetResult.Code);
            Assert.AreEqual(exception.GetResult.Message, result.GetResult.Message);
        }
Esempio n. 21
0
        public async Task CompactionCellDatumExecutor_TRex_Success()
        {
            var expectedResult = new CompactionCellDatumResult(DisplayMode.Height, CellDatumReturnCode.ValueFound, 5.23,
                                                               DateTime.UtcNow.AddHours(-4.5), 12345, 9876);

            var tRexProxy = new Mock <ITRexCompactionDataProxy>();

            tRexProxy.Setup(x => x.SendDataPostRequest <CompactionCellDatumResult, CellDatumTRexRequest>(
                                It.IsAny <CellDatumTRexRequest>(),
                                It.IsAny <string>(),
                                It.IsAny <IDictionary <string, string> >(), false))
            .ReturnsAsync(expectedResult);

            var configStore = new Mock <IConfigurationStore>();

            configStore.Setup(x => x.GetValueBool("ENABLE_TREX_GATEWAY_CELL_DATUM")).Returns(true);

            var executor = RequestExecutorContainerFactory
                           .Build <CompactionCellDatumExecutor>(logger, configStore: configStore.Object, trexCompactionDataProxy: tRexProxy.Object);

            var request =
                new CellDatumRequest(0, Guid.NewGuid(), expectedResult.displayMode, new WGSPoint(123.456, 678.987), null, null, null, null);

            var result = await executor.ProcessAsync(request) as CompactionCellDatumResult;

            Assert.AreEqual(expectedResult.displayMode, result.displayMode, "Wrong displayMode");
            Assert.AreEqual(expectedResult.returnCode, result.returnCode, "Wrong returnCode");
            Assert.AreEqual(expectedResult.value, result.value, "Wrong value");
            Assert.AreEqual(expectedResult.timestamp, result.timestamp, "Wrong timestamp");
            Assert.AreEqual(expectedResult.northing, result.northing, "Wrong northing");
            Assert.AreEqual(expectedResult.easting, result.easting, "Wrong easting");
        }
Esempio n. 22
0
        public async Task GetDevice_NoAccountFound_UnhappyPath()
        {
            var cwsDevice = new DeviceResponseModel()
            {
                TRN        = TRNHelper.MakeTRN(_deviceUid, TRNHelper.TRN_DEVICE),
                DeviceName = _deviceName, SerialNumber = _serialNumber
            };
            var cwsDeviceClient = new Mock <ICwsDeviceClient>();

            cwsDeviceClient.Setup(pr => pr.GetDeviceBySerialNumber(It.IsAny <string>(), _customHeaders))
            .ReturnsAsync(cwsDevice);
            cwsDeviceClient.Setup(pr => pr.GetAccountsForDevice(It.IsAny <Guid>(), _customHeaders))
            .ReturnsAsync((DeviceAccountListResponseModel)null);

            var getDeviceBySerialExecutor = RequestExecutorContainerFactory.Build <GetDeviceBySerialExecutor>
                                                (_logger, _configStore, _serviceExceptionHandler,
                                                headers: _customHeaders, cwsDeviceClient: cwsDeviceClient.Object);
            var response = await getDeviceBySerialExecutor.ProcessAsync(new DeviceSerial(_serialNumber))
                           as DeviceDescriptorSingleResult;

            Assert.NotNull(response);
            Assert.Equal(102, response.Code);
            Assert.Equal("Unable to locate any account for the device in cws", response.Message);

            Assert.NotNull(response.DeviceDescriptor);
            Assert.Equal(102, response.DeviceDescriptor.Code);
            Assert.Null(response.DeviceDescriptor.CustomerUID);
            Assert.Equal(_deviceUid, response.DeviceDescriptor.DeviceUID);
            Assert.Equal(_deviceName, response.DeviceDescriptor.DeviceName);
            Assert.Equal(_serialNumber, response.DeviceDescriptor.SerialNumber);
            Assert.Equal("UNKNOWN", response.DeviceDescriptor.RelationStatus.ToString().ToUpper());
            Assert.Equal("Unknown", response.DeviceDescriptor.TccDeviceStatus.ToString());
            Assert.Null(response.DeviceDescriptor.ShortRaptorAssetId);
        }
Esempio n. 23
0
        public void CompactionCellDatumExecutorNoResult()
        {
            var request =
                new CellDatumRequest(0, null, DisplayMode.CompactionCoverage, null, null, null, null, null);

            TCellProductionData data = new TCellProductionData();

            var raptorClient = new Mock <IASNodeClient>();
            var configStore  = new Mock <IConfigurationStore>();

            raptorClient.Setup(x => x.GetCellProductionData(
                                   request.ProjectId.Value,
                                   (int)RaptorConverters.convertDisplayMode(request.DisplayMode),
                                   request.GridPoint != null ? request.GridPoint.x : 0.0,
                                   request.GridPoint != null ? request.GridPoint.y : 0.0,
                                   It.IsAny <TWGS84Point>(),
                                   request.LLPoint == null,
                                   It.IsAny <TICFilterSettings>(),
                                   It.IsAny <TICLiftBuildSettings>(),
                                   It.IsAny <TVLPDDesignDescriptor>(),
                                   out data))
            .Returns(false);

            var executor = RequestExecutorContainerFactory
                           .Build <CompactionCellDatumExecutor>(logger, raptorClient.Object, configStore: configStore.Object);

            Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request));
        }
Esempio n. 24
0
        public async Task <UserPreferenceV1Result> CreateUserPreference([FromBody] UpsertUserPreferenceRequest request, [FromQuery] bool allowUpdate = false)
        {
            var methodName = $"{nameof(CreateUserPreference)}";

            Logger.LogInformation($"{methodName} request: {0}", JsonConvert.SerializeObject(request));

            request.TargetUserUID = ValidateUserUid(request.TargetUserUID);

            UserPreferenceV1Result result = null;
            var existing = await PreferenceRepo.GetUserPreference(request.TargetUserUID.Value, request.PreferenceKeyName);

            if (existing == null)
            {
                result = await WithServiceExceptionTryExecuteAsync(() =>
                                                                   RequestExecutorContainerFactory
                                                                   .Build <CreateUserPreferenceExecutor>(LoggerFactory, ServiceExceptionHandler, PreferenceRepo)
                                                                   .ProcessAsync(AutoMapperUtility.Automapper.Map <CreateUserPreferenceEvent>(request))
                                                                   ) as UserPreferenceV1Result;
            }
            else if (allowUpdate)
            {
                result = await WithServiceExceptionTryExecuteAsync(() =>
                                                                   RequestExecutorContainerFactory
                                                                   .Build <UpdateUserPreferenceExecutor>(LoggerFactory, ServiceExceptionHandler, PreferenceRepo)
                                                                   .ProcessAsync(AutoMapperUtility.Automapper.Map <UpdateUserPreferenceEvent>(request))
                                                                   ) as UserPreferenceV1Result;
            }
            else
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 13);
            }

            Logger.LogResult(methodName, JsonConvert.SerializeObject(request), result);
            return(result);
        }
Esempio n. 25
0
        public void Success()
        {
            var projectUid = Guid.NewGuid();
            var designUid  = Guid.NewGuid();

            var request        = new AlignmentGeometryRequest(projectUid, designUid, false, 0.0);
            var expectedResult = new AlignmentGeometryResult
                                 (
                0,
                new AlignmentGeometry
                (
                    designUid,
                    "",
                    new[] { new[] { new double[] { 1, 2, 3 } } },
                    new[] { new AlignmentGeometryResultArc(0, 1, 2, 3, 4, 5, 6, 7, 8, true) },
                    new[] { new AlignmentGeometryResultLabel(0, 1, 2, 3), }
                )
                                 );

            var tRexProxy = new Mock <ITRexCompactionDataProxy>();

            tRexProxy.Setup(x => x.SendDataGetRequest <AlignmentGeometryResult>(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IHeaderDictionary>(), It.IsAny <List <KeyValuePair <string, string> > >()))
            .ReturnsAsync(expectedResult);

            var executor = RequestExecutorContainerFactory
                           .Build <AlignmentGeometryExecutor>(logger, trexCompactionDataProxy: tRexProxy.Object, customHeaders: _customHeaders);

            var result = executor.ProcessAsync(request).Result as AlignmentGeometryResult;

            result.Should().NotBeNull();
            result.Should().BeEquivalentTo(expectedResult);
        }
Esempio n. 26
0
        public async Task <ContractExecutionResult> DeleteUserPreference(
            string preferencekeyname, Guid?preferencekeyuid = null, Guid?userGuid = null)
        {
            var methodName = $"{nameof(DeleteUserPreference)}";

            Logger.LogInformation($"{methodName} userGuid: {userGuid}, preferencekeyname: {preferencekeyname}, preferencekeyuid: {preferencekeyuid}");

            userGuid = ValidateUserUid(userGuid);

            var deleteEvent = new DeleteUserPreferenceEvent
            {
                UserUID           = userGuid,
                PreferenceKeyName = preferencekeyname,
                PreferenceKeyUID  = preferencekeyuid
            };

            var result = await WithServiceExceptionTryExecuteAsync(() =>
                                                                   RequestExecutorContainerFactory
                                                                   .Build <DeleteUserPreferenceExecutor>(LoggerFactory, ServiceExceptionHandler, PreferenceRepo)
                                                                   .ProcessAsync(deleteEvent)
                                                                   );

            Logger.LogResult(methodName, $"userGuid: {userGuid}, preferencekeyname: {preferencekeyname}, preferencekeyuid: {preferencekeyuid}", result);
            return(result);
        }
Esempio n. 27
0
        public void ProjectStatisticsExecutor_TRex_Success()
        {
            var excludedSurveyedSurfaceUids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            var excludedSurveyedSurfaceIds  = new long[] { 444, 777, 888 };
            var request = new ProjectStatisticsMultiRequest(Guid.NewGuid(), 123, excludedSurveyedSurfaceUids, excludedSurveyedSurfaceIds);

            var expectedResult = new ProjectStatisticsResult(ContractExecutionStatesEnum.ExecutedSuccessfully)
            {
                startTime         = DateTime.UtcNow.AddDays(-5),
                endTime           = DateTime.UtcNow.AddDays(-1),
                cellSize          = 32.5,
                indexOriginOffset = 10,
                extents           = new BoundingBox3DGrid(10, 500, 0, 20, 510, 0)
            };
            var tRexProxy = new Mock <ITRexCompactionDataProxy>();

            tRexProxy.Setup(x => x.SendDataPostRequest <ProjectStatisticsResult, ProjectStatisticsTRexRequest>(It.IsAny <ProjectStatisticsTRexRequest>(), It.IsAny <string>(), It.IsAny <IHeaderDictionary>(), false))
            .ReturnsAsync((expectedResult));


            var configStore = new Mock <IConfigurationStore>();

            configStore.Setup(x => x.GetValueBool("ENABLE_TREX_GATEWAY_PROJECTSTATISTICS")).Returns(true);

            var executor = RequestExecutorContainerFactory
                           .Build <ProjectStatisticsExecutor>(logger, configStore: configStore.Object,
                                                              trexCompactionDataProxy: tRexProxy.Object, customHeaders: _customHeaders);

            var result = executor.ProcessAsync(request).Result as ProjectStatisticsResult;

            Assert.IsNotNull(result, "Result should not be null");
            Assert.AreEqual(expectedResult.startTime, result.startTime, "Wrong startTime");
            Assert.AreEqual(expectedResult.extents.MaxX, result.extents.MaxX, "Wrong MaxX extent");
        }
Esempio n. 28
0
        public async Task <CompactionExportResult> GetExportReportVeta(
            [FromQuery] Guid projectUid,
            [FromQuery] string fileName,
            [FromQuery] string machineNames,
            [FromQuery] Guid?filterUid,
            [FromQuery] CoordType coordType = CoordType.Northeast)
        {
            Log.LogInformation($"{nameof(GetExportReportVeta)}: {Request.QueryString}");

            var projectTask     = ((RaptorPrincipal)User).GetProject(projectUid);
            var projectSettings = GetProjectSettingsTargets(projectUid);
            var filterTask      = GetCompactionFilter(projectUid, filterUid);
            var userPreferences = GetUserPreferences();

            await Task.WhenAll(projectTask, projectSettings, filterTask, userPreferences);

            var project = projectTask.Result;
            var filter  = filterTask.Result;

            var startEndDate = await GetDateRange(project.ShortRaptorProjectId, filter);

            var exportRequest = requestFactory.Create <ExportRequestHelper>(r => r
                                                                            .ProjectUid(projectUid)
                                                                            .ProjectId(project.ShortRaptorProjectId)
                                                                            .Headers(CustomHeaders)
                                                                            .ProjectSettings(projectSettings.Result)
                                                                            .Filter(filter))
#if RAPTOR
                                .SetRaptorClient(RaptorClient)
#endif
                                .SetUserPreferences(userPreferences.Result)
                                .SetProjectDescriptor(project)
                                .CreateExportRequest(
                startEndDate.startUtc,
                startEndDate.endUtc,
                coordType,
                ExportTypes.VedaExport,
                fileName,
                false,
                true,
                OutputTypes.VedaAllPasses,
                machineNames);

            exportRequest.Validate();

            var result = await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory
                                                                   .Build <CompactionExportExecutor>(LoggerFactory,
#if RAPTOR
                                                                                                     RaptorClient,
#endif
                                                                                                     configStore : ConfigStore,
                                                                                                     trexCompactionDataProxy : TRexCompactionDataProxy,
                                                                                                     customHeaders : CustomHeaders,
                                                                                                     userId : GetUserId(),
                                                                                                     fileImportProxy : FileImportProxy)
                                                                   .ProcessAsync(exportRequest)) as CompactionExportResult;

            Log.LogInformation($"GetExportReportVeta completed");
            return(result);
        }
Esempio n. 29
0
        public async Task <CompactionCutFillDetailedResult> GetCutFillDetails(
            [FromQuery] Guid projectUid,
            [FromQuery] Guid?filterUid,
            [FromQuery] Guid cutfillDesignUid)
        {
            Log.LogInformation("GetCutFillDetails: " + Request.QueryString);

            var projectSettings = GetProjectSettingsTargets(projectUid);
            var cutFillDesign   = GetAndValidateDesignDescriptor(projectUid, cutfillDesignUid);
            var filter          = GetCompactionFilter(projectUid, filterUid);
            var projectId       = GetLegacyProjectId(projectUid);

            await Task.WhenAll(projectSettings, cutFillDesign, filter, projectId);

            var cutFillRequest = RequestFactory.Create <CutFillRequestHelper>(r => r
                                                                              .ProjectUid(projectUid)
                                                                              .ProjectId(projectId.Result)
                                                                              .Headers(CustomHeaders)
                                                                              .ProjectSettings(projectSettings.Result)
                                                                              .Filter(filter.Result)
                                                                              .DesignDescriptor(cutFillDesign.Result))
                                 .Create();

            cutFillRequest.Validate();

            return(await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory.Build <CompactionCutFillExecutor>(LoggerFactory,
#if RAPTOR
                                                                                                                                     RaptorClient,
#endif
                                                                                                                                     configStore : ConfigStore, trexCompactionDataProxy : TRexCompactionDataProxy, customHeaders : CustomHeaders,
                                                                                                                                     userId : GetUserId(), fileImportProxy : FileImportProxy)
                                                             .ProcessAsync(cutFillRequest)) as CompactionCutFillDetailedResult);
        }
Esempio n. 30
0
        public void CS_CoordinateConversionFailed()
        {
            var request = new CoordinateConversionRequest(1, TwoDCoordinateConversionType.NorthEastToLatLon,
                                                          new[]
            {
                new TwoDConversionCoordinate(381043.710, 807625.050),
                new TwoDConversionCoordinate(381821.617, 807359.462),
                new TwoDConversionCoordinate(380781.358, 806969.174)
            });

            // Create the mock PDSClient with successful result...
            var mockRaptorClient = new Mock <IASNodeClient>();
            var mockLogger       = new Mock <ILoggerFactory>();
            var mockConfigStore  = new Mock <IConfigurationStore>();

            var raptorResult = TCoordReturnCode.nercFailedToConvertCoords;

            TCoordPointList pointList;

            mockRaptorClient.Setup(prj => prj.GetGridCoordinates(
                                       request.ProjectId ?? VelociraptorConstants.NO_PROJECT_ID,
                                       It.IsAny <TWGS84FenceContainer>(),
                                       request.ConversionType == TwoDCoordinateConversionType.LatLonToNorthEast ? TCoordConversionType.ctLLHtoNEE : TCoordConversionType.ctNEEtoLLH,
                                       out pointList)).Returns(raptorResult);

            // Create an executor...
            var executor = RequestExecutorContainerFactory.Build <CoordinateConversionExecutor>(mockLogger.Object, mockRaptorClient.Object, configStore: mockConfigStore.Object);

            Assert.ThrowsExceptionAsync <ServiceException>(async() => await executor.ProcessAsync(request));
        }