Esempio n. 1
0
        private static ProcessingResult ValidateFinPeriods(GLBudgetEntry graph, IEnumerable <GLBudgetLineDetail> records)
        {
            ProcessingResult generalResult = new ProcessingResult();

            var recordsByPeriod = records.GroupBy(record => record.FinPeriodID);

            foreach (var recordsByPeriodGroup in recordsByPeriod)
            {
                string finPeriodID = recordsByPeriodGroup.Key;

                int?[] orgnizationIDs = recordsByPeriodGroup.GroupBy(t => PXAccess.GetParentOrganizationID(t.BranchID))
                                        .Select(g => g.Key)
                                        .ToArray();

                ICollection <OrganizationFinPeriod> finPeriods =
                    PXSelect <OrganizationFinPeriod,
                              Where <OrganizationFinPeriod.organizationID, In <Required <OrganizationFinPeriod.organizationID> >,
                                     And <OrganizationFinPeriod.finPeriodID, Equal <Required <OrganizationFinPeriod.finPeriodID> > > > >
                    .Select(graph, orgnizationIDs, finPeriodID)
                    .RowCast <OrganizationFinPeriod>()
                    .ToArray();

                if (finPeriods.Count != orgnizationIDs.Length)
                {
                    string[] organizationCDs = orgnizationIDs.Except(finPeriods.Select(period => period.OrganizationID))
                                               .Select(PXAccess.GetOrganizationCD)
                                               .ToArray();

                    generalResult.AddErrorMessage(Messages.FinPeriodDoesNotExistForCompanies,
                                                  FinPeriodIDFormattingAttribute.FormatForError(finPeriodID),
                                                  organizationCDs.JoinIntoStringForMessageNoQuotes(20));
                }

                foreach (OrganizationFinPeriod finPeriod in finPeriods)
                {
                    ProcessingResult result = new ProcessingResult();
                    if (finPeriod.Status == FinPeriod.status.Locked)
                    {
                        result.AddErrorMessage(Messages.FinPeriodIsLockedInCompany,
                                               FinPeriodIDFormattingAttribute.FormatForError(finPeriod.FinPeriodID),
                                               PXAccess.GetOrganizationCD(finPeriod.OrganizationID));
                    }

                    generalResult.Aggregate(result);

                    if (generalResult.Messages.Count > 20)
                    {
                        return(generalResult);
                    }
                }
            }
            return(generalResult);
        }
        public void GetEmptyResultFromCache()
        {
            ResultCache sut = new ResultCache();

            ProcessingResult cachedResultUser1 = sut.Get("testUser1");

            sut.Set("testUser3", new ProcessingResult());
            ProcessingResult cachedResultUser2 = sut.Get("testUser2");

            Assert.Null(cachedResultUser1);
            Assert.Null(cachedResultUser2);
        }
Esempio n. 3
0
        private static ProcessingResult GetMemberInstances(MemberInfo member, ProcessingResult instanceResult)
        {
            if (instanceResult.IsSingleItem)
            {
                return(new ProcessingResult(true, GetValue(instanceResult.Result, member), true));
            }

            var instances = from object item in instanceResult.GetItems()
                            select GetValue(item, member);

            return(new ProcessingResult(true, instances.ToList()));
        }
Esempio n. 4
0
 private static void CheckForErrors(ProcessingResult result)
 {
     if (!result.Success)
     {
         // TODO: Remove this method after simplifying ProcessingEngine error handling to always throw exceptions on error.
         if (result.UserMessage != null)
         {
             throw new UserException(result.UserMessage, result.SystemMessage); // JsonErrorHandler will return HttpStatusCode.BadRequest.
         }
         throw new FrameworkException(result.SystemMessage);                    // JsonErrorHandler will return HttpStatusCode.InternalServerError.
     }
 }
Esempio n. 5
0
        public void SubjectMustHasValidContentLength()
        {
            // Arrange
            var note = new HmmNote
            {
                Author      = _user,
                Description = "testing note",
                Subject     = "",
                Content     = "<root><time>2017-08-01</time></root>",
                Catalog     = new NoteCatalog()
            };

            // Act
            var processResult = new ProcessingResult();
            var result        = _validator.IsValidEntity(note, processResult);

            // Assert
            Assert.False(result);

            // Arrange
            note = new HmmNote
            {
                Author      = _user,
                Description = "testing note",
                Subject     = GetRandomString(1001),
                Content     = "<root><time>2017-08-01</time></root>",
                Catalog     = new NoteCatalog()
            };

            // Act
            processResult = new ProcessingResult();
            result        = _validator.IsValidEntity(note, processResult);

            // Assert
            Assert.False(result);

            // Arrange
            note = new HmmNote
            {
                Author      = _user,
                Description = "testing note",
                Subject     = GetRandomString(15),
                Content     = "<root><time>2017-08-01</time></root>",
                Catalog     = new NoteCatalog()
            };

            // Act
            processResult = new ProcessingResult();
            result        = _validator.IsValidEntity(note, processResult);

            // Assert
            Assert.True(result);
        }
        public ProcessingResult <ICollection <ICroppedArea> > CropUserInput(Bitmap bitmapToCropIntoParts, Guid documentId,
                                                                            ITemplatePageDefinition definitionForCropping)
        {
            if (definitionForCropping == null)
            {
                return(ProcessingResult <ICollection <ICroppedArea> > .Failure(new PageDefinitionNotProvided()));
            }

            if (documentId == Guid.Empty)
            {
                return(ProcessingResult <ICollection <ICroppedArea> > .Failure(new MissingDocumentId()));
            }

            //Can this be more granular without downloading bitmap all over again?
            //Maybe parent holding bitmap and just passing it over to all children?
            using (bitmapToCropIntoParts)
            {
                var results = new List <ICroppedArea>();
                foreach (var templateArea in definitionForCropping.DefinedAreas)
                {
                    try
                    {
                        var croppedAreaParts = new List <OrderedBitmap>();

                        if (templateArea.InterestPoints == null || templateArea.InterestPoints.Count == 0)
                        {
                            croppedAreaParts.Add(
                                new OrderedBitmap(0, new Crop(templateArea.AreaDimension).Apply(bitmapToCropIntoParts)));
                        }
                        else
                        {
                            foreach (var areaPart in templateArea.InterestPoints)
                            {
                                croppedAreaParts.Add(
                                    new OrderedBitmap(areaPart.OrderInArea, new Crop(areaPart.Dimension).Apply(bitmapToCropIntoParts)));
                            }
                        }

                        results.Add(new CroppedArea(templateArea, croppedAreaParts, documentId));
                    }
                    catch (UnsupportedImageFormatException)
                    {
                        return(ProcessingResult <ICollection <ICroppedArea> > .Failure(new UnsupportedImageFormat()));
                    }
                    catch (Exception ex)
                    {
                        ProcessingResult <ICollection <ICroppedArea> > .Failure(new UncaughtException(ex));
                    }
                }
                return(ProcessingResult <ICollection <ICroppedArea> > .Success(results));
            }
        }
Esempio n. 7
0
        public ProcessingResult ProcessQuery(MethodCallExpression query, ProcessingResult parentResult, DataContext context)
        {
            var itemType = parentResult.IsDeferred()
                ? typeof(NodeReference)
                : QueryProcessingHelper.GetSourceParameterType(query);

            var result = RuntimeMethodInvoker.InvokeFuncCached <IEnumerable <RuntimeType1>, IEnumerable <RuntimeType1> >(
                Reverse, new RuntimeTypeBinding {
                new RuntimeType1(itemType)
            }, parentResult.Result);

            return(new ProcessingResult(true, result));
        }
        private static ProcessingResult LoadData(ProcessingResult result, Type dataType)
        {
            if (!result.IsSuccess)
            {
                return(ProcessingResult.Unsuccessful);
            }

            var loadedResult = result.IsSingleItem
                ? result.GetLoadedItem(dataType)
                : result.GetLoadedItems(dataType);

            return(new ProcessingResult(true, loadedResult, result.IsSingleItem));
        }
        private void ResizeBeetleSuccess(MediaDimension resizeBy, int size, ImageSaveFormat format)
        {
            ImageResizeProcessor processor = GetProcessor(resizeBy, size, format, false);

            processor.Init(RunInfo);
            ProcessingResult result = processor.Process(GetTestFile("beetle.jpg"),
                                                        MatchResultType.Yes, new string[0], new FileInfo[0], ProcessInput.OriginalFile,
                                                        CancellationToken.None);

            processor.Cleanup();
            Assert.AreEqual(ProcessingResultType.Success, result.Type);
            Assert.AreEqual(1, result.OutputFiles.Length);
        }
Esempio n. 10
0
        protected virtual ProcessingResult HandleErrorThatPeriodIsClosed(IFinPeriod finPeriod)
        {
            ProcessingResult result = new ProcessingResult();

            if (!CanPostToClosedPeriod())
            {
                result.AddErrorMessage(Messages.FinPeriodIsClosedInCompany,
                                       FinPeriodIDFormattingAttribute.FormatForError(finPeriod.FinPeriodID),
                                       PXAccess.GetOrganizationCD(finPeriod.OrganizationID));
            }

            return(result);
        }
        public void Publish(ProcessingResult result)
        {
            try
            {
                var filePath = ResolveFilePath(result.Payload);

                SaveFile(filePath, result.Print());
            }
            catch (Exception e)
            {
                _logger.LogError("Error writing result {0}:{1}", e.Message, e.StackTrace);
            }
        }
Esempio n. 12
0
 protected virtual ProcessingResult Processing(bool processActions)
 {
     using (var entry = ConcurrencyLimiter.TryEnter())
     {
         ProcessingResult result = entry.HasEntry ? ProcessingResult.Processed : ProcessingResult.ExclusiveSkip;
         NullSafeSequencer.PointArg(SeqPointTypeUC.Notify, TimerProcessorSequencer.Processing, result);
         if (result == ProcessingResult.Processed)
         {
             ExclusiveProcessing(processActions);
         }
         return(result);
     }
 }
        /// <summary>
        /// Generate project data for the given parameters and cache results locally.
        /// </summary>
        /// <returns>Resulting parameters hash</returns>
        private async Task <(string hash, FdaStatsDTO stats)> UpdateAsync(ProjectStorage storage, InventorParameters parameters, string hash, bool bForceUpdate = false)
        {
            _logger.LogInformation("Update the project");
            var bucket = await _userResolver.GetBucketAsync();

            var isUpdateExists = bForceUpdate ? false : await IsGenerated(bucket, storage.GetOssNames(hash));

            FdaStatsDTO stats;

            if (isUpdateExists)
            {
                _logger.LogInformation("Detected existing outputs at OSS");
                var statsNative = await bucket.DeserializeAsync <List <Statistics> >(storage.GetOssNames(hash).StatsUpdate);

                stats = FdaStatsDTO.CreditsOnly(statsNative);
            }
            else
            {
                Project project = storage.Project;

                var inputDocUrl = await bucket.CreateSignedUrlAsync(project.OSSSourceModel);

                UpdateData updateData = await _arranger.ForUpdateAsync(inputDocUrl, storage.Metadata.TLA, parameters);

                ProcessingResult result = await _fdaClient.UpdateAsync(updateData);

                if (!result.Success)
                {
                    _logger.LogError($"Failed to update '{project.Name}' project.");
                    throw new FdaProcessingException($"Failed to update '{project.Name}' project.", result.ReportUrl);
                }

                _logger.LogInformation("Moving files around");

                // rearrange generated data according to the parameters hash
                // NOTE: hash might be changed if Inventor adjust them!
                hash = await _arranger.MoveViewablesAsync(project, storage.IsAssembly);

                // process statistics
                await bucket.UploadAsJsonAsync(storage.GetOssNames(hash).StatsUpdate, result.Stats);

                stats = FdaStatsDTO.All(result.Stats);
            }

            _logger.LogInformation($"Cache the project locally ({hash})");

            // and now cache the generated stuff locally
            await storage.EnsureViewablesAsync(bucket, hash);

            return(hash, stats);
        }
Esempio n. 14
0
        public virtual ProcessingResult CanPostToPeriod(IFinPeriod finPeriod, Type fieldModuleClosed = null)
        {
            ProcessingResult result = new ProcessingResult();

            if (finPeriod.Status == FinPeriod.status.Locked)
            {
                result.AddErrorMessage(Messages.FinPeriodIsLockedInCompany,
                                       FinPeriodIDFormattingAttribute.FormatForError(finPeriod.FinPeriodID),
                                       PXAccess.GetOrganizationCD(finPeriod.OrganizationID));

                return(result);
            }

            if (AllowPostToUnlockedPeriodAnyway)
            {
                return(result);
            }

            if (finPeriod.Status == FinPeriod.status.Inactive)
            {
                result.AddErrorMessage(Messages.FinPeriodIsInactiveInCompany,
                                       FinPeriodIDFormattingAttribute.FormatForError(finPeriod.FinPeriodID),
                                       PXAccess.GetOrganizationCD(finPeriod.OrganizationID));

                return(result);
            }

            if (finPeriod.Status == FinPeriod.status.Closed)
            {
                result = HandleErrorThatPeriodIsClosed(finPeriod);

                if (result.HasWarningOrError)
                {
                    return(result);
                }
            }

            if (fieldModuleClosed != null)
            {
                PXCache cache = Graph.Caches[BqlCommand.GetItemType(fieldModuleClosed)];

                bool?isClosedInModule = (bool)cache.GetValue(finPeriod, fieldModuleClosed.Name);

                if (isClosedInModule == true)
                {
                    result = HandleErrorThatPeriodIsClosed(finPeriod);
                }
            }

            return(result);
        }
Esempio n. 15
0
        public void SingleFailure()
        {
            Mock <IProcessor> mockProcessor1 = new Mock <IProcessor>();
            Mock <IProcessor> mockProcessor2 = new Mock <IProcessor>();
            FileInfo          file1          = GetTestFile("BasicTextFile.txt");
            FileInfo          file2          = GetTestFile("Lipsum.txt");
            FileInfo          file3          = GetTestFile("TextFileWithNewlines.txt");

            FileInfo[] generatedFiles = new FileInfo[] { file2, file2, file2 };
            FileInfo[] outputFiles    = new FileInfo[] { file3, file3, file3 };
            string[]   values         = new string[] { "foo", "bar", "baz" };

            mockProcessor1.Setup(p => p.Init(It.IsAny <IRunInfo>()));
            mockProcessor1.Setup(p => p.InputFileSource).Returns(InputFileSource.ParentInput);
            mockProcessor1.Setup(p => p.Process(file1, It.IsAny <MatchResultType>(),
                                                values, generatedFiles, ProcessInput.GeneratedFiles, It.IsAny <CancellationToken>()))
            .Returns(new ProcessingResult(ProcessingResultType.Success,
                                          "Processor 1 Success", outputFiles));
            mockProcessor1.Setup(p => p.ProcessAggregated(It.IsAny <CancellationToken>()));
            mockProcessor1.Setup(p => p.Cleanup());

            mockProcessor2.Setup(p => p.Init(It.IsAny <IRunInfo>()));
            mockProcessor2.Setup(p => p.InputFileSource).Returns(InputFileSource.ParentInput);
            mockProcessor2.Setup(p => p.Process(file1, It.IsAny <MatchResultType>(),
                                                values, generatedFiles, ProcessInput.GeneratedFiles, It.IsAny <CancellationToken>()))
            .Returns(new ProcessingResult(ProcessingResultType.Failure,
                                          "Processor 2 Failure", new FileInfo[] { }));
            mockProcessor2.Setup(p => p.ProcessAggregated(It.IsAny <CancellationToken>()));
            mockProcessor2.Setup(p => p.Cleanup());

            MultiProcessor multiProcessor = new MultiProcessor();

            multiProcessor.Processors.Add(mockProcessor1.Object);
            multiProcessor.Processors.Add(mockProcessor2.Object);

            multiProcessor.Init(RunInfo);
            ProcessingResult result = multiProcessor.Process(file1, MatchResultType.Yes,
                                                             values, generatedFiles, ProcessInput.GeneratedFiles, CancellationToken.None);

            multiProcessor.ProcessAggregated(CancellationToken.None);
            multiProcessor.Cleanup();

            mockProcessor1.VerifyAll();
            mockProcessor2.VerifyAll();

            Assert.IsNotNull(result);
            Assert.AreEqual(ProcessingResultType.Failure, result.Type);
            Assert.AreEqual("Processor 1 Success | Processor 2 Failure", result.Message);
            Assert.AreEqual(3, result.OutputFiles.Length);
            Assert.IsTrue(result.OutputFiles.All(file => file == file3));
        }
Esempio n. 16
0
        /// <summary>
        /// Go through all modules and check if any of them can handle the current request.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private ProcessingResult ProcessModules(RequestContext context)
        {
            foreach (IModule module in _modules)
            {
                ProcessingResult result = module.Process(context);
                if (result != ProcessingResult.Continue)
                {
                    _logger.Debug(module.GetType().Name + ": " + result);
                    return(result);
                }
            }

            return(ProcessingResult.Continue);
        }
Esempio n. 17
0
        public static ProcessingResult ProcessRules(ShippingContext shippingContext, List <Rule> rules)
        {
            ProcessingResult ruleProcessingResult = new ProcessingResult();

            rules.ForEach(rule =>
            {
                ruleProcessingResult = rule.Func(shippingContext);
                shippingContext.processingResult.discount = ruleProcessingResult.discount;
            });

            shippingContext.totalDiscount += ruleProcessingResult.discount;

            return(ruleProcessingResult);
        }
        public async Task <TResult> ExecuteTransaction <TResult>(string requestId, TPartition partitionKey, Func <IHumanInterfaceConnectorMessageSession, Task <TResult> > transaction)
        {
            var transactionRecordContainer = applicationStateStore.Create(partitionKey);

            var outcome = await processor.Process(requestId, transactionRecordContainer, null, async (ctx, transactionContext) =>
            {
                var session = new HumanInterfaceConnectorMessageSession(requestId, transactionContext, rootMessageSession, messageStore);
                var result  = await transaction(session).ConfigureAwait(false);
                await transactionInProgressStore.BeginTransaction(requestId, transactionRecordContainer.UniqueIdentifier).ConfigureAwait(false);
                return(ProcessingResult <TResult> .Successful(result));
            });

            return(outcome.Value); //Duplicate check is ignored in the human interface
        }
        public ProcessingResult ProcessQuery(MethodCallExpression query, ProcessingResult parentResult, DataContext context)
        {
            var elementType = QueryProcessingHelper.GetSourceParameterType(query);

            var items    = parentResult.GetLoadedItems(elementType);
            var comparer = query.Arguments.Count > 1 ? ((ConstantExpression)query.Arguments[1]).Value : null;

            var result = RuntimeMethodInvoker.InvokeFuncCached <IEnumerable <RuntimeType1>, IEqualityComparer <RuntimeType1>, List <RuntimeType1> >(
                Distinct, new RuntimeTypeBinding {
                new RuntimeType1(elementType)
            }, items, comparer);

            return(new ProcessingResult(true, result));
        }
Esempio n. 20
0
        public void AuthorAccountNameMustHasValidContentLength()
        {
            // Arrange
            var author = new Author
            {
                AccountName = "",
                IsActivated = true,
            };

            // Act

            var processResult = new ProcessingResult();
            var result        = _validator.IsValidEntity(author, processResult);

            // Assert
            Assert.False(result);
            Assert.NotEmpty(processResult.MessageList[0].Message);

            // Arrange
            author = new Author
            {
                AccountName = GetRandomString(154),
                IsActivated = true,
            };

            // Act

            processResult = new ProcessingResult();
            result        = _validator.IsValidEntity(author, processResult);

            // Assert
            Assert.True(result);
            Assert.Empty(processResult.MessageList);

            // Arrange
            author = new Author
            {
                AccountName = GetRandomString(500),
                IsActivated = true,
            };

            // Act

            processResult = new ProcessingResult();
            result        = _validator.IsValidEntity(author, processResult);

            // Assert
            Assert.False(result);
            Assert.NotEmpty(processResult.MessageList[0].Message);
        }
        public static AliceResponse CreateAliceResponse(ProcessingResult result, Session session, Func <int, int> variantSelector)
        {
            var responseArgs = GetResponseArgs(result);
            var response     = CreateResponse(responseArgs, result.CultureInfo, variantSelector);

            var aliceResponse = new AliceResponse()
            {
                Response = response,
                Session  = session,
                Version  = "1.0"
            };

            return(aliceResponse);
        }
Esempio n. 22
0
        public ProcessingResult ValidateTaxYearStructure(TaxPeriod taxPeriod)
        {
            var finPeriodWithSameStartDate = _gafRepository.FindFinPeriodWithStartDate(taxPeriod.StartDate);
            var finPeriodWithSameEndDate   = _gafRepository.FindFinPeriodWithEndDate(taxPeriod.EndDate);

            if (finPeriodWithSameStartDate == null || finPeriodWithSameEndDate == null)
            {
                var result = new ProcessingResult();
                result.AddErrorMessage(Messages.TheGAFFileCannotBePrepared);
                return(result);
            }

            return(ProcessingResult.Success);
        }
Esempio n. 23
0
        private static void ProcessFiles(string folderPath)
        {
            IEnumerable <string> files = Directory.EnumerateFiles(folderPath);

            Console.WriteLine("Processing {0} files...", files.Count());
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            ProcessingResult result = FileProcessor.ProcessFiles(files);

            stopwatch.Stop();

            FormattedOutput(stopwatch, result);
        }
Esempio n. 24
0
 private void ThrowExceptionOnError(ProcessingResult processingResult)
 {
     if (!processingResult.Success)
     {
         if (processingResult.UserMessage != null)
         {
             throw new UserException(processingResult.UserMessage, processingResult.SystemMessage);
         }
         else
         {
             throw new FrameworkException(processingResult.SystemMessage);
         }
     }
 }
        public void RunsCommandLine()
        {
            CommandLineProcessor p = new CommandLineProcessor();

            p.SetParameter("CommandLine", $"copy \"{{FullName}}\" \"{CurrentTestResultsDirectoryPath}\"");
            p.SetParameter("WaitForTaskToFinish", true);
            p.Init(RunInfo);
            FileInfo         file   = GetTestFile("BasicTextFile.txt");
            ProcessingResult result = p.Process(file, MatchResultType.Yes, new string[0], new FileInfo[0],
                                                ProcessInput.OriginalFile, CancellationToken.None);

            Assert.AreEqual(ProcessingResultType.Success, result.Type);
            p.Cleanup();
        }
        public void GetResultFromCacheAfterInitialAdd()
        {
            ResultCache      sut         = new ResultCache();
            ProcessingResult resultUser1 = new ProcessingResult();
            ProcessingResult resultUser2 = new ProcessingResult();

            sut.Set("testUser1", resultUser1);
            sut.Set("testUser2", resultUser2);
            ProcessingResult cachedResultUser1 = sut.Get("testUser1");
            ProcessingResult cachedResultUser2 = sut.Get("testUser2");

            Assert.Equal(resultUser1, cachedResultUser1);
            Assert.Equal(resultUser2, cachedResultUser2);
        }
Esempio n. 27
0
        internal void AddResult(ProcessingResult result)
        {
            if (!result.IsSuccess)
            {
                IsSuccess = false;
            }

            if (!result.IsSingleItem)
            {
                IsSingle = false;
            }

            Result = result;
        }
Esempio n. 28
0
        public void GetProcessingResultFromCopyAndDeleteTempFile_Successs()
        {
            Mock <ProcessorBase> mockProcessor = new Mock <ProcessorBase>();
            ProcessorBase        processor     = mockProcessor.Object;
            string tmpFile = Path.GetTempFileName();

            File.WriteAllText(tmpFile, "This is the final text.");
            string           outputPath = GetCurrentTestResultsFilePath("out.txt");
            ProcessingResult result     = processor.GetProcessingResultFromCopyAndDeleteTempFile(
                null, outputPath, tmpFile, true, true);

            Assert.IsFalse(File.Exists(tmpFile));
            Assert.AreEqual(ProcessingResultType.Success, result.Type);
        }
Esempio n. 29
0
        public ProcessingResult ProcessFiles(IEnumerable <string> files)
        {
            Regex pattern = new Regex(PatternString, RegexOptions.Compiled | RegexOptions.Multiline);

            List <Task <ProcessingResult> > tasks = new List <Task <ProcessingResult> >();

            foreach (string fileName in files)
            {
                Task <ProcessingResult> task = Task.Factory.StartNew <ProcessingResult>((arg) =>
                {
                    string localFileName         = (string)arg;
                    ProcessingResult localResult = new ProcessingResult();

                    byte[] bytes = File.ReadAllBytes(localFileName);
                    string body  = Encoding.UTF8.GetString(bytes);

                    Match match = pattern.Match(body);
                    while (match.Success)
                    {
                        localResult.Total++;

                        if (match.Groups[2].Value == Tele2Brand)
                        {
                            Guid id = Guid.Parse(match.Groups[1].Value);
                            localResult.Tele2OrderIds.Add(id);
                        }

                        match = match.NextMatch();
                    }

                    return(localResult);
                },
                                                                                        fileName);
                tasks.Add(task);
            }

            Task.WaitAll(tasks.ToArray());

            // Aggregate the results
            ProcessingResult aggregatedResult = new ProcessingResult();

            foreach (var task in tasks)
            {
                aggregatedResult.Total += task.Result.Total;
                aggregatedResult.Tele2OrderIds.AddRange(task.Result.Tele2OrderIds);
            }

            return(aggregatedResult);
        }
Esempio n. 30
0
        /// <summary>
        /// Generate RFA (or take it from cache).
        /// </summary>
        public async Task GenerateRfaAsync(string projectName, string hash)
        {
            _logger.LogInformation($"Generating RFA for hash {hash}");

            ProjectStorage storage = await _userResolver.GetProjectStorageAsync(projectName);

            Project project = storage.Project;

            //// *********************************************
            //// temporary fail *********************************************
            //_logger.LogError($"Failed to generate SAT file");
            //throw new FdaProcessingException($"Failed to generate SAT file", "https://localhost:5000/#");
            //// *********************************************


            var ossNameProvider = project.OssNameProvider(hash);

            var bucket = await _userResolver.GetBucketAsync();

            // check if RFA file is already generated
            try
            {
                // TODO: this might be ineffective as some "get details" API call
                await bucket.CreateSignedUrlAsync(ossNameProvider.Rfa);

                return;
            }
            catch (ApiException e) when(e.ErrorCode == StatusCodes.Status404NotFound)
            {
                // the file does not exist, so just swallow
            }

            // OK, nothing in cache - generate it now
            var inputDocUrl = await bucket.CreateSignedUrlAsync(ossNameProvider.GetCurrentModel(storage.IsAssembly));

            ProcessingArgs satData = await _arranger.ForSatAsync(inputDocUrl, storage.Metadata.TLA);

            ProcessingArgs rfaData = await _arranger.ForRfaAsync(satData.SatUrl);

            ProcessingResult result = await _fdaClient.GenerateRfa(satData, rfaData);

            if (!result.Success)
            {
                _logger.LogError($"{result.ErrorMessage} for project {project.Name} and hash {hash}");
                throw new FdaProcessingException($"{result.ErrorMessage} for project {project.Name} and hash {hash}", result.ReportUrl);
            }

            await _arranger.MoveRfaAsync(project, hash);
        }
 public void ProcessingCompleted(ProcessingResult result)
 {
     this.logger.Log(
         LogLevel.Information,
         "Processing completed: {0}",
         result.StatusMessage);
 }
Esempio n. 32
0
        private void ProcessTree(Item item)
        {
            Assert.ArgumentNotNull(item, "item");

            var pr = new ProcessingResult() {Path = item.Paths.ContentPath, Updated = false};
            if (!_processingResults.ContainsKey(item.ID))
            {
                _processingResults.Add(item.ID, pr);
            }

            ProcessItem(item);

            if (RenderingModifierSettings.ProcessDescendants)
            {
                ProcessChildren(item);
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Process result (check if it should be sent back or not)
        /// </summary>
        /// <param name="result"></param>
        /// <param name="e"></param>
        /// <returns><c>true</c> if request was processed properly.; otherwise <c>false</c>.</returns>
        protected virtual bool ProcessResult(ProcessingResult result, RequestEventArgs e)
        {
            if (result == ProcessingResult.Abort)
            {
                e.IsHandled = true;
                return true;
            }

            if (result == ProcessingResult.SendResponse)
            {
                SendResponse(e.Context, e.Request, e.Response);
                e.IsHandled = true;
                return true;
            }

            return false;
        }
Esempio n. 34
0
 public void AddResult(ProcessingResult result)
 {
     _results.Add(result);
 }