コード例 #1
0
 public ActionResult <PreviewResponse> PreviewPdf(Stream stream, int pageIndex)
 {
     try
     {
         if (stream.Length == 0)
         {
             throw new Exception("Поток не может быть пуст");
         }
         if (pageIndex < 0)
         {
             throw new Exception("Номер страницы не может быть меньше 0");
         }
         _logger.LogDebug($"Start create preview");
         PreviewResponse     responsePreview = new PreviewResponse();
         PreviewFileResponse previewResult   = _fileInfoPdf.Preview(stream, pageIndex);
         responsePreview.Values.Add(previewResult);
         _logger.LogDebug("PdfController.PreviewPdf() OK");
         return(Ok(responsePreview));
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(BadRequest(e.Message));
     }
 }
コード例 #2
0
    public IEnumerator NetworkManager(UnityWebRequest uWR)
    {
        // send request and wait for response
        yield return(uWR.SendWebRequest());

        if (uWR.isNetworkError || uWR.isHttpError)
        {
            Debug.LogError("Network error");
            yield break;
        }

        //Debug.Log("Status Code: " + uWR.responseCode);
        //Debug.Log("Number of Bytes: " + uWR.downloadedBytes);

        else if (uWR.isDone)
        {
            var previewResponse = new PreviewResponse();
            /*previewResponse.DeserializePreviewResponse(uWR.downloadHandler.text);*/

            //JSON = uWR.downloadHandler.text;
            //yield break;
        }

        /*if (uWR.responseCode == 200)
         * {
         *
         *  _jsonResponse = uWR.downloadHandler.text;
         *  //Debug.Log(uWR.downloadHandler.text);
         *  Debug.Log(_jsonResponse);
         * }*/

        //byte[] _byte = Encoding.UTF8.GetBytes(request.downloadHandler.text);
        //string results = request.downloadHandler.text;
    }
コード例 #3
0
        public override async Task RunExampleAsync()
        {
            PreviewSms previewClient = new PreviewSms(BASIC_AUTH_CONFIGURATION);

            PreviewRequest request = new PreviewRequest()
            {
                Text            = "Artık Ulusal Dil Tanımlayıcısı ile Türkçe karakterli smslerinizi rahatlıkla iletebilirsiniz.",
                LanguageCode    = "TR",
                Transliteration = "TURKISH"
            };

            PreviewResponse response = await previewClient.ExecuteAsync(request);

            Console.WriteLine("Original text: ");
            Console.WriteLine("\t" + response.OriginalText);
            Console.WriteLine("Previews:");
            foreach (Preview preview in response.Previews)
            {
                Console.WriteLine("\t------------------------------------------------");
                Console.WriteLine("\tText preview: " + preview.TextPreview);
                Console.WriteLine("\tNumber of messages: " + preview.MessageCount);
                Console.WriteLine("\tCharacters remaining: " + preview.CharactersRemaining);
                Console.WriteLine("\tConfiguration: " + JsonConvert.SerializeObject(preview.Configuration));
            }
            Console.WriteLine("\t------------------------------------------------");
        }
コード例 #4
0
    public static void Display()
    {
        Text text = GameObject.FindGameObjectWithTag("PreviewResponseText").GetComponent <Text>();

        //Debug.Log(JsonPreviewResponse);

        var previewResponse = PreviewResponse.DeserializePreviewResponse(JsonPreviewResponse);

        if (previewResponse.Features.Count == 0)
        {
            text.text = "No licenses available";
        }

        else
        {
            foreach (var feature in previewResponse.Features)
            {
                var timeSpan = feature.expires - DateTime.Today;
                var days     = timeSpan.Days;

                //Debug.Log("Feature: " + $"{feature.name}" + "\t\tAvailable: " + $"{feature.count}" + "\t\tTotal: " + $"{feature.maxCount}" + "\t\tExpiration: " + $"{feature.expires.ToLongDateString()}");
                text.text = "Feature: " + $"{feature.name}" + "\t\t\tAvailable: " + $"{feature.count}" + "\t\tTotal: "
                            + $"{feature.maxCount}" + "\t\t\tLicense Expiry: " + $"{feature.entitlementExpiry}" + "\t\tMax Borrow: " + $"{days}" + " days";
            }
        }
    }
        public async Task ValidateAsync_WhenSourceCodeDoesNotCompile_ValidIsFalse()
        {
            //Arrange
            CalculationEditModel model = CreateModel();

            PreviewResponse previewResponse = new PreviewResponse
            {
                CompilerOutput = new Build
                {
                    CompilerMessages = new List <CompilerMessage>
                    {
                        new CompilerMessage {
                            Message = "Failed"
                        }
                    }
                }
            };

            IPreviewService previewService = CreatePreviewService(previewResponse);

            CalculationEditModelValidator validator = CreateValidator(previewService: previewService);

            //Act
            ValidationResult result = await validator.ValidateAsync(model);

            //Assert
            result
            .IsValid
            .Should()
            .BeFalse();
        }
コード例 #6
0
        public async Task ValidateAsync_WhenSourceCodeDoesNotCompile__ValidIsFalse()
        {
            //Arrange
            CalculationCreateModel model = CreateModel();

            model.CalculationType = CalculationType.Additional;

            ICalculationsRepository calculationsRepository = CreateCalculationRepository();

            calculationsRepository
            .GetCalculationsBySpecificationIdAndCalculationName(Arg.Is(model.SpecificationId), Arg.Is(model.Name))
            .Returns((Calculation)null);

            SpecModel.SpecificationSummary specificationSummary = new SpecModel.SpecificationSummary
            {
                Name           = "spec name",
                FundingStreams = new[] { new Reference(model.FundingStreamId, "funding stream name") }
            };

            ISpecificationsApiClient specificationsApiClient = CreateSpecificationsApiClient();

            specificationsApiClient
            .GetSpecificationSummaryById(Arg.Is(model.SpecificationId))
            .Returns(new Common.ApiClient.Models.ApiResponse <SpecModel.SpecificationSummary>(HttpStatusCode.OK, specificationSummary));

            PreviewResponse previewResponse = new PreviewResponse
            {
                CompilerOutput = new Build
                {
                    CompilerMessages = new List <CompilerMessage>
                    {
                        new CompilerMessage {
                            Message = "Failed"
                        }
                    }
                }
            };

            IPreviewService previewService = CreatePreviewService(previewResponse);

            CalculationCreateModelValidator validator = CreateValidator(
                calculationsRepository, previewService: previewService, specificationsApiClient: specificationsApiClient);

            //Act
            ValidationResult result = await validator.ValidateAsync(model);

            //Assert
            result
            .IsValid
            .Should()
            .BeFalse();

            result.Errors
            .Should()
            .Contain(_ => _.ErrorMessage == "There are errors in the source code provided");
        }
コード例 #7
0
        public async Task CompilePreview_OnSuccessfulSaveRequest_ThenResponseSentToClient()
        {
            // Arrange
            ICalculationsApiClient calcsClient = Substitute.For <ICalculationsApiClient>();
            IMapper mapper = MappingHelper.CreateFrontEndMapper();

            string calculationId   = "5";
            string specificationId = "65";

            IAuthorizationHelper  authorizationHelper = TestAuthHelper.CreateAuthorizationHelperSubstitute(specificationId, SpecificationActionTypes.CanEditCalculations);
            CalculationController controller          = CreateCalculationController(calcsClient, mapper, authorizationHelper, resultsApiClient);

            PreviewCompileRequestViewModel previewViewModel = new PreviewCompileRequestViewModel()
            {
                SourceCode = "Updated source code",
            };

            PreviewResponse apiResultCalculation = new PreviewResponse()
            {
                CompilerOutput = new Build()
                {
                    Success = true,
                }
            };

            calcsClient
            .PreviewCompile(Arg.Any <PreviewRequest>())
            .Returns(new ApiResponse <PreviewResponse>(HttpStatusCode.OK, apiResultCalculation));

            // Act
            IActionResult result = await controller.CompilePreview(specificationId, calculationId, previewViewModel);

            // Assert
            result.Should().NotBeNull();
            result.Should().BeOfType <OkObjectResult>();

            OkObjectResult  typedResult   = result as OkObjectResult;
            PreviewResponse previewResult = typedResult.Value as PreviewResponse;

            previewResult.CompilerOutput.Success.Should().Be(apiResultCalculation.CompilerOutput.Success);

            await authorizationHelper
            .DidNotReceive()
            .DoesUserHavePermission(Arg.Any <ClaimsPrincipal>(), Arg.Any <string>(), Arg.Any <SpecificationActionTypes>());
        }
コード例 #8
0
        public async Task <IActionResult> CompilePreview([FromRoute] string specificationId, [FromRoute] string calculationId
                                                         , [FromBody] PreviewCompileRequestViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                PreviewResponse errorResponse = new PreviewResponse();

                foreach (var modelStateValue in ModelState.Values)
                {
                    errorResponse.CompilerOutput = new Build
                    {
                        CompilerMessages = new List <CompilerMessage>
                        {
                            new CompilerMessage {
                                Message = modelStateValue.Errors[0].ErrorMessage
                            }
                        }
                    };
                }

                return(BadRequest(errorResponse));
            }

            PreviewRequest request = _mapper.Map <PreviewRequest>(vm);

            request.CalculationId   = calculationId;
            request.SpecificationId = specificationId;
            request.ProviderId      = vm.ProviderId;

            ApiResponse <PreviewResponse> response = await _calcClient.PreviewCompile(request);

            if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest)
            {
                return(Ok(response.Content));
            }

            throw new InvalidOperationException($"An error occurred while compiling calculation. Status code={response.StatusCode}");
        }
コード例 #9
0
        private static IPreviewService CreatePreviewService(PreviewResponse previewResponse = null)
        {
            if (previewResponse == null)
            {
                previewResponse = new PreviewResponse
                {
                    CompilerOutput = new Build
                    {
                        CompilerMessages = new List <CompilerMessage>()
                    }
                };
            }

            OkObjectResult okObjectResult = new OkObjectResult(previewResponse);

            IPreviewService previewService = Substitute.For <IPreviewService>();

            previewService
            .Compile(Arg.Any <PreviewRequest>())
            .Returns(okObjectResult);

            return(previewService);
        }
コード例 #10
0
    public static PreviewResponse DeserializePreviewResponse(string jsonString)
    {
        //Text text = GameObject.FindGameObjectWithTag("Display").GetComponent<Text>();

        var previewResponse = new PreviewResponse();

        previewResponse = JsonConvert.DeserializeObject <PreviewResponse>(jsonString);

        return(previewResponse);

        /*int featureCount = previewResponse.Features.Count;
         * int statusListCount = previewResponse.StatusList.Count;
         *
         * Debug.Log("Feature Count: " + featureCount);
         * Debug.Log("StatusList Count: " + statusListCount);
         *
         * text.text = ("Requested HostId: " + previewResponse.RequestHostId.value + "\n");
         *
         * for (int i = 0; i < featureCount; i++)
         * {
         *  text.text += ("Feature: " + previewResponse.Features[i].name + "\t\t\tAvailable: " + previewResponse.Features[i].count + "\t\tTotal: " + previewResponse.Features[i].maxCount + "\t\tExpiration: " + previewResponse.Features[i].expires.ToLongDateString());
         *
         * }*/
    }
コード例 #11
0
        public async Task <IActionResult> Compile(PreviewRequest previewRequest)
        {
            if (previewRequest == null)
            {
                _logger.Error("A null preview request was supplied");

                return(new BadRequestObjectResult("A null preview request was provided"));
            }

            FluentValidation.Results.ValidationResult validationResult = await _previewRequestValidator.ValidateAsync(previewRequest);

            if (!validationResult.IsValid)
            {
                string errors = string.Join(";", validationResult.Errors.Select(m => m.ErrorMessage).ToArraySafe());

                _logger.Warning($"The preview request failed to validate with errors: {errors}");

                return(new BadRequestObjectResult("The preview request failed to validate"));
            }

            Task <IEnumerable <Calculation> > calculationsTask = _calculationsRepository.GetCalculationsBySpecificationId(previewRequest.SpecificationId);

            Task <BuildProject>    buildProjectTask    = _buildProjectsService.GetBuildProjectForSpecificationId(previewRequest.SpecificationId);
            Task <CompilerOptions> compilerOptionsTask = _calculationsRepository.GetCompilerOptions(previewRequest.SpecificationId);

            await TaskHelper.WhenAllAndThrow(calculationsTask, buildProjectTask, compilerOptionsTask);

            BuildProject buildProject = buildProjectTask.Result;

            if (buildProject == null)
            {
                _logger.Warning($"Build project for specification '{previewRequest.SpecificationId}' could not be found");

                return(new PreconditionFailedResult($"Build project for specification '{previewRequest.SpecificationId}' could not be found"));
            }

            List <Calculation> allSpecCalculations = new List <Calculation>(calculationsTask.Result);

            Calculation calculationToPreview = allSpecCalculations.SingleOrDefault(m => m.Id == previewRequest.CalculationId);

            if (calculationToPreview == null)
            {
                calculationToPreview = GenerateTemporaryCalculationForPreview(previewRequest);

                allSpecCalculations.Add(calculationToPreview);
            }
            else
            {
                ApplyChangesToCurrentCalculationForPreview(previewRequest, calculationToPreview);
            }

            Build buildForDatasetAggregationCheck = await CheckDatasetValidAggregations(previewRequest);

            if (buildForDatasetAggregationCheck != null && buildForDatasetAggregationCheck.CompilerMessages.Any(m => m.Severity == Severity.Error))
            {
                PreviewResponse response = new PreviewResponse
                {
                    Calculation    = calculationToPreview.ToResponseModel(),
                    CompilerOutput = buildForDatasetAggregationCheck
                };

                return(new OkObjectResult(response));
            }

            CompilerOptions compilerOptions = compilerOptionsTask.Result ?? new CompilerOptions {
                SpecificationId = buildProject.SpecificationId
            };

            return(await GenerateAndCompile(buildProject, calculationToPreview, allSpecCalculations, compilerOptions, previewRequest));
        }
コード例 #12
0
        public TableHelper GetTableInfosFromApp(string tableName, ScriptCode script, IDoc app)
        {
            try
            {
                var resultTable = new ResultTable()
                {
                    Name = tableName,
                };

                var fields = new List <ResultHeader>();
                var rows   = new List <ResultRow>();
                var size   = new Size();

                if (app == null)
                {
                    throw new Exception("No App session.");
                }

                var tableObject = app.GetObjectAsync(script.ObjectId).Result;
                if (tableObject == null)
                {
                    throw new Exception("No Table object found.");
                }
                logger.Debug($"TableObject objectId: {script.ObjectId} - objectType {tableObject.qGenericType}");

                dynamic   hyperCubeLayout = tableObject.GetLayoutAsync <JObject>().Result;
                HyperCube hyperCube       = hyperCubeLayout.qHyperCube.ToObject <HyperCube>();
                var       columnOrder     = hyperCube.qColumnOrder.ToList();
                size = hyperCube.qSize;
                fields.AddRange(GetHyperCubeFields(hyperCube.qDimensionInfo, hyperCube.qMeasureInfo, script));

                if (columnOrder == null || columnOrder.Count == 0)
                {
                    columnOrder = new List <int>();
                    for (int i = 0; i < fields.Count; i++)
                    {
                        columnOrder.Add(i);
                    }
                }

                var preview = new PreviewResponse()
                {
                    MaxCount = 15,
                };

                if (script != null)
                {
                    var allPages = new List <IEnumerable <NxDataPage> >();
                    if (script.Full)
                    {
                        //DataLoad
                        preview.MaxCount = 0;
                        var pageHeight = Math.Min(size.qcy * size.qcx, 5000) / size.qcx;
                        logger.Debug($"read data - column count: {size.qcx}");
                        var counter = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(size.qcy) / Convert.ToDouble(pageHeight)));
                        allPages = new List <IEnumerable <NxDataPage> >(counter);
                        var options = new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = Environment.ProcessorCount
                        };
                        Parallel.For(0, counter, options, i =>
                        {
                            var initalPage = new NxPage {
                                qTop = 0, qLeft = 0, qWidth = size.qcx, qHeight = pageHeight
                            };
                            initalPage.qTop = i * pageHeight;
                            var pages       = tableObject.GetHyperCubeDataAsync("/qHyperCubeDef", new List <NxPage>()
                            {
                                initalPage
                            }).Result;
                            allPages.Add(pages);
                        });
                    }
                    else
                    {
                        //Preview
                        var initalPage = new NxPage {
                            qTop = 0, qLeft = 0, qWidth = size.qcx, qHeight = preview.MaxCount
                        };
                        var pages = tableObject.GetHyperCubeDataAsync("/qHyperCubeDef", new List <NxPage>()
                        {
                            initalPage
                        }).Result;
                        allPages.Add(pages);
                    }
                    if (allPages == null)
                    {
                        throw new Exception($"no dimension in table {script.ObjectId} exits.");
                    }
                    logger.Debug($"read pages - count {allPages.Count}");

                    var hrow = new PreviewRow();
                    preview.qPreview.Add(hrow);

                    foreach (var page in allPages)
                    {
                        var allMatrix = page?.SelectMany(p => p.qMatrix);
                        foreach (var matrix in allMatrix)
                        {
                            var drow = new PreviewRow();
                            preview.qPreview.Add(drow);

                            foreach (var order in columnOrder)
                            {
                                if (order < fields.Count)
                                {
                                    var row   = new ResultRow();
                                    var field = fields[order];
                                    row.Value  = matrix[order].qText;
                                    row.Num    = matrix[order]?.qNum ?? Double.NaN;
                                    row.Header = field.Name;

                                    if (order == 0)
                                    {
                                        row.IsFirstRow = true;
                                    }

                                    if (order == fields.Count - 1)
                                    {
                                        row.IsLastRow = true;
                                    }

                                    rows.Add(row);

                                    if (!preview.qPreview.Any(s => s.qValues.Contains(field.Name)))
                                    {
                                        hrow.qValues.Add(field.Name);
                                    }
                                    if (preview.qPreview.Count <= preview.MaxCount)
                                    {
                                        drow.qValues.Add(matrix[order].qText);
                                    }
                                }
                            }
                        }
                    }
                }

                resultTable.Headers.AddRange(fields);
                resultTable.Rows.AddRange(rows);
                logger.Debug($"return table {resultTable.Name}");
                return(new TableHelper(resultTable, preview));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "can´t read table infos.");
                return(null);
            }
        }
コード例 #13
0
        public CalculationCreateModelValidator(
            ICalculationsRepository calculationRepository,
            IPreviewService previewService,
            ISpecificationsApiClient specificationsApiClient,
            ICalcsResiliencePolicies calcsResiliencePolicies)
        {
            Guard.ArgumentNotNull(calculationRepository, nameof(calculationRepository));
            Guard.ArgumentNotNull(previewService, nameof(previewService));
            Guard.ArgumentNotNull(specificationsApiClient, nameof(specificationsApiClient));
            Guard.ArgumentNotNull(calcsResiliencePolicies, nameof(calcsResiliencePolicies));
            Guard.ArgumentNotNull(calcsResiliencePolicies?.SpecificationsApiClient, nameof(calcsResiliencePolicies.SpecificationsApiClient));

            _calculationRepository         = calculationRepository;
            _previewService                = previewService;
            _specificationsApiClient       = specificationsApiClient;
            _specificationsApiClientPolicy = calcsResiliencePolicies.SpecificationsApiClient;

            CascadeMode = CascadeMode.StopOnFirstFailure;

            RuleFor(model => model.SpecificationId)
            .NotEmpty()
            .NotNull()
            .WithMessage("Null or empty specification id provided.");

            RuleFor(model => model.ValueType)
            .NotNull()
            .WithMessage("Null value type was provided.");

            RuleFor(model => model.Name)
            .Custom((name, context) =>
            {
                CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel;
                if (string.IsNullOrWhiteSpace(calculationCreateModel.Name))
                {
                    context.AddFailure("Null or empty calculation name provided.");
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(calculationCreateModel.SpecificationId))
                    {
                        Calculation calculation = _calculationRepository.GetCalculationsBySpecificationIdAndCalculationName(calculationCreateModel.SpecificationId, calculationCreateModel.Name).Result;

                        if (calculation != null)
                        {
                            context.AddFailure($"A calculation already exists with the name: '{calculationCreateModel.Name}' for this specification");
                        }
                    }
                }
            });

            RuleFor(model => model.SourceCode)
            .Custom((sc, context) =>
            {
                CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel;
                if (string.IsNullOrWhiteSpace(calculationCreateModel.SourceCode))
                {
                    context.AddFailure("Null or empty source code provided.");
                }
                else
                {
                    if (calculationCreateModel.CalculationType == CalculationType.Additional)
                    {
                        PreviewRequest previewRequest = new PreviewRequest
                        {
                            SpecificationId = calculationCreateModel.SpecificationId,
                            CalculationId   = calculationCreateModel.Id,
                            Name            = calculationCreateModel.Name,
                            SourceCode      = calculationCreateModel.SourceCode
                        };

                        IActionResult result = _previewService.Compile(previewRequest).Result;

                        OkObjectResult okObjectResult = result as OkObjectResult;

                        PreviewResponse response = okObjectResult.Value as PreviewResponse;

                        if (response != null)
                        {
                            if (!response.CompilerOutput.CompilerMessages.IsNullOrEmpty())
                            {
                                context.AddFailure("There are errors in the source code provided");
                            }
                        }
                    }
                }
            });

            RuleFor(model => model.FundingStreamId)
            .Custom((fs, context) =>
            {
                CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel;

                //only validate funding stream id for template calcs
                var isTemplateCalculation = calculationCreateModel.CalculationType == CalculationType.Template;

                if (isTemplateCalculation &&
                    string.IsNullOrWhiteSpace(calculationCreateModel.FundingStreamId))
                {
                    context.AddFailure("Null or empty funding stream id provided.");
                }
                else
                {
                    ApiResponse <SpecModel.SpecificationSummary> specificationApiResponse = _specificationsApiClientPolicy.ExecuteAsync(() => _specificationsApiClient.GetSpecificationSummaryById(calculationCreateModel.SpecificationId)).GetAwaiter().GetResult();

                    if (specificationApiResponse == null || !specificationApiResponse.StatusCode.IsSuccess() || specificationApiResponse.Content == null)
                    {
                        context.AddFailure("Failed to find specification for provided specification id.");
                    }
                    else
                    {
                        SpecModel.SpecificationSummary specificationSummary = specificationApiResponse.Content;

                        //I don't want to have to fetch the spec summary again outside of this method to get the name and funding stream so we set them on input model here
                        calculationCreateModel.SpecificationName = specificationSummary.Name;

                        //only validate funding stream ids for template calcs
                        if (!isTemplateCalculation)
                        {
                            return;
                        }

                        Reference fundingStream = specificationSummary.FundingStreams.FirstOrDefault(m => m.Id == calculationCreateModel.FundingStreamId);

                        if (fundingStream == null)
                        {
                            context.AddFailure("The funding stream id provided is not associated with the provided specification.");
                        }
                        else
                        {
                            calculationCreateModel.FundingStreamName = fundingStream.Name;
                        }
                    }
                }
            });
        }
コード例 #14
0
        public async Task <IActionResult> Compile(HttpRequest request)
        {
            string json = await request.GetRawBodyStringAsync();

            var previewRequest = JsonConvert.DeserializeObject <PreviewRequest>(json);

            if (previewRequest == null)
            {
                _logger.Error("A null preview request was supplied");

                return(new BadRequestObjectResult("A null preview request was provided"));
            }

            var validationResult = await _previewRequestValidator.ValidateAsync(previewRequest);

            if (!validationResult.IsValid)
            {
                string errors = string.Join(";", validationResult.Errors.Select(m => m.ErrorMessage).ToArraySafe());

                _logger.Warning($"The preview request failed to validate with errors: {errors}");

                return(new BadRequestObjectResult("The preview request failed to validate"));
            }

            Task <IEnumerable <Calculation> > calculationsTask = _calculationsRepository.GetCalculationsBySpecificationId(previewRequest.SpecificationId);

            Task <BuildProject>    buildProjectTask    = _buildProjectsService.GetBuildProjectForSpecificationId(previewRequest.SpecificationId);
            Task <CompilerOptions> compilerOptionsTask = _calculationsRepository.GetCompilerOptions(previewRequest.SpecificationId);

            await TaskHelper.WhenAllAndThrow(calculationsTask, buildProjectTask, compilerOptionsTask);

            BuildProject buildProject = buildProjectTask.Result;

            if (buildProject == null)
            {
                _logger.Warning($"Build project for specification '{previewRequest.SpecificationId}' could not be found");

                return(new PreconditionFailedResult($"Build project for specification '{previewRequest.SpecificationId}' could not be found"));
            }

            List <Calculation> calculations = new List <Calculation>(calculationsTask.Result);

            Calculation calculation = calculations.FirstOrDefault(m => m.Id == previewRequest.CalculationId);

            if (calculation == null)
            {
                string message = $"Calculation ('{previewRequest.CalculationId}') could not be found for specification Id '{previewRequest.SpecificationId}'";
                _logger.Warning(message);
                return(new PreconditionFailedResult(message));
            }

            calculation.Current.SourceCode = previewRequest.SourceCode;

            Build build = await CheckDatasetValidAggregations(previewRequest);

            if (build != null && build.CompilerMessages.Any(m => m.Severity == Severity.Error))
            {
                PreviewResponse response = new PreviewResponse
                {
                    Calculation    = calculation,
                    CompilerOutput = build
                };

                return(new OkObjectResult(response));
            }

            CompilerOptions compilerOptions = compilerOptionsTask.Result ?? new CompilerOptions {
                SpecificationId = buildProject.SpecificationId
            };

            return(await GenerateAndCompile(buildProject, calculation, calculations, compilerOptions, previewRequest));
        }