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); }
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); }
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); }
/// <summary> /// Helper method to execute a request against 3dp and throw a service exception if the request fails /// </summary> private async Task <T> ExecuteRequest <T>(string baseEndPoint, Guid projectUid, Guid filterUid, Dictionary <string, string> additionalParams = null) where T : class, IMasterDataModel { var route = $"{baseEndPoint}?projectUid={projectUid}&filterUid={filterUid}"; if (additionalParams != null) { foreach (var(key, value) in additionalParams) { route += $"&{key}={value}"; } } var result = await _productivity3dV2ProxyCompaction.ExecuteGenericV2Request <T>(route, HttpMethod.Get, null, CustomHeaders); if (result != null) { return(result); } ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.GeneralError, null, "No Data"); return(null); }
public async Task <IActionResult> VolumesReport([FromQuery, BindRequired] SimpleFilter filter) { Log.LogInformation($"VolumesReport Filter: {filter}"); // Ground to design only // SummaryVolumesRequest // Returns SummaryVolumesResult var filterUid = await ConvertSimpleFilter(filter); // Base UID needs to be filter // Top UID needs to be design var route = $"/volumes/summary?projectUid={filter.ProjectUid}&baseUid={filterUid}&topUid={filter.DesignFileUid}"; var result = await _productivity3dV2ProxyCompaction.ExecuteGenericV2Request <CompactionVolumesSummaryResult>(route, HttpMethod.Get, null, CustomHeaders); if (result != null) { return(Json(result)); } ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.GeneralError, null, "No Data"); return(null); }
public async Task <ImportedFileDescriptorSingleResult> CreateImportedFileDirectV6( [FromServices] ISchedulerProxy schedulerProxy, Guid projectUid, string filename, ImportedFileType importedFileType, DxfUnitsType dxfUnitsType, DateTime fileCreatedUtc, DateTime fileUpdatedUtc, DateTime?surveyedUtc = null) { if (importedFileType == ImportedFileType.ReferenceSurface) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 122); } FileImportDataValidator.ValidateUpsertImportedFileRequest(projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, UserEmailAddress, surveyedUtc, filename, null, null); Logger.LogInformation( $"{nameof(CreateImportedFileDirectV6)}: ProjectUID: `{projectUid}`, Filename: `{filename}` ImportedFileType: `{importedFileType}`, DxfUnitsType: `{dxfUnitsType}`, SurveyedUTC: `{(surveyedUtc == null ? "N/A" : surveyedUtc.ToString())}`"); //When debugging locally using Postman, remove this check so can do an update await ValidateFileDoesNotExist(projectUid.ToString(), filename, importedFileType, surveyedUtc, null, null); if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 58, $"Expected a multipart request, but got '{Request.ContentType}'"); } var tempFilePath = await HttpContext.Request.StreamFile(Guid.NewGuid().ToString(), Logger); var result = await UpsertFile(tempFilePath, filename, projectUid.ToString(), importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, surveyedUtc, schedulerProxy); return(result); }
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); }
public async Task <ContractExecutionResult> CreateReferenceSurface( [FromQuery] Guid projectUid, [FromQuery] string filename, [FromQuery] DateTime fileCreatedUtc, [FromQuery] DateTime fileUpdatedUtc, [FromQuery] Guid parentUid, [FromQuery] double offset, [FromServices] ISchedulerProxy schedulerProxy, [FromServices] IPreferenceProxy prefProxy) { Logger.LogInformation($"{nameof(CreateReferenceSurface)}: projectUid {projectUid} filename: {filename} parentUid: {parentUid} offset: {offset}"); await ValidateProjectId(projectUid.ToString()); //Check parent design does exist var importedFiles = await ImportedFileRequestDatabaseHelper.GetImportedFileList(projectUid.ToString(), Logger, UserId, ProjectRepo); var parent = importedFiles.FirstOrDefault(i => i.ImportedFileUid == parentUid.ToString()); if (parent == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 120); } //Fill in file name if not provided if (string.IsNullOrEmpty(filename)) { filename = await DefaultReferenceSurfaceName(prefProxy, offset, Path.GetFileNameWithoutExtension(parent.Name)); } //Validate parameters FileImportDataValidator.ValidateUpsertImportedFileRequest(projectUid, ImportedFileType.ReferenceSurface, DxfUnitsType.Meters, fileCreatedUtc, fileUpdatedUtc, UserEmailAddress, null, filename, parentUid, offset); //Check reference surface does not exist await ValidateFileDoesNotExist(projectUid.ToString(), filename, ImportedFileType.ReferenceSurface, null, parentUid, offset); var importedFileResult = await UpsertFileInternal(filename, null, projectUid, ImportedFileType.ReferenceSurface, DxfUnitsType.Meters, fileCreatedUtc, fileUpdatedUtc, null, schedulerProxy, parentUid, offset); //If parent design is deactivated then deactivate reference surface if (!parent.IsActivated) { var filesToUpdate = new Dictionary <Guid, bool>(); filesToUpdate.Add(new Guid(importedFileResult.ImportedFileDescriptor.ImportedFileUid), false); await DoActivationAndNotification(projectUid.ToString(), filesToUpdate); importedFiles = await ImportedFileRequestDatabaseHelper.GetImportedFileList(projectUid.ToString(), Logger, UserId, ProjectRepo); importedFileResult.ImportedFileDescriptor = importedFiles.SingleOrDefault(i => i.ImportedFileUid == importedFileResult.ImportedFileDescriptor.ImportedFileUid); } Logger.LogInformation( $"{nameof(CreateReferenceSurface)}: Completed successfully. Response: {JsonConvert.SerializeObject(importedFileResult)}"); return(importedFileResult); }
public async Task <ScheduleJobResult> BackgroundUpload( FlowFile file, [FromQuery] Guid projectUid, [FromQuery] ImportedFileType importedFileType, [FromQuery] DxfUnitsType dxfUnitsType, [FromQuery] DateTime fileCreatedUtc, [FromQuery] DateTime fileUpdatedUtc, [FromQuery] DateTime?surveyedUtc, [FromServices] ISchedulerProxy scheduler, [FromServices] ITransferProxyFactory transferProxyFactory) { if (importedFileType == ImportedFileType.ReferenceSurface) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 122); } FlowJsFileImportDataValidator.ValidateUpsertImportedFileRequest( file, projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, UserEmailAddress, surveyedUtc, null, null); Logger.LogInformation( $"{nameof(BackgroundUpload)}: file: {file.flowFilename} path {file.path} projectUid {projectUid} ImportedFileType: {importedFileType} " + $"DxfUnitsType: {dxfUnitsType} surveyedUtc {(surveyedUtc == null ? "N/A" : surveyedUtc.ToString())}"); if (string.Equals(Request.Method, HttpMethod.Post.ToString(), StringComparison.OrdinalIgnoreCase)) { await ValidateFileDoesNotExist(projectUid.ToString(), file.flowFilename, importedFileType, surveyedUtc, null, null); } var s3Path = $"project/importedfile/{Guid.NewGuid()}.dat"; var fileStream = System.IO.File.Open(file.path, FileMode.Open, FileAccess.Read); var transferProxy = transferProxyFactory.NewProxy(TransferProxyType.Temporary); transferProxy.Upload(fileStream, s3Path); var baseUrl = Request.Host.ToUriComponent(); // The QueryString will have values in it, so it's safe to add extra queries with the & as opposed to ?, then & var callbackUrl = $"http://{baseUrl}/internal/v6/importedfile{Request.QueryString}"; callbackUrl += $"&filename={WebUtility.UrlEncode(file.flowFilename)}&awsFilePath={WebUtility.UrlEncode(s3Path)}"; Logger.LogInformation($"{nameof(BackgroundUpload)}: baseUrl {callbackUrl}"); var executionTimeout = ConfigStore.GetValueInt("PEGASUS_EXECUTION_TIMEOUT_MINS", 5) * 60000;//minutes converted to millisecs var request = new ScheduleJobRequest { Filename = file.flowFilename, Method = "GET", // match the internal upload Method Url = callbackUrl, Timeout = executionTimeout }; request.SetStringPayload(string.Empty); var headers = Request.Headers.GetCustomHeaders(); return(await scheduler.ScheduleBackgroundJob(request, headers)); }
public ReturnSuccessV5Result ValidateTccAuthorization( [FromBody] ValidateTccAuthorizationRequest tccAuthorizationRequest) { if (tccAuthorizationRequest == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.InternalServerError, 86); } Logger.LogInformation($"{nameof(ValidateTccAuthorization)}: completed successfully"); return(ReturnSuccessV5Result.CreateReturnSuccessV5Result(HttpStatusCode.OK, true)); }
public async Task <ImportedFileDescriptorSingleResult> InternalImportedFileV6( [FromQuery] string filename, [FromQuery] string awsFilePath, [FromQuery] Guid projectUid, [FromQuery] ImportedFileType importedFileType, [FromQuery] DxfUnitsType dxfUnitsType, [FromQuery] DateTime fileCreatedUtc, [FromQuery] DateTime fileUpdatedUtc, [FromQuery] DateTime?surveyedUtc, [FromServices] ITransferProxyFactory transferProxyFactory, [FromServices] ISchedulerProxy schedulerProxy) { if (importedFileType == ImportedFileType.ReferenceSurface) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 122); } ImportedFileDescriptorSingleResult importedFileResult = null; var transferProxy = transferProxyFactory.NewProxy(TransferProxyType.Temporary); Logger.LogInformation( $"{nameof(InternalImportedFileV6)}:. filename: {filename} awspath {awsFilePath} projectUid {projectUid} ImportedFileType: {importedFileType} " + $"DxfUnitsType: {dxfUnitsType} surveyedUtc {(surveyedUtc == null ? "N/A" : surveyedUtc.ToString())}"); // Retrieve the stored file from AWS var fileResult = await transferProxy.Download(awsFilePath); if (fileResult == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.InternalServerError, 55); } using (var ms = new MemoryStream()) { // Depending on the size of the file in S3, the stream returned may or may not support seeking // Which we need to TCC to know the length of the file (can't find the length, if you can't seek). // To solve this, we have to download the entire stream here and copy to memory. // Allowing TCC to upload the file. // Not the best solution for extra large files, but TCC doesn't support uploading without file size AFAIK fileResult.FileStream.CopyTo(ms); importedFileResult = await UpsertFileInternal(filename, ms, projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, surveyedUtc, schedulerProxy); } Logger.LogInformation( $"{nameof(InternalImportedFileV6)}: Completed successfully. Response: {JsonConvert.SerializeObject(importedFileResult)}"); return(importedFileResult); }
/// <summary> /// Validates a project identifier. /// </summary> protected async Task ValidateProjectId(string projectUid) { LogCustomerDetails("GetProject", projectUid); var project = (await ProjectRequestHelper.GetProjectListForCustomer(new Guid(CustomerUid), new Guid(UserId), Logger, ServiceExceptionHandler, CwsProjectClient, null, null, true, false, customHeaders)) .FirstOrDefault(p => string.Equals(p.ProjectUID, projectUid, StringComparison.OrdinalIgnoreCase)); if (project == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 1); } Logger.LogInformation($"Project {JsonConvert.SerializeObject(project)} retrieved"); }
public async Task <ContractExecutionResult> DeleteImportedFileV6( [FromQuery] Guid projectUid, [FromQuery] Guid?importedFileUid, // for 3dpm imported files [FromServices] IPegasusClient pegasusClient, [FromServices] IWebClientWrapper webClient) { Logger.LogInformation($"{nameof(DeleteImportedFileV6)}: projectUid {projectUid} importedFileUid: {importedFileUid}"); await ValidateProjectId(projectUid.ToString()); var importedFiles = await ImportedFileRequestDatabaseHelper.GetImportedFiles(projectUid.ToString(), Logger, ProjectRepo).ConfigureAwait(false); ImportedFile existing = null; if (importedFiles.Count > 0) { existing = importedFiles.FirstOrDefault(f => f.ImportedFileUid == importedFileUid.ToString()); } if (existing == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 56); return(new ContractExecutionResult(ContractExecutionStatesEnum.InternalProcessingError, "shouldn't get here")); // to keep compiler happy } var deleteImportedFile = new DeleteImportedFile( projectUid, existing.ImportedFileType, JsonConvert.DeserializeObject <FileDescriptor>(existing.FileDescriptor), Guid.Parse(existing.ImportedFileUid), existing.ImportedFileId, existing.LegacyImportedFileId, DataOceanRootFolderId, existing.SurveyedUtc); var result = await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory .Build <DeleteImportedFileExecutor>( LoggerFactory, ConfigStore, ServiceExceptionHandler, CustomerUid, UserId, UserEmailAddress, customHeaders, persistantTransferProxyFactory : persistantTransferProxyFactory, filterServiceProxy : filterServiceProxy, tRexImportFileProxy : tRexImportFileProxy, projectRepo : ProjectRepo, dataOceanClient : DataOceanClient, authn : Authorization, pegasusClient : pegasusClient, cwsProjectClient : CwsProjectClient) .ProcessAsync(deleteImportedFile) ); await NotificationHubClient.Notify(new ProjectChangedNotification(projectUid)); Logger.LogInformation( $"{nameof(DeleteImportedFileV6)}: Completed successfully. projectUid {projectUid} importedFileUid: {importedFileUid}"); return(result); }
/// <summary> /// Common file processing method used by all importedFile endpoints. /// </summary> private async Task <ImportedFileDescriptorSingleResult> UpsertFile( string tmpFilePath, string filename, string projectUid, ImportedFileType importedFileType, DxfUnitsType dxfUnitsType, DateTime fileCreatedUtc, DateTime fileUpdatedUtc, DateTime?surveyedUtc, ISchedulerProxy schedulerProxy) { if (!System.IO.File.Exists(tmpFilePath)) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 55); } using (var fileStream = new FileStream(tmpFilePath, FileMode.Open)) { return(await UpsertFileInternal(filename, fileStream, Guid.Parse(projectUid), importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, surveyedUtc, schedulerProxy)); } }
public async Task <ImportedFileDescriptorSingleResult> SyncUpload( [FromServices] ISchedulerProxy schedulerProxy, FlowFile file, [FromQuery] Guid projectUid, [FromQuery] ImportedFileType importedFileType, [FromQuery] DxfUnitsType dxfUnitsType, [FromQuery] DateTime fileCreatedUtc, [FromQuery] DateTime fileUpdatedUtc, [FromQuery] DateTime?surveyedUtc) { if (importedFileType == ImportedFileType.ReferenceSurface) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 122); } // Validate the file FlowJsFileImportDataValidator.ValidateUpsertImportedFileRequest( file, projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, UserEmailAddress, surveyedUtc, null, null); Logger.LogInformation( $"{nameof(SyncUpload)}: file: {file.flowFilename} path {file.path} projectUid {projectUid} ImportedFileType: {importedFileType} " + $"DxfUnitsType: {dxfUnitsType} surveyedUtc {(surveyedUtc == null ? "N/A" : surveyedUtc.ToString())}"); await ValidateFileDoesNotExist(projectUid.ToString(), file.flowFilename, importedFileType, surveyedUtc, null, null); ContractExecutionResult importedFileResult; using (var fileStream = System.IO.File.Open(file.path, FileMode.Open, FileAccess.Read)) { importedFileResult = await UpsertFileInternal(file.flowFilename, fileStream, projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, surveyedUtc, schedulerProxy); } Logger.LogInformation( $"{nameof(SyncUpload)}: Completed successfully. Response: {JsonConvert.SerializeObject(importedFileResult)}"); return(importedFileResult as ImportedFileDescriptorSingleResult); }
public Task <ImportedFileDescriptorSingleResult> UpsertImportedFileV6( [FromServices] ISchedulerProxy schedulerProxy, FlowFile file, [FromQuery] Guid projectUid, [FromQuery] ImportedFileType importedFileType, [FromQuery] DxfUnitsType dxfUnitsType, [FromQuery] DateTime fileCreatedUtc, [FromQuery] DateTime fileUpdatedUtc, [FromQuery] DateTime?surveyedUtc = null) { if (importedFileType == ImportedFileType.ReferenceSurface) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 122); } FlowJsFileImportDataValidator.ValidateUpsertImportedFileRequest(file, projectUid, importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, UserEmailAddress, surveyedUtc, null, null); Logger.LogInformation( $"{nameof(UpsertImportedFileV6)}: file: {JsonConvert.SerializeObject(file)} projectUid {projectUid} ImportedFileType: {importedFileType} DxfUnitsType: {dxfUnitsType} surveyedUtc {(surveyedUtc == null ? "N/A" : surveyedUtc.ToString())}"); return(UpsertFile(file.path, file.flowFilename, projectUid.ToString(), importedFileType, dxfUnitsType, fileCreatedUtc, fileUpdatedUtc, surveyedUtc, schedulerProxy)); }
/// <summary> /// Validate that the uploaded file doesn't already exist in the database. /// Should only be called from create methods where there's an expectation the file isn't already present. /// </summary> private async Task ValidateFileDoesNotExist(string projectUid, string filename, ImportedFileType importedFileType, DateTime?surveyedUtc, Guid?parentUid, double?offset) { var fileExists = false; var importedFileList = ImportedFileRequestDatabaseHelper.GetImportedFileList(projectUid, Logger, UserId, ProjectRepo) .ConfigureAwait(false) .GetAwaiter() .GetResult(); ImportedFileDescriptor importedFileDescriptor = null; if (importedFileList.Count > 0) { if (importedFileType == ImportedFileType.ReferenceSurface) { importedFileDescriptor = importedFileList.FirstOrDefault( f => f.ImportedFileType == ImportedFileType.ReferenceSurface && f.ParentUid == parentUid && f.Offset.EqualsToNearestMillimeter(offset)); } else { importedFileDescriptor = importedFileList.FirstOrDefault( f => string.Equals(f.Name, filename, StringComparison.OrdinalIgnoreCase) && f.ImportedFileType == importedFileType && (importedFileType != ImportedFileType.SurveyedSurface || f.SurveyedUtc == surveyedUtc)); } } fileExists = importedFileDescriptor != null; if (fileExists) { var message = $"{nameof(ValidateFileDoesNotExist)}: File: {filename} has already been imported."; Logger.LogError(message); ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, importedFileType == ImportedFileType.ReferenceSurface ? 121 : 58); } }
/// <summary> /// Convert a simple filter into a Real Filter via the Filter service /// </summary> /// <returns>Filter UID</returns> private async Task <Guid> ConvertSimpleFilter(SimpleFilter simpleFilter) { if (simpleFilter == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure, null, "No Simple Filter found"); } var project = await _projectProxy.GetProjectForCustomer(CustomerUid, simpleFilter.ProjectUid, CustomHeaders); if (project == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure, null, $"Cannot find project {simpleFilter.ProjectUid} for Customer {CustomerUid}"); } var file = await _fileImportProxy.GetFileForProject(simpleFilter.ProjectUid, UserId, simpleFilter.DesignFileUid, CustomHeaders); if (file == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.FilterConvertFailure, null, $"Cannot find file {simpleFilter.DesignFileUid} for project {simpleFilter.ProjectUid}"); } var filterModel = new Filter.Abstractions.Models.Filter(simpleFilter.StartDateUtc, simpleFilter.EndDateUtc, simpleFilter.DesignFileUid, file.Name, null, null, null, null, null, null, simpleFilter.LiftNumber); var filterRequest = FilterRequest.Create(filterModel); var result = await _filterServiceProxy.CreateFilter(simpleFilter.ProjectUid, filterRequest, CustomHeaders); if (result.Code != 0) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, (int)Now3DExecutionStates.ErrorCodes.DataError, result.Code.ToString(), result.Message); } var guid = Guid.Parse(result.FilterDescriptor.FilterUid); Log.LogInformation($"Converted Simple filter '{JsonConvert.SerializeObject(simpleFilter)}' to a " + $"{nameof(FilterRequest)}: '{JsonConvert.SerializeObject(filterRequest)}'. FilterUID: {guid}"); return(guid); }
public async Task <IActionResult> UpdateImportedFileActivationStateV6(string projectUid, [FromBody] ActivatedImportFilesRequest request) { Logger.LogInformation($"{nameof(UpdateImportedFileActivationStateV6)}:"); await ValidateProjectId(projectUid).ConfigureAwait(false); if (request == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.InternalServerError, 40); } var fileIds = string.Join(",", request.ImportedFileDescriptors.Select(x => x.ImportedFileUid)); if (string.IsNullOrEmpty(fileIds)) { return(Ok(new { Code = HttpStatusCode.BadRequest, Message = "Request contains no imported file IDs." })); } Logger.LogInformation($"{nameof(UpdateImportedFileActivationStateV6)}: projectUid: {projectUid}, fileUids: {fileIds}"); var importedFiles = await ImportedFileRequestDatabaseHelper.GetImportedFileList(projectUid, Logger, UserId, ProjectRepo).ConfigureAwait(false); if (!importedFiles.Any()) { Logger.LogInformation($"{nameof(UpdateImportedFileActivationStateV6)}: Attempt to set file activation state when project contains no files"); return(Ok(new { Code = HttpStatusCode.BadRequest, Message = "Project contains no imported files." })); } var filesToUpdate = new Dictionary <Guid, bool>(); foreach (var activatedFileDescriptor in request.ImportedFileDescriptors) { var existingFile = importedFiles.FirstOrDefault(f => f.ImportedFileUid == activatedFileDescriptor.ImportedFileUid); if (existingFile == null) { Logger.LogError( $"{nameof(UpdateImportedFileActivationStateV6)}: File doesn't exist. projectUid {projectUid}, fileUid: {activatedFileDescriptor.ImportedFileUid}"); continue; } if (existingFile.ImportedFileType == ImportedFileType.ReferenceSurface) { Logger.LogError( $"{nameof(UpdateImportedFileActivationStateV6)}: Attempt to set file activation on a reference surface. projectUid {projectUid}, fileUid: {activatedFileDescriptor.ImportedFileUid}"); continue; } if (existingFile.IsActivated == activatedFileDescriptor.IsActivated) { Logger.LogDebug( $"{nameof(UpdateImportedFileActivationStateV6)}: File activation state is already set to {existingFile.IsActivated}. No changes required. {existingFile.ImportedFileUid}"); continue; } Logger.LogInformation( $"{nameof(UpdateImportedFileActivationStateV6)}: File queued for updating: {JsonConvert.SerializeObject(existingFile)}"); filesToUpdate.Add(new Guid(activatedFileDescriptor.ImportedFileUid), activatedFileDescriptor.IsActivated); //If user is activating or deactivating a design which has reference surfaces, do as a group if (existingFile.ImportedFileType == ImportedFileType.DesignSurface) { var children = importedFiles .Where(f => f.ParentUid.HasValue && f.ParentUid.ToString() == existingFile.ImportedFileUid).ToList(); if (children.Count > 0) { Logger.LogInformation( $"{nameof(UpdateImportedFileActivationStateV6)}: Setting file activation state of reference surfaces for design {existingFile.ImportedFileUid}"); foreach (var child in children) { if (child.IsActivated != activatedFileDescriptor.IsActivated) { filesToUpdate.Add(new Guid(child.ImportedFileUid), activatedFileDescriptor.IsActivated); } } } } } if (!filesToUpdate.Any()) { Logger.LogInformation($"{nameof(UpdateImportedFileActivationStateV6)}: No files eligible for activation state change."); return(Ok(new { Code = HttpStatusCode.OK, Message = "Success" })); } try { await DoActivationAndNotification(projectUid, filesToUpdate); return(Ok(new { Code = HttpStatusCode.OK, Message = "Success" })); } catch (Exception exception) { return(new JsonResult(new { Code = HttpStatusCode.InternalServerError, exception.GetBaseException().Message })); } }
public async Task <ReturnLongV5Result> CreateProjectTBC([FromBody] CreateProjectV5Request projectRequest) { if (projectRequest == null) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.InternalServerError, 81); } Logger.LogInformation($"{nameof(CreateProjectTBC)} projectRequest: {JsonConvert.SerializeObject(projectRequest)}"); var projectValidation = MapV5Models.MapCreateProjectV5RequestToProjectValidation(projectRequest, CustomerUid); projectRequest.CoordinateSystem = ProjectDataValidator.ValidateBusinessCentreFile(projectRequest.CoordinateSystem); // Read CoordSystem file from TCC as byte[]. projectValidation.CoordinateSystemFileContent = await TccHelper .GetFileContentFromTcc(projectRequest.CoordinateSystem, Logger, ServiceExceptionHandler, FileRepo).ConfigureAwait(false); try { var resultPolygonWkt = PolygonUtils.MakeCounterClockwise(projectValidation.ProjectBoundaryWKT, out var hasBeenReversed); if (hasBeenReversed) { Logger.LogInformation($"{nameof(CreateProjectTBC)} Boundary has been reversed to: {projectValidation.ProjectBoundaryWKT}"); projectValidation.ProjectBoundaryWKT = resultPolygonWkt; } } catch (Exception e) { Logger.LogError(e, $"{nameof(CreateProjectTBC)} Boundary orientation check threw exception: "); throw; } var validationResult = await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory .Build <ValidateProjectExecutor>(LoggerFactory, ConfigStore, ServiceExceptionHandler, CustomerUid, UserId, null, customHeaders, Productivity3dV1ProxyCoord, cwsProjectClient : CwsProjectClient) .ProcessAsync(projectValidation) ); if (validationResult.Code != ContractExecutionStatesEnum.ExecutedSuccessfully) { ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, validationResult.Code); } var result = (await WithServiceExceptionTryExecuteAsync(() => RequestExecutorContainerFactory .Build <CreateProjectTBCExecutor>(LoggerFactory, ConfigStore, ServiceExceptionHandler, CustomerUid, UserId, null, customHeaders, Productivity3dV1ProxyCoord, dataOceanClient: DataOceanClient, authn: Authorization, cwsProjectClient: CwsProjectClient, cwsDeviceClient: CwsDeviceClient, cwsProfileSettingsClient: CwsProfileSettingsClient) .ProcessAsync(projectValidation)) as ProjectV6DescriptorsSingleResult ); Logger.LogInformation($"{nameof(CreateProjectTBC)}: completed successfully. ShortProjectId {result.ProjectDescriptor.ShortRaptorProjectId}"); return(ReturnLongV5Result.CreateLongV5Result(HttpStatusCode.Created, result.ProjectDescriptor.ShortRaptorProjectId)); }