Esempio n. 1
0
        public void Processor_CoinFactoryTest()
        {
            AbstractChangeProcessor abstractProcessor = ProcessorFactory.Create(74);

            Assert.IsNotNull(abstractProcessor);
            Assert.IsTrue(abstractProcessor is CoinProcessor);
        }
Esempio n. 2
0
        private void EditConfig()
        {
            if (this.cmBoxProcessorType.SelectedItem == null)
            {
                return;
            }
            string ProcessorType = this.cmBoxProcessorType.SelectedItem.ToString();

            IProcessorConfig cfg = ProcessorFactory.CreateProcessorConfig(ProcessorType, _param.Log);

            if (cfg == null)
            {
                return;
            }

            if (!cfg.Initialize(_param))
            {
                return;
            }

            string cfgXml = _Processor.Setting;

            if (cfg.EditConfig(this, ref cfgXml))
            {
                _Processor.Setting = cfgXml;
            }
        }
Esempio n. 3
0
        public void Processor_BankNoteFactoryTest()
        {
            AbstractChangeProcessor abstractProcessor = ProcessorFactory.Create(200);

            Assert.IsNotNull(abstractProcessor);
            Assert.IsTrue(abstractProcessor is BankNoteProcessor);
        }
Esempio n. 4
0
        private void CreatConfig()
        {
            if (this.cmBoxProcessorType.SelectedItem == null)
            {
                return;
            }
            string ProcessorType = this.cmBoxProcessorType.SelectedItem.ToString();

            IProcessorConfig cfg = ProcessorFactory.CreateProcessorConfig(ProcessorType, _param.Log);

            if (cfg == null)
            {
                return;
            }

            if (!cfg.Initialize(_param))
            {
                return;
            }

            string cfgXml = "";

            if (cfg.CreateConfig(this, out cfgXml))
            {
                _Processor.Setting = cfgXml.ToString();
                rtBoxSetting.Clear();
                rtBoxSetting.Text = _Processor.Setting;
            }
        }
Esempio n. 5
0
        private void Main_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SessionInfo.CurrentExperimentsInfo != null)
            {
                if (SessionInfo.CurrentExperimentsInfo.State == (short)ExperimentStatus.Processing)
                {
                    MessageBox.Show("当前实验正在运行,请先停止!", "系统提示!");
                    e.Cancel = true;
                    return;
                }
                if (SessionInfo.CurrentExperimentsInfo.State == (short)ExperimentStatus.Fail || SessionInfo.CurrentExperimentsInfo.State == (short)ExperimentStatus.Create ||
                    SessionInfo.CurrentExperimentsInfo.State == (short)ExperimentStatus.Suspend)
                {
                    if (MessageBox.Show("当前实验未完成,是否退出?", "系统提示!", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                    {
                        e.Cancel = true;
                        return;
                    }
                    WanTai.Controller.RotationInfoController rotationInfoController = new WanTai.Controller.RotationInfoController();
                    rotationInfoController.UpdataExperimentStatus(SessionInfo.CurrentExperimentsInfo.ExperimentID, true, ExperimentStatus.Fail);
                }
            }

            if (!ProcessorFactory.HasClosed)
            {
                IProcessor processor = ProcessorFactory.GetProcessor();
                processor.Close();
            }
        }
Esempio n. 6
0
        public void WhenCompress_DecompressFile_Checksums_TheSame()
        {
            // Arrange
            const int OneKb = 1024;

            var compressorParms = new CreateProcessParms()
            {
                Operation       = OperationType.Compress,
                SourceFile      = toCompressFilename,
                DestinationFile = compressedFilename
            };

            var factory    = new ProcessorFactory(compressorParms, OneKb);
            var compressor = factory.Create();

            var decompressorParms = new CreateProcessParms()
            {
                Operation       = OperationType.Decompress,
                SourceFile      = compressedFilename,
                DestinationFile = decompressedFilename
            };

            factory = new ProcessorFactory(decompressorParms, 0);
            var decompressor = factory.Create();

            // Act
            compressor.StartProcess();
            decompressor.StartProcess();

            // Assert
            var expectedChecksum = CalcMD5Checksum(toCompressFilename);
            var actualChecksum   = CalcMD5Checksum(decompressedFilename);

            Assert.True(Enumerable.SequenceEqual(expectedChecksum, actualChecksum), "Uncompressed file not equal to original file");
        }
Esempio n. 7
0
        void run(string[] args)
        {
            string cmd, pathIn;

            if (args.Length == 1) //передан путь ко входному Xml
            {
                cmd    = ProcessorFactory.UseMapper;
                pathIn = Path.GetFullPath(saveGetParam(args[0]));
            }
            else if (args.Length == 2) //переданы метод обратоки Xml и путь ко входному Xml
            {
                cmd    = args[0];
                pathIn = Path.GetFullPath(saveGetParam(args[1]));
            }
            else
            {
                throw new Exception(string.Format("Unrecognized command line. Examples:\r\n" +
                                                  "\tCommersantTest path - process file by Mapper processor;\r\n" +
                                                  "\tCommersantTest {0} path - process file by Mapper processor;\r\n" +
                                                  "\tCommersantTest {1} path - process file by Xslt processor\r\n", ProcessorFactory.UseMapper, ProcessorFactory.UseXslt)
                                    );
            }


            //обрабатываем Xml выбранным методом
            var processor = new ProcessorFactory().CreateProcessor(cmd);

            processor.ProcessData(pathIn, Path.Combine(Path.GetDirectoryName(pathIn), "out.xml"));
            //отображаем отчёт
            writeReport(processor, Path.GetFileName(pathIn));
        }
Esempio n. 8
0
        private List <ChangeData> CalculateEntities(long changeAmount)
        {
            long changeRest = changeAmount;

            List <ChangeData> changeDataCollection = new List <ChangeData>();

            while (changeRest > 0)
            {
                ChangeData currentData = new ChangeData();

                AbstractProcessor      proc         = ProcessorFactory.CreateProcessor(changeRest);
                Dictionary <int, long> monetaryObjs = proc.CalculateChange(changeRest);

                currentData.Name             = proc.GetName();
                currentData.ChangeDictionary = monetaryObjs.Where(p => p.Value > 0).ToDictionary(p => p.Key, p => p.Value);

                long currentProduct = monetaryObjs.Sum(p => p.Key * p.Value);

                changeRest = changeRest - currentProduct;

                changeDataCollection.Add(currentData);

                // Dispara o evento informando que um processador foi executado.
                if (this.OnProcessorExecuted != null)
                {
                    string nameProcessor = proc.GetName();

                    this.OnProcessorExecuted(this, nameProcessor, currentProduct);
                }
            }

            return(changeDataCollection);
        }
Esempio n. 9
0
        public void TestEvalution()
        {
            string              docPath             = @"E:\桌面工作目录\正在进行的\My Little Pony Novel\无限维度\main.pony";
            ErrorListener       listener            = new ErrorListener();
            GlobalConfiguration globalConfiguration = GlobalConfiguration.Instance;
            PonyLexer           lexer  = new PonyLexer();
            PonyParser          parser = new PonyParser(lexer);

            lexer.errorListener  = globalConfiguration.ParserErrorListener;
            parser.errorListener = globalConfiguration.ParserErrorListener;
            PonyTextStructureBase structureBase = parser.Parse(File.ReadAllText(docPath));

            AssemblyInjectionManager injectionManager = new AssemblyInjectionManager();

            injectionManager.RegisterAssembly("PonyTextRenderer.Pdf", Assembly.GetAssembly(typeof(PdfRenderer)));
            injectionManager.RegisterAssembly("PonyText.Processor", Assembly.GetAssembly(typeof(PonyParser)));

            IProcessorFactory processor         = new ProcessorFactory(new ProcessorExperience(), injectionManager);
            SimpleTextContext simpleTextContext = new SimpleTextContext(processor, new TextElementFactory());

            processor.LoadProcessorFrom("PonyText.Processor");

            structureBase.Evaluate(simpleTextContext);

            PdfRenderer pdfRenderer = new PdfRenderer(simpleTextContext);

            simpleTextContext.GetCurrentContext().Render(pdfRenderer, simpleTextContext);

            using (FileStream fs = new FileStream("out.pdf", FileMode.Create)) {
                pdfRenderer.RenderContentTo(fs);
            }
        }
Esempio n. 10
0
        public static ExtractResultCollection ExtractSelector(string content, ExtractBase extractBase)
        {
            var pr = ProcessorFactory.Process(content, extractBase.Selectors);

            var  results = new ExtractResultCollection();
            Type t       = extractBase.ContentType;

            foreach (var m in pr.Matches)
            {
                ExtractResult result;

                try
                {
                    result = new ExtractResult
                    {
                        Name    = "tile",
                        Content = Convert.ChangeType(m, extractBase.ContentType)
                    };
                }
                catch
                {
                    result = new ExtractResult
                    {
                        Name    = "tile",
                        Content = m
                    };
                }

                results.Add(result);
            }

            return(results);
        }
Esempio n. 11
0
        public void Build_PostProcessing_Test()
        {
            var postProcessorConfig = Substitute.For <PostProcessorConfig>();

            var processor = ProcessorFactory.Build(postProcessorConfig);

            Assert.AreEqual(1, processor.PostProcessActions.Length);
        }
        public void Install(IContainer container)
        {
            var processorFactory = new ProcessorFactory();

            container.Register(Component.For <IProcessorFactory>().ImplementedBy(processorFactory).AsSingleton());

            this.RegisterDefaultContent(processorFactory);
        }
Esempio n. 13
0
        public ComputeChangeResponse ComputeChange(ComputeChangeRequest request)
        {
            ComputeChangeResponse response = new ComputeChangeResponse();

            Logger.Log(request);

            try {
                // Verifica se os dados recebidos são válidos.
                if (request.IsValid == false)
                {
                    response.OperationReport = request.ValidationReport;
                    return(response);
                }

                uint change                      = CalculateTotalChangeAmount(request.ReceivedAmount, request.ProductAmount);
                uint totalChangeAmount           = change;
                List <ChangeData> changeDataList = new List <ChangeData>();

                while (change > 0)
                {
                    AbstractProcessor processor = ProcessorFactory.Create(change);

                    if (processor == null)
                    {
                        Report report = new Report();
                        report.Message = "Ocorreu um erro: Não há troco disponível";
                        response.OperationReport.Add(report);
                        return(response);
                    }

                    Dictionary <uint, uint> changeDictionary = processor.Calculate(change);

                    ChangeData changeData = new ChangeData()
                    {
                        Name             = processor.GetName(),
                        ChangeDictionary = changeDictionary
                    };

                    changeDataList.Add(changeData);
                    long totalCurrentAmount = changeDictionary.Sum(p => (p.Value * p.Key));

                    change -= (uint)totalCurrentAmount;
                }
                response.ChangeDataList    = changeDataList;
                response.TotalChangeAmount = totalChangeAmount;
                response.Success           = true;
            }
            catch (Exception e) {
                Logger.Log(e);
                Report report = new Report();
                report.Message = "Ocorreu um erro: não foi possível processar sua operação.";
                response.OperationReport.Add(report);
            }

            Logger.Log(response);
            return(response);
        }
Esempio n. 14
0
        public void Build_EmptyPluginExceptionTest()
        {
            var empty = new object();
            var ex    = Assert.ThrowsException <ArgumentException>(() =>
            {
                ProcessorFactory.Build(empty);
            });

            Assert.AreEqual($"The plugin object \"{empty.ToString()}\" does not have any PreProcessing or ElementProcessing or PostProcessing attribute.", ex.Message);
        }
Esempio n. 15
0
 public void Start(Task task)
 {
     if (!IsBusy())
     {
         this.task      = task;
         this.processor = ProcessorFactory.CreateProcessor(task.Site);
         Downloading(task.Sender);
         executor.RunWorkerAsync();
     }
 }
        public void CreateProcessor_should_return_processor(PaymentGateway paymentGateway)
        {
            //Given : paymentGateway parameter

            //When
            var result = new ProcessorFactory().CreateProcessor(paymentGateway);

            //Then
            Assert.NotNull(result);
        }
        public void Directory_with_xml_files_returns_folder_processor()
        {
            var files          = s_expectedFiles.ToDictionary(s => "archive/" + s + ".xml", _ => new MockFileData("test"));
            var mockFileSystem = new MockFileSystem(files);

            var processorFactory = new ProcessorFactory(mockFileSystem);

            var processor = processorFactory.VerifyAndCreateProcessor("archive");

            processor.ShouldBeOfType <FolderProcessor>();
        }
        public void ProcessImage([FromBody] byte[] imageData, [FromQuery(Name = "ops")] string operations, [FromQuery] string strategy)
        {
            if (imageData == null || imageData.Length == 0)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return;
            }

            if (string.IsNullOrEmpty(strategy))
            {
                strategy = "functional";
            }

            try
            {
                logger.LogInformation("executing {0} strategy", strategy);

                var processor = ProcessorFactory.GetProcessor(strategy);
                if (processor == null)
                {
                    logger.LogInformation("unknown strategy {0}", strategy);
                    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                    return;
                }

                byte[] resultingImage = processor.ProcessImage(operations, imageData, loggerFactory);
                if (resultingImage == null || resultingImage.Count() == 0)
                {
                    logger.LogInformation("failed to process image");
                    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                    return;
                }

                logger.LogInformation("image processed, new image size is {0} bytes", resultingImage.Count());
                Response.StatusCode = (int)System.Net.HttpStatusCode.OK;

                // the underlying library is leving the image type intact, so we're just going to return it
                Response.ContentType = Request.ContentType;

                // write the image data back on the stream, we don't deal with Content-Length because
                // we're relying on aspnet core to use Transfer-Encoding: Chunked here
                Response.Body.Write(resultingImage);
            }
            catch (InvalidOperationException ioe)
            {
                logger.LogInformation("{0}", ioe);
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            }
            catch (Exception e)
            {
                logger.LogInformation("{0}", e);
                Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            }
        }
        public void CreateProcessor_should_return_visaprocessor_by_visapaymentgateway()
        {
            //Given
            var type = PaymentGateway.Visa;

            //When
            var result = new ProcessorFactory().CreateProcessor(type);

            //Then
            Assert.IsType <VisaProcessor>(result);
        }
 public void Init()
 {
     try
     {
         _processor = new ProcessorFactory();
         _processor.InitializeCompiler();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 21
0
        public void Build_ElementProcessing_Test()
        {
            var paragraph = new Paragraph();
            var elementProcessingConfig = Substitute.For <ElementProcessorConfig>();

            var processor = ProcessorFactory.Build(elementProcessingConfig);

            Assert.AreEqual(
                1,
                processor.ElementProcessingActions[typeof(Paragraph)].Length
                );
        }
        public void Archive_processor_is_created_for_7z_file()
        {
            var mockFileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { "archive.7z", new MockFileData("") }
            });

            var processorFactory = new ProcessorFactory(mockFileSystem);
            var processor        = processorFactory.VerifyAndCreateProcessor("archive.7z");

            processor.ShouldBeOfType <ArchiveProcessor>();
        }
Esempio n. 23
0
        public void CSVConvertTest()
        {
            ConfigLoader _testloader = new ConfigLoader();
            _testloader.Load();

            DataDownloader _testDownloader = new DataDownloader(_testloader.classConfigResult);
            _testDownloader.DataDownload();

            ProcessorFactory _testFactory = new ProcessorFactory(_testloader.classConfigResult);
            CSVProcessor _processor = _testFactory.GetYourProcessor() as CSVProcessor;

            Way _way = _processor.Process(_testDownloader.strDownloadData , _testloader.classConfigResult);

            Console.WriteLine(_way.Nodes.Count);

            Assert.IsNotNull(_way.Nodes);
        }
Esempio n. 24
0
        public void ProcessorFactoryTest()
        {
            ConfigLoader _testloader = new ConfigLoader();

            _testloader.Load();

            ProcessorFactory _testFactory = new ProcessorFactory(_testloader.classConfigResult);

            Assert.IsNotNull(_testFactory.GetYourProcessor());
        }