Example #1
0
        public async Task <IActionResult> PostSnsTagFile(
            [FromServices] IWebRequest webRequest,
            [FromServices] ILoggerFactory loggerFactory,
            [FromServices] IConfigurationStore configStore,
            [FromServices] IDataCache dataCache,
            [FromServices] ITRexTagFileProxy trexTagFileProxy,
            [FromServices] ITransferProxyFactory transferProxyFactory)
        {
            // https://forums.aws.amazon.com/thread.jspa?threadID=69413
            // AWS SNS is in text/plain, not application/json - so need to parse manually
            var payloadMs = new MemoryStream();
            await Request.Body.CopyToAsync(payloadMs);

            var payload = JsonConvert.DeserializeObject <SnsPayload>(Encoding.UTF8.GetString(payloadMs.ToArray()));

            if (payload == null)
            {
                return(BadRequest());
            }

            var result = await RequestExecutorContainer.Build <TagFileSnsProcessExecutor>(loggerFactory,
                                                                                          configStore, dataCache, trexTagFileProxy, transferProxyFactory, webRequest)
                         .ProcessAsync(payload);

            if (result != null)
            {
                return(Ok());
            }
            // Note sure if we return bad request or not on failed processing - will updated if needed
            return(BadRequest());
        }
Example #2
0
        public async Task CSVExportExecutor_SiteModelNotFound()
        {
            var          projectUid = Guid.NewGuid();
            FilterResult filter     = null;
            var          fileName   = "gotAFilename";
            var          coordType  = CoordType.LatLon;
            var          outputType = OutputTypes.VedaAllPasses;

            string[] machineNames    = new string[] { "first machineName" };
            var      userPreferences = new UserPreferences();

            var request = new CompactionVetaExportRequest(
                projectUid, filter, fileName,
                coordType, outputType, userPreferences, machineNames, null, null);

            request.Validate();
            var compactionCSVExportRequest = AutoMapperUtility.Automapper.Map <CompactionCSVExportRequest>(request);

            var executor = RequestExecutorContainer
                           .Build <CSVExportExecutor>(DIContext.Obtain <IConfigurationStore>(),
                                                      DIContext.Obtain <ILoggerFactory>(),
                                                      DIContext.Obtain <IServiceExceptionHandler>());
            var result = await Assert.ThrowsAsync <ServiceException>(() => executor.ProcessAsync(compactionCSVExportRequest));

            result.Code.Should().Be(HttpStatusCode.BadRequest);
            result.GetResult.Code.Should().Be(ContractExecutionStatesEnum.InternalProcessingError);
            result.GetResult.Message.Should().Be($"Site model {projectUid} is unavailable");
        }
Example #3
0
        public Task <ContractExecutionResult> GetDesignFilterBoundaries(
            [FromQuery] Guid projectUid,
            [FromQuery] Guid designUid,
            [FromQuery] string fileName,
            [FromQuery] double startStation,
            [FromQuery] double endStation,
            [FromQuery] double leftOffset,
            [FromQuery] double rightOffset)
        {
            Log.LogInformation($"{nameof(GetDesignFilterBoundaries)}: projectUid:{projectUid}, designUid:{designUid}, fileName:{fileName}, " +
                               $"startStation: {startStation}, endStation: {endStation}, leftOffset: {leftOffset}, rightOffset: {rightOffset}");

            var designFilterBoundaryRequest = new DesignFilterBoundaryRequest(
                projectUid,
                designUid,
                fileName,
                startStation,
                endStation,
                leftOffset,
                rightOffset);

            designFilterBoundaryRequest.Validate();

            return(WithServiceExceptionTryExecuteAsync(() =>
                                                       RequestExecutorContainer
                                                       .Build <DesignFilterBoundaryExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                       .ProcessAsync(designFilterBoundaryRequest)));
        }
Example #4
0
        public async Task <ContractExecutionResult> PostTagFile([FromBody] CompactionTagFileRequest request,
                                                                [FromServices] ILoggerFactory loggerFactory,
                                                                [FromServices] IConfigurationStore configStore,
                                                                [FromServices] IDataCache dataCache,
                                                                [FromServices] ITRexTagFileProxy trexTagFileProxy,
                                                                [FromServices] ITransferProxyFactory transferProxyFactory,
                                                                [FromServices] IWebRequest webRequest)
        {
            var isDirect = Request.Path.Value.Contains("/direct");

            _logger.LogInformation($"{nameof(PostTagFile)} Attempting to process {(isDirect ? "Direct" : "Non-Direct")} tag file {request?.FileName}");
            var executor = RequestExecutorContainer
                           .Build <TagFileProcessExecutor>(loggerFactory, configStore, dataCache, trexTagFileProxy, transferProxyFactory, webRequest);

            executor.ArchiveOnInternalError = true;
            var result = await executor.ProcessAsync(request);

            _logger.LogInformation($"{nameof(PostTagFile)} Got result {JsonConvert.SerializeObject(result)} for Tag file: {request?.FileName}");


            // If we uploaded, return a successful result
            // (as the tag file may not have been processed for legitimate reasons)
            // We don't want the machine sending tag files over and over again in this instance
            return(new ContractExecutionResult());
        }
Example #5
0
        public async Task <GeofenceDataSingleResult> UpsertBoundary(string projectUid, [FromBody] BoundaryRequest request)
        {
            Log.LogInformation(
                $"{ToString()}.{nameof(UpsertBoundary)}: CustomerUID={CustomerUid} BoundaryRequest: {JsonConvert.SerializeObject(request)}");

            var requestFull = BoundaryRequestFull.Create(
                CustomerUid,
                IsApplication,
                await GetProject(projectUid),
                GetUserId,
                request);

            requestFull.Validate(ServiceExceptionHandler);
            requestFull.Request.BoundaryPolygonWKT = GeofenceValidation.MakeGoodWkt(requestFull.Request.BoundaryPolygonWKT);

            var getResult = await BoundaryHelper.GetProjectBoundaries(
                Log, ServiceExceptionHandler,
                projectUid, _projectRepository, _geofenceRepository).ConfigureAwait(false);

            if (getResult.GeofenceData.Any(g => request.Name.Equals(g.GeofenceName, StringComparison.OrdinalIgnoreCase)))
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 62);
            }

            var executor = RequestExecutorContainer.Build <UpsertBoundaryExecutor>(ConfigStore, Logger,
                                                                                   ServiceExceptionHandler, _geofenceRepository, _projectRepository, ProjectProxy);
            var result = await executor.ProcessAsync(requestFull) as GeofenceDataSingleResult;

            Log.LogInformation(
                $"{ToString()}.UpsertBoundary Completed: resultCode: {result?.Code} result: {JsonConvert.SerializeObject(result)}");
            return(result);
        }
Example #6
0
        public Task <ContractExecutionResult> UpdateDesign([FromBody] DesignRequest designRequest)
        {
            Log.LogInformation($"{nameof(UpdateDesign)}: {JsonConvert.SerializeObject(designRequest)}");
            designRequest.Validate();
            GatewayHelper.ValidateAndGetSiteModel(nameof(UpdateDesign), designRequest.ProjectUid, true);

            if (!DesignExists(designRequest.ProjectUid, designRequest.FileType, designRequest.DesignUid))
            {
                return(Task.FromResult(new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError, "Design doesn't exist. Cannot update.")));
            }

            if (designRequest.FileType == ImportedFileType.DesignSurface || designRequest.FileType == ImportedFileType.SurveyedSurface)
            {
                return(WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainer
                                                           .Build <UpdateTTMDesignExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                           .ProcessAsync(designRequest)));
            }

            if (designRequest.FileType == ImportedFileType.Alignment)
            {
                return(WithServiceExceptionTryExecuteAsync(() =>
                                                           RequestExecutorContainer
                                                           .Build <UpdateSVLDesignExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                           .ProcessAsync(designRequest)));
            }
            throw new ServiceException(HttpStatusCode.BadRequest, new ContractExecutionResult(ContractExecutionStatesEnum.ValidationError, "File type must be DesignSurface, SurveyedSurface or Alignment"));
        }
Example #7
0
        public async Task DeleteBoundaryExecutor_ExistingBoundary()
        {
            var custUid     = Guid.NewGuid();
            var userId      = Guid.NewGuid();
            var projectUid  = Guid.NewGuid();
            var boundaryUid = Guid.NewGuid();

            WriteEventToDb(new CreateGeofenceEvent
            {
                GeofenceUID  = boundaryUid,
                GeofenceType = GeofenceType.Filter.ToString(),
                CustomerUID  = custUid,
                UserUID      = userId,
                ActionUTC    = DateTime.UtcNow,
                GeometryWKT  = GenerateWKTPolygon(),
                GeofenceName = "name",
                Description  = null
            });
            WriteEventToDb(new AssociateProjectGeofence
            {
                ProjectUID  = projectUid,
                GeofenceUID = boundaryUid,
                ActionUTC   = DateTime.UtcNow
            });

            var request = CreateAndValidateRequest(custUid, projectUid, userId, boundaryUid);

            var executor =
                RequestExecutorContainer.Build <DeleteBoundaryExecutor>(ConfigStore, Logger, ServiceExceptionHandler, GeofenceRepo, ProjectRepo, ProjectProxy);
            var result = await executor.ProcessAsync(request);

            Assert.IsNotNull(result, "executor should always return a result");
            Assert.AreEqual(0, result.Code, "executor returned incorrect code");
            Assert.AreEqual("success", result.Message, "executor returned incorrect message");
        }
Example #8
0
        public void SiteModelStatisticsExecutor_EmptySiteModel()
        {
            var siteModel = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel();

            var request = new ProjectStatisticsTRexRequest(siteModel.ID, null);

            request.Validate();

            var executor = RequestExecutorContainer
                           .Build <SiteModelStatisticsExecutor>(DIContext.Obtain <IConfigurationStore>(),
                                                                DIContext.Obtain <ILoggerFactory>(),
                                                                DIContext.Obtain <IServiceExceptionHandler>());
            var result = executor.Process(request) as ProjectStatisticsResult;

            result.Code.Should().Be(ContractExecutionStatesEnum.ExecutedSuccessfully);
            result.cellSize.Should().Be(SubGridTreeConsts.DefaultCellSize);
            result.startTime.Should().Be(Consts.MAX_DATETIME_AS_UTC);
            result.endTime.Should().Be(Consts.MIN_DATETIME_AS_UTC);
            result.extents.MinX.Should().Be(BoundingWorldExtent3D.Inverted().MinX);
            result.extents.MaxX.Should().Be(BoundingWorldExtent3D.Inverted().MaxX);
            result.extents.MinY.Should().Be(BoundingWorldExtent3D.Inverted().MinY);
            result.extents.MaxY.Should().Be(BoundingWorldExtent3D.Inverted().MaxY);
            result.extents.MinZ.Should().Be(BoundingWorldExtent3D.Inverted().MinZ);
            result.extents.MaxZ.Should().Be(BoundingWorldExtent3D.Inverted().MaxZ);
            result.indexOriginOffset.Should().Be((int)SubGridTreeConsts.DefaultIndexOriginOffset);

            var expectedJson = "{\"startTime\":\"9999-12-31T23:59:59.9999999\",\"endTime\":\"0001-01-01T00:00:00\",\"cellSize\":0.34,\"indexOriginOffset\":536870912,\"extents\":{\"maxX\":-1E+100,\"maxY\":-1E+100,\"maxZ\":-1E+100,\"minX\":1E+100,\"minY\":1E+100,\"minZ\":1E+100},\"Code\":0,\"Message\":\"success\"}";
            var json         = JsonConvert.SerializeObject(result);

            json.Should().Be(expectedJson);
        }
Example #9
0
        public async Task CSVExportExecutor_NoCSIB()
        {
            var fileName   = "gotAFilename";
            var coordType  = CoordType.LatLon;
            var outputType = OutputTypes.VedaAllPasses;

            string[] machineNames    = new string[] { "first machineName" };
            var      userPreferences = new UserPreferences();
            var      siteModel       = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel();

            var request = new CompactionVetaExportRequest(
                siteModel.ID, null, fileName,
                coordType, outputType, userPreferences, machineNames, null, null);

            request.Validate();
            var compactionCSVExportRequest = AutoMapperUtility.Automapper.Map <CompactionCSVExportRequest>(request);

            var executor = RequestExecutorContainer
                           .Build <CSVExportExecutor>(DIContext.Obtain <IConfigurationStore>(),
                                                      DIContext.Obtain <ILoggerFactory>(),
                                                      DIContext.Obtain <IServiceExceptionHandler>());
            var result = await Assert.ThrowsAsync <ServiceException>(() => executor.ProcessAsync(compactionCSVExportRequest));

            result.Code.Should().Be(HttpStatusCode.InternalServerError);
            result.GetResult.Code.Should().Be(ContractExecutionStatesEnum.InternalProcessingError);
            result.GetResult.Message.Should().Be("Failed to complete TRex request: CSVExportExecutor with error: Unable to load CSIB for LatLong conversion");
        }
Example #10
0
        public async void TileExecutor_EmptySiteModel()
        {
            AddRoutings();

            var siteModel = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel();

            var request = new QMTileRequest
                          (
                siteModel.ID,
                new FilterResult(),
                1, 3, 3, 3, false
                          );

            request.Validate();

            var executor = RequestExecutorContainer
                           .Build <QuantizedMeshTileExecutor>(DIContext.Obtain <IConfigurationStore>(),
                                                              DIContext.Obtain <ILoggerFactory>(),
                                                              DIContext.Obtain <IServiceExceptionHandler>());

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

            result.Should().NotBeNull();
            result.Code.Should().Be(ContractExecutionStatesEnum.ExecutedSuccessfully);
            result.TileData.Should().NotBeNull();
        }
Example #11
0
        private async Task ExecuteManual(GetProjectUidsRequest request, ProjectData projectForProjectUid,
                                         DeviceData platformDevice, ProjectDataResult projectListForPlatform,
                                         CoordinateConversionResult coordinateConversionResult,
                                         GetProjectUidsResult expectedResult, int expectedCode, string expectedMessage
                                         )
        {
            projectProxy.Setup(p => p.GetProject(request.ProjectUid, It.IsAny <HeaderDictionary>())).ReturnsAsync(projectForProjectUid);

            deviceProxy.Setup(d => d.GetDevice(request.PlatformSerial, It.IsAny <HeaderDictionary>())).ReturnsAsync(platformDevice);
            if (platformDevice != null)
            {
                deviceProxy.Setup(d => d.GetProjectsForDevice(platformDevice.DeviceUID, It.IsAny <HeaderDictionary>())).ReturnsAsync(projectListForPlatform);
            }

            if (coordinateConversionResult != null)
            {
                tRexCompactionDataProxy.Setup(x => x.SendDataPostRequest <CoordinateConversionResult, CoordinateConversionRequest>(
                                                  It.IsAny <CoordinateConversionRequest>(),
                                                  It.IsAny <string>(),
                                                  It.IsAny <HeaderDictionary>(), false))
                .ReturnsAsync(coordinateConversionResult);
            }

            var executor = RequestExecutorContainer.Build <ProjectUidsExecutor>(
                _loggerFactory.CreateLogger <ProjectUidsExecutorManualTests>(), ConfigStore, authorization.Object,
                projectProxy.Object, deviceProxy.Object, tRexCompactionDataProxy.Object, requestCustomHeaders);
            var result = await executor.ProcessAsync(request) as GetProjectUidsResult;

            ValidateResult(result, expectedResult, expectedCode, expectedMessage);
        }
Example #12
0
        public async Task <FilterDescriptorListResult> CreateFilters(
            string projectUid,
            [FromBody] FilterListRequest request
            /* ,     [FromServices] IGeofenceProxy geofenceProxy */
            )
        {
            Log.LogInformation($"{nameof(CreateFilters)}: CustomerUID={CustomerUid} FilterListRequest: {JsonConvert.SerializeObject(request)}");

            if (request?.FilterRequests == null || request.FilterRequests?.Count() == 0)
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 7, "Missing filters");
            }

            var projectTask    = GetProject(projectUid);
            var newFilters     = new List <FilterDescriptor>();
            var filterExecutor = RequestExecutorContainer.Build <UpsertFilterExecutor>(ConfigStore, Logger, ServiceExceptionHandler, filterRepo, geofenceRepository, ProjectProxy,
                                                                                       productivity3dV2ProxyNotification: Productivity3dV2ProxyNotification, productivity3dV2ProxyCompaction: Productivity3dV2ProxyCompaction
                                                                                       /* , geofenceProxy: geofenceProxy */);

            var project = await projectTask;

            foreach (var filterRequest in request.FilterRequests)
            {
                newFilters.Add((await UpsertFilter(filterExecutor, project, filterRequest)).FilterDescriptor);
            }

            var result = new FilterDescriptorListResult {
                FilterDescriptors = newFilters.ToImmutableList()
            };

            Log.LogInformation($"{nameof(CreateFilters)} Completed: resultCode: {result.Code} result: {JsonConvert.SerializeObject(result)}");

            return(result);
        }
Example #13
0
        public async Task <FileResult> PostGriddedReport(
            [FromBody] CompactionReportGridTRexRequest reportGridRequest,
            [FromServices] IReportDataValidationUtility reportDataValidationUtility)
        {
            Log.LogInformation($"{nameof(PostGriddedReport)}: {Request.QueryString}");

            reportGridRequest.Validate();
            reportDataValidationUtility.ValidateData(nameof(PostGriddedReport), reportGridRequest.ProjectUid, (object)reportGridRequest);
            ValidateFilterMachines(nameof(PostGriddedReport), reportGridRequest.ProjectUid, reportGridRequest.Filter);

            var griddedReportDataResult = await WithServiceExceptionTryExecuteAsync(() =>
                                                                                    RequestExecutorContainer
                                                                                    .Build <GriddedReportExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                                                    .ProcessAsync(reportGridRequest)) as GriddedReportDataResult;

            if (griddedReportDataResult?.GriddedData == null)
            {
                var code   = griddedReportDataResult == null ? HttpStatusCode.BadRequest : HttpStatusCode.NoContent;
                var exCode = griddedReportDataResult == null ? ContractExecutionStatesEnum.FailedToGetResults : ContractExecutionStatesEnum.ValidationError;

                throw new ServiceException(code, new ContractExecutionResult(exCode, $"Failed to get gridded report data for projectUid: {reportGridRequest.ProjectUid}"));
            }

            return(new FileStreamResult(new MemoryStream(griddedReportDataResult.GriddedData), ContentTypeConstants.ApplicationOctetStream));
        }
Example #14
0
        public async Task GetFilterExecutor_ExistingFilter_CaseInsensitive(FilterType filterType)
        {
            string custUid    = Guid.NewGuid().ToString().ToLower(); // actually Guid.Parse converts to lower anyway
            string userId     = Guid.NewGuid().ToString().ToLower();
            string projectUid = Guid.NewGuid().ToString().ToLower();
            string filterUid  = Guid.NewGuid().ToString().ToLower();
            string name       = "blah";

            WriteEventToDb(new CreateFilterEvent
            {
                CustomerUID = new Guid(custUid),
                UserID      = userId,
                ProjectUID  = new Guid(projectUid),
                FilterUID   = new Guid(filterUid),
                Name        = name,
                FilterType  = filterType,
                FilterJson  = "{\"dateRangeType\":0,\"elevationType\":null}",
                ActionUTC   = DateTime.UtcNow
            });

            var request = CreateAndValidateRequest(customerUid: custUid.ToUpper(), userId: userId.ToUpper(), projectUid: projectUid.ToUpper(), filterUid: filterUid.ToUpper(), filterType: filterType, name: name);

            var executor =
                RequestExecutorContainer.Build <GetFilterExecutor>(ConfigStore, Logger, ServiceExceptionHandler, FilterRepo, null);
            var result = await executor.ProcessAsync(request) as FilterDescriptorSingleResult;

            Assert.IsNotNull(result, Responses.ShouldReturnResult);
            Assert.AreEqual(filterUid, result.FilterDescriptor.FilterUid, Responses.IncorrectFilterDescriptorFilterUid);
            Assert.AreEqual(name, result.FilterDescriptor.Name, Responses.IncorrectFilterDescriptorName);
            Assert.AreEqual("{\"dateRangeType\":0,\"dateRangeName\":\"Today\"}", result.FilterDescriptor.FilterJson, Responses.IncorrectFilterDescriptorFilterJson);
            Assert.AreEqual(filterType, result.FilterDescriptor.FilterType, Responses.IncorrectFilterDescriptorFilterType);
        }
Example #15
0
        public async Task <GeofenceDataListResult> GetProjectBoundaries(
            string projectUid

            /*,    [FromServices] IGeofenceProxy geofenceProxy,
             * [FromServices] IUnifiedProductivityProxy unifiedProductivityProxy*/
            )
        {
            Log.LogInformation(
                $"{ToString()}.GetProjectBoundaries: CustomerUID={CustomerUid} IsApplication={IsApplication} UserUid={GetUserId} ProjectUid: {projectUid}");

            var requestFull = BaseRequestFull.Create(
                CustomerUid,
                IsApplication,
                await GetProject(projectUid),
                GetUserId,
                Request.Headers.GetCustomHeaders());

            requestFull.Validate(ServiceExceptionHandler);

            var executor = RequestExecutorContainer.Build <GetBoundariesExecutor>(ConfigStore, Logger, ServiceExceptionHandler,
                                                                                  _geofenceRepository, _projectRepository, ProjectProxy
                                                                                  /* ,  geofenceProxy: geofenceProxy, unifiedProductivityProxy: unifiedProductivityProxy */);

            var result = await executor.ProcessAsync(requestFull);

            Log.LogInformation(
                $"{ToString()}.GetProjectBoundaries Completed: resultCode: {result?.Code} result: {JsonConvert.SerializeObject(result)}");
            return(result as GeofenceDataListResult);
        }
Example #16
0
        public async Task TileExecutor_EmptySiteModel()
        {
            AddRoutings();

            var siteModel = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel();

            var request = new TRexTileRequest
                          (
                siteModel.ID,
                DisplayMode.Height,
                null, //List<ColorPalette> palettes,
                null, //new DesignDescriptor(0, FileDescriptor.EmptyFileDescriptor, 0),
                new FilterResult(),
                new FilterResult(),
                null, //new BoundingBox2DLatLon boundingBoxLatLon,
                new BoundingBox2DGrid(0, 0, 100, 100),
                256,
                256,
                null,
                null,
                VolumesType.None);

            request.Validate();

            var executor = RequestExecutorContainer
                           .Build <TileExecutor>(DIContext.Obtain <IConfigurationStore>(),
                                                 DIContext.Obtain <ILoggerFactory>(),
                                                 DIContext.Obtain <IServiceExceptionHandler>());
            var result = await executor.ProcessAsync(request) as TileResult;

            result.Should().NotBeNull();
            result?.Code.Should().Be(ContractExecutionStatesEnum.ExecutedSuccessfully);
            result?.TileData.Should().NotBeNull();
        }
Example #17
0
        public async Task DeleteFilterExecutor_ExistingFilter(FilterType filterType)
        {
            var    custUid    = Guid.NewGuid();
            var    userId     = Guid.NewGuid();
            var    projectUid = Guid.NewGuid();
            var    filterUid  = Guid.NewGuid();
            string name       = "blah";
            string filterJson = "theJsonString";

            WriteEventToDb(new CreateFilterEvent
            {
                CustomerUID = custUid,
                UserID      = userId.ToString(),
                ProjectUID  = projectUid,
                FilterUID   = filterUid,
                Name        = name,
                FilterType  = filterType,
                FilterJson  = filterJson,
                ActionUTC   = DateTime.UtcNow
            });

            var request = CreateAndValidateRequest(name: name, customerUid: custUid.ToString(), userId: userId.ToString(), projectUid: projectUid.ToString(), filterUid: filterUid.ToString(), filterType: filterType, onlyFilterUid: true);

            var executor =
                RequestExecutorContainer.Build <DeleteFilterExecutor>(ConfigStore, Logger, ServiceExceptionHandler, FilterRepo, null, ProjectProxy,
                                                                      productivity3dV2ProxyNotification: Productivity3dV2ProxyNotification, productivity3dV2ProxyCompaction: Productivity3dV2ProxyCompaction);
            var result = await executor.ProcessAsync(request);

            Assert.IsNotNull(result, "executor should always return a result");
            Assert.AreEqual(0, result.Code, "executor returned incorrect code");
            Assert.AreEqual("success", result.Message, "executor returned incorrect message");
        }
Example #18
0
        private async Task ProcessSingleMessage(Message m)
        {
            try
            {
                SnsPayload snsPayload;
                try
                {
                    snsPayload = JsonConvert.DeserializeObject <SnsPayload>(m.Body);
                }
                catch (Exception e)
                {
                    Logger.LogError(e, $"{nameof(ProcessSingleMessage)} Failed to deserialize snsPayload with ID {m.MessageId}");
                    snsPayload = null;
                }

                if (snsPayload == null)
                {
                    // Either exception or null deserialization can occur with badly formed Json.
                    // Delete, so they don't just fill up the que
                    var deleteMessage  = new DeleteMessageRequest(_url, m.ReceiptHandle);
                    var deleteResponse = await _awSqsClient.DeleteMessageAsync(deleteMessage);

                    Logger.LogWarning($"{nameof(ProcessSingleMessage)} Failed to parse SQS Message. MessageID: {m.MessageId}, Body: {m.Body} Delete SQS Message Response Code: {deleteResponse.HttpStatusCode}");
                    return;
                }

                Logger.LogInformation($"{nameof(ProcessSingleMessage)} Processing SQS Message ID: {m.MessageId}.");
                // We need to create a scope, as a hosted service is a singleton, but some of the services are transient, we can't inject them.
                // Instead we create a scope for 'our' work
                using var serviceScope = ScopeFactory.CreateScope();
                var executor = RequestExecutorContainer.Build <TagFileSnsProcessExecutor>(
                    serviceScope.ServiceProvider.GetService <ILoggerFactory>(),
                    serviceScope.ServiceProvider.GetService <IConfigurationStore>(),
                    serviceScope.ServiceProvider.GetService <IDataCache>(),
                    serviceScope.ServiceProvider.GetService <ITRexTagFileProxy>(),
                    serviceScope.ServiceProvider.GetService <ITransferProxyFactory>(),
                    serviceScope.ServiceProvider.GetService <IWebRequest>());

                var result = await executor.ProcessAsync(snsPayload);

                // internalErrors are retry-able, so leave them on the que to be picked up again.
                if (result != null && result.Code != ContractExecutionStatesEnum.InternalProcessingError)
                {
                    // Mark as processed
                    var deleteMessage  = new DeleteMessageRequest(_url, m.ReceiptHandle);
                    var deleteResponse = await _awSqsClient.DeleteMessageAsync(deleteMessage);

                    Logger.LogInformation($"{nameof(ProcessSingleMessage)} Delete SQS Message Response Code: {deleteResponse.HttpStatusCode}");
                }
                else
                {
                    Logger.LogWarning($"{nameof(ProcessSingleMessage)} Tag file failed to process due to internal error, leave it on que to be re-processed: {m.MessageId}.");
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"{nameof(ProcessSingleMessage)} Failed to process message with ID {m.MessageId} - not deleted from the queue");
            }
        }
Example #19
0
 public Task <ContractExecutionResult> RemoveDataEdit([FromBody] TRexEditData request)
 {
     Log.LogInformation($"{nameof(RemoveDataEdit)}: {JsonConvert.SerializeObject(request)}");
     request.Validate();
     return(WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainer
                                                .Build <RemoveEditDataExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                .ProcessAsync(request)));
 }
Example #20
0
        public async Task GetBoundaryExecutor()
        {
            string custUid     = Guid.NewGuid().ToString();
            string userUid     = Guid.NewGuid().ToString();
            string projectUid  = Guid.NewGuid().ToString();
            string boundaryUid = Guid.NewGuid().ToString();
            string name        = "blah";
            string geometryWKT = "whatever";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var geofenceRepo = new Mock <GeofenceRepository>(configStore, logger);
            var geofence     = new Geofence
            {
                CustomerUID     = custUid,
                UserUID         = userUid,
                GeofenceUID     = boundaryUid,
                Name            = name,
                GeometryWKT     = geometryWKT,
                GeofenceType    = GeofenceType.Filter,
                LastActionedUTC = DateTime.UtcNow
            };

            geofenceRepo.As <IGeofenceRepository>().Setup(g => g.GetGeofence(It.IsAny <string>())).ReturnsAsync(geofence);

            var projectRepo     = new Mock <ProjectRepository>(configStore, logger);
            var projectGeofence = new ProjectGeofence {
                GeofenceUID = boundaryUid, ProjectUID = projectUid
            };

            projectRepo.As <IProjectRepository>().Setup(p => p.GetAssociatedGeofences(It.IsAny <string>())).ReturnsAsync(new List <ProjectGeofence> {
                projectGeofence
            });

            var geofenceToTest = new GeofenceDataSingleResult(AutoMapperUtility.Automapper.Map <GeofenceData>(geofence));

            var request = BoundaryUidRequestFull.Create
                          (
                custUid,
                false,
                new ProjectData {
                ProjectUID = projectUid
            },
                userUid,
                boundaryUid
                          );

            var executor =
                RequestExecutorContainer.Build <GetBoundaryExecutor>(configStore, logger, serviceExceptionHandler,
                                                                     geofenceRepo.Object, projectRepo.Object);
            var result = await executor.ProcessAsync(request) as GeofenceDataSingleResult;

            Assert.NotNull(result);
            Assert.Equal(geofenceToTest.GeofenceData.GeofenceUID, result.GeofenceData.GeofenceUID);
            Assert.Equal(geofenceToTest.GeofenceData.GeofenceName, result.GeofenceData.GeofenceName);
            Assert.Equal(geofenceToTest.GeofenceData.GeometryWKT, result.GeofenceData.GeometryWKT);
        }
Example #21
0
        public async Task GetFilterExecutor_Should_not_alter_existing_start_end_dates(int dateRangeType, bool asAtDate)
        {
            const string startDate = "2017-12-10T08:00:00Z";
            const string endDate   = "2017-12-10T20:09:59.108671Z";

            var filterType = FilterType.Transient;
            var name       = $"dateRangeType={dateRangeType},asAtDate={asAtDate}";

            var filterCreateEvent = new CreateFilterEvent
            {
                CustomerUID = Guid.NewGuid(),
                UserID      = TestUtility.UIDs.JWT_USER_ID,
                ProjectUID  = TestUtility.UIDs.MOCK_WEB_API_DIMENSIONS_PROJECT_UID,
                FilterUID   = Guid.NewGuid(),
                Name        = name,
                FilterType  = filterType,
                FilterJson  = $"{{\"startUtc\": \"{startDate}\",\"endUtc\": \"{endDate}\",\"dateRangeType\": {dateRangeType}, \"asAtDate\":\"{asAtDate}\"}}",
                ActionUTC   = DateTime.UtcNow
            };

            WriteEventToDb(filterCreateEvent);

            var request = CreateAndValidateRequest(customerUid: filterCreateEvent.CustomerUID.ToString(), userId: filterCreateEvent.UserID, projectUid: filterCreateEvent.ProjectUID.ToString(), filterUid: filterCreateEvent.FilterUID.ToString(), filterType: filterType, name: name);

            var projectData = new ProjectData {
                ProjectUID = filterCreateEvent.ProjectUID.ToString(), IanaTimeZone = "America/Los_Angeles"
            };

            var tcs = new TaskCompletionSource <List <ProjectData> >();

            tcs.SetResult(new List <ProjectData> {
                projectData
            });

            var projectProxy = new Mock <IProjectProxy>();

            projectProxy.Setup(x => x.GetProjects(filterCreateEvent.CustomerUID.ToString(), request.CustomHeaders)).Returns(() => tcs.Task);

            var executor = RequestExecutorContainer.Build <GetFilterExecutor>(ConfigStore, Logger, ServiceExceptionHandler, FilterRepo, null, projectProxy.Object);
            var result   = await executor.ProcessAsync(request) as FilterDescriptorSingleResult;

            Assert.IsNotNull(result, Responses.ShouldReturnResult);
            Assert.AreEqual(filterCreateEvent.FilterUID, Guid.Parse(result.FilterDescriptor.FilterUid), Responses.IncorrectFilterDescriptorFilterUid);

            dynamic filterObj = JsonConvert.DeserializeObject(result.FilterDescriptor.FilterJson);

            if (asAtDate)
            {
                Assert.IsNull(filterObj.startUtc);
            }
            else
            {
                Assert.AreEqual(DateTime.Parse(startDate).ToUniversalTime(), DateTime.Parse(filterObj.startUtc.ToString()));
            }

            Assert.AreEqual((DateTime.Parse(endDate).ToUniversalTime()).ToString(), filterObj.endUtc.ToString());
        }
Example #22
0
        public async Task Should_return_expected_boundary_When_object_exists_in_database()
        {
            var custUid     = Guid.NewGuid();
            var userId      = Guid.NewGuid();
            var projectUid  = Guid.NewGuid();
            var boundaryUid = Guid.NewGuid();
            var name        = "name";

            WriteEventToDb(new CreateGeofenceEvent
            {
                GeofenceUID  = boundaryUid,
                GeofenceType = GeofenceType.Filter.ToString(),
                CustomerUID  = custUid,
                UserUID      = userId,
                ActionUTC    = DateTime.UtcNow,
                GeometryWKT  = boundaryPolygon,
                GeofenceName = name,
                Description  = null
            });
            WriteEventToDb(new AssociateProjectGeofence
            {
                ProjectUID  = projectUid,
                GeofenceUID = boundaryUid,
                ActionUTC   = DateTime.UtcNow
            });

            var request = CreateAndValidateRequest(custUid, projectUid, userId, boundaryUid);

            var executor =
                RequestExecutorContainer.Build <GetBoundaryExecutor>(ConfigStore, Logger, ServiceExceptionHandler, GeofenceRepo, ProjectRepo);
            var result = await executor.ProcessAsync(request) as GeofenceDataSingleResult;

            var filterToTest = new GeofenceDataSingleResult(
                new GeofenceData
            {
                GeofenceUID   = boundaryUid,
                Description   = null,
                GeofenceName  = name,
                UserUID       = userId,
                GeometryWKT   = boundaryPolygon,
                GeofenceType  = GeofenceType.Filter.ToString(),
                CustomerUID   = custUid,
                FillColor     = 0,
                IsTransparent = false
            });

            Assert.IsNotNull(result, Responses.ShouldReturnResult);
            Assert.AreEqual(filterToTest.GeofenceData.GeofenceUID, result.GeofenceData.GeofenceUID);
            Assert.AreEqual(filterToTest.GeofenceData.Description, result.GeofenceData.Description);
            Assert.AreEqual(filterToTest.GeofenceData.GeofenceName, result.GeofenceData.GeofenceName);
            Assert.AreEqual(filterToTest.GeofenceData.UserUID, result.GeofenceData.UserUID);
            Assert.AreEqual(filterToTest.GeofenceData.GeometryWKT, result.GeofenceData.GeometryWKT);
            Assert.AreEqual(filterToTest.GeofenceData.GeofenceType, result.GeofenceData.GeofenceType);
            Assert.AreEqual(filterToTest.GeofenceData.CustomerUID, result.GeofenceData.CustomerUID);
            Assert.AreEqual(filterToTest.GeofenceData.FillColor, result.GeofenceData.FillColor);
            Assert.AreEqual(filterToTest.GeofenceData.IsTransparent, result.GeofenceData.IsTransparent);
        }
Example #23
0
        public async Task GetFiltersExecutor()
        {
            string custUid    = Guid.NewGuid().ToString();
            string userUid    = Guid.NewGuid().ToString();
            string projectUid = Guid.NewGuid().ToString();
            string filterUid  = Guid.NewGuid().ToString();
            string name       = "blah";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var filterRepo = new Mock <FilterRepository>(configStore, logger);
            var filters    = new List <MasterData.Repositories.DBModels.Filter>
            {
                new MasterData.Repositories.DBModels.Filter
                {
                    CustomerUid     = custUid,
                    UserId          = userUid,
                    ProjectUid      = projectUid,
                    FilterUid       = filterUid,
                    Name            = name,
                    FilterJson      = "{\"dateRangeType\":\"0\",\"elevationType\":null}",
                    FilterType      = FilterType.Persistent,
                    LastActionedUtc = DateTime.UtcNow
                }
            };

            filterRepo.As <IFilterRepository>().Setup(ps => ps.GetFiltersForProjectUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), false)).ReturnsAsync(filters);

            var filterListToTest = new FilterDescriptorListResult
            {
                FilterDescriptors = filters
                                    .Select(filter => AutoMapperUtility.Automapper.Map <FilterDescriptor>(filter))
                                    .ToImmutableList()
            };

            var request = FilterRequestFull.Create
                          (
                null,
                custUid,
                false,
                userUid,
                new ProjectData {
                ProjectUID = projectUid
            });

            var executor =
                RequestExecutorContainer.Build <GetFiltersExecutor>(configStore, logger, serviceExceptionHandler,
                                                                    filterRepo.Object, null);
            var filterListResult = await executor.ProcessAsync(request) as FilterDescriptorListResult;

            Assert.NotNull(filterListResult);
            Assert.Equal(filterListToTest.FilterDescriptors[0].FilterUid, filterListResult.FilterDescriptors[0].FilterUid);
            Assert.Equal(filterListToTest.FilterDescriptors[0].Name, filterListResult.FilterDescriptors[0].Name);
            Assert.Equal("{\"dateRangeType\":0,\"dateRangeName\":\"Today\"}", filterListResult.FilterDescriptors[0].FilterJson);
            Assert.Equal(filterListToTest.FilterDescriptors[0].FilterType, filterListResult.FilterDescriptors[0].FilterType);
        }
Example #24
0
        public void ClassInit()
        {
            Setup();

            executor = RequestExecutorContainer
                       .Build <UpsertFilterExecutor>(ConfigStore, Logger, ServiceExceptionHandler, FilterRepo, GeofenceRepo, ProjectProxy,
                                                     productivity3dV2ProxyNotification: Productivity3dV2ProxyNotification, productivity3dV2ProxyCompaction: Productivity3dV2ProxyCompaction,
                                                     fileImportProxy: FileImportProxy);
        }
Example #25
0
        public async Task UpsertBoundaryExecutor()
        {
            string custUid     = Guid.NewGuid().ToString();
            string userUid     = Guid.NewGuid().ToString();
            string projectUid  = Guid.NewGuid().ToString();
            string name        = "not entry";
            string geometryWKT = "whatever";

            var configStore = serviceProvider.GetRequiredService <IConfigurationStore>();
            var logger      = serviceProvider.GetRequiredService <ILoggerFactory>();

            var geofenceRepo = new Mock <GeofenceRepository>(configStore, logger);
            var geofence     = new Geofence
            {
                CustomerUID     = custUid,
                UserUID         = userUid,
                Name            = name,
                GeometryWKT     = geometryWKT,
                GeofenceType    = GeofenceType.Filter,
                LastActionedUTC = DateTime.UtcNow
            };

            geofenceRepo.As <IGeofenceRepository>().Setup(g => g.GetGeofence(It.IsAny <string>())).ReturnsAsync(geofence);
            geofenceRepo.As <IGeofenceRepository>().Setup(g => g.StoreEvent(It.IsAny <CreateGeofenceEvent>())).ReturnsAsync(1);

            var projectRepo = new Mock <ProjectRepository>(configStore, logger);

            projectRepo.As <IProjectRepository>().Setup(p => p.GetAssociatedGeofences(It.IsAny <string>())).ReturnsAsync(new List <ProjectGeofence>());
            projectRepo.As <IProjectRepository>().Setup(p => p.StoreEvent(It.IsAny <AssociateProjectGeofence>())).ReturnsAsync(1);

            var productivity3dV2ProxyNotification = new Mock <IProductivity3dV2ProxyNotification>();

            productivity3dV2ProxyNotification.Setup(ps => ps.NotifyFilterChange(It.IsAny <Guid>(), It.IsAny <Guid>(), null)).ReturnsAsync(new BaseMasterDataResult());

            var request = BoundaryRequestFull.Create
                          (
                custUid,
                false,
                new ProjectData {
                ProjectUID = projectUid
            },
                userUid,
                new BoundaryRequest {
                BoundaryUid = null, Name = name, BoundaryPolygonWKT = geometryWKT
            }
                          );

            var executor =
                RequestExecutorContainer.Build <UpsertBoundaryExecutor>(configStore, logger, serviceExceptionHandler,
                                                                        geofenceRepo.Object, projectRepo.Object);
            var result = await executor.ProcessAsync(request) as GeofenceDataSingleResult;

            Assert.NotNull(result);
            Assert.Equal(name, result.GeofenceData.GeofenceName);
            Assert.Equal(geometryWKT, result.GeofenceData.GeometryWKT);
        }
Example #26
0
        public Task <ContractExecutionResult> PostTagFile([FromBody] CompactionTagFileRequest request)
        {
            var serializedRequest = ConvertObjectForLogging.SerializeObjectIgnoringProperties(request, "Data");

            Log.LogInformation("PostTagFile: " + serializedRequest);

            return(WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainer
                                                       .Build <TagFileExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                       .ProcessAsync(request)));
        }
Example #27
0
        public T CreateExecutor <T>() where T : RequestExecutorContainer, new()
        {
            ConfigStore.Reset();
            DataCache.Reset();

            TRexTagFileProxy.Reset();
            TransferProxy.Reset();
            WebRequest.Reset();
            return(RequestExecutorContainer.Build <T>(LoggerFactory, ConfigStore.Object, DataCache.Object, TRexTagFileProxy.Object, TransferProxyFactory.Object, WebRequest.Object));
        }
Example #28
0
        public Task <ContractExecutionResult> PostDesignProfile([FromBody] DesignProfileRequest designProfileRequest)
        {
            Log.LogInformation($"{nameof(PostDesignProfile)}: {Request.QueryString}");

            designProfileRequest.Validate();

            return(WithServiceExceptionTryExecuteAsync(() =>
                                                       RequestExecutorContainer
                                                       .Build <DesignProfileExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                       .ProcessAsync(designProfileRequest)));
        }
Example #29
0
        public async Task GetFiltersExecutor_NoExistingFilter()
        {
            var request = CreateAndValidateRequest();

            var executor =
                RequestExecutorContainer.Build <GetFiltersExecutor>(ConfigStore, Logger, ServiceExceptionHandler, FilterRepo, null);
            var result = await executor.ProcessAsync(request) as FilterDescriptorListResult;

            Assert.IsNotNull(result, "executor should always return a result");
            Assert.AreEqual(0, result.FilterDescriptors.Count, "executor count is incorrect");
        }
Example #30
0
        public CCAColorPaletteResult GetCCAColorPalette([FromBody] CCAColorPaletteTrexRequest request)
        {
            Log.LogInformation($"{nameof(GetCCAColorPalette)}: {JsonConvert.SerializeObject(request)}");

            request.Validate();
            ValidateFilterMachines(nameof(GetCCAColorPalette), request.ProjectUid, request.Filter);
            return(WithServiceExceptionTryExecute(() =>
                                                  RequestExecutorContainer
                                                  .Build <PaletteExecutor>(ConfigStore, LoggerFactory, ServiceExceptionHandler)
                                                  .Process(request)) as CCAColorPaletteResult);
        }