コード例 #1
0
 public PhotoService(IConverterFactory factory, BaseProvider <Photo> provider,
                     BaseProvider <Watermark> providerWatermark, BaseProvider <Tag> providerTag,
                     BaseProvider <PhotoToTag> providerPhotoToTag, BaseProvider <Album> providerAlbum)
 {
     _providerPhoto      = provider;
     _providerWatermark  = providerWatermark;
     _providerPhotoToTag = providerPhotoToTag;
     _providerTag        = providerTag;
     _factory            = factory;
     _providerAlbum      = providerAlbum;
     _converter          = _factory.GetConverter <IPhotoConverter>();
     _converterWatermark = _factory.GetConverter <IWatermarkConverter>();
     _converterTag       = _factory.GetConverter <ITagConverter>();
 }
コード例 #2
0
 public AlbumService(IConverterFactory factory, BaseProvider <Album> providerAlbum, IPhotoService photoService)
 {
     _providerAlbum = providerAlbum;
     _factory       = factory;
     _photoService  = photoService;
     _converter     = _factory.GetConverter <IAlbumConverter>();
 }
コード例 #3
0
 public TagService(IConverterFactory factory, BaseProvider <Tag> provider,
                   BaseProvider <PhotoToTag> providerPhotoToTag, BaseProvider <Photo> providerPhoto)
 {
     _providerTag        = provider;
     _providerPhoto      = providerPhoto;
     _providerPhotoToTag = providerPhotoToTag;
     _factory            = factory;
     _converter          = _factory.GetConverter <ITagConverter>();
 }
コード例 #4
0
        private IUnitConverter GetConverter(Unit unit)
        {
            var converter = converterFactory.GetConverter(unit);

            if (converter == null)
            {
                throw new Exception(string.Format("No Converter were found for this unit: {0}, please contact the dev, or create a new converter for the unit", unit));
            }
            return(converter);
        }
コード例 #5
0
        public void Run()
        {
            var data = _repository.GetAllRows();

            WriteLine("Csv raw data:");
            foreach (var line in data)
            {
                WriteLine(line);
            }
            WriteLine();
            WriteLine("Please choose conversion type:");
            foreach (var type in Enum.GetValues(typeof(ConverterType)))
            {
                WriteLine($"{(int) type!}:{type}");
            }
            WriteLine("Any other key to Exit!");

            ConsoleKeyInfo ch;

            do
            {
                ch = ReadKey();


                var converterService =
                    // ReSharper disable once SwitchExpressionHandlesSomeKnownEnumValuesWithExceptionInDefault
                    ch.Key switch
                {
                    ConsoleKey.D0 => _converterFactory.GetConverter(ConverterType.CsvToXml),
                    ConsoleKey.D1 => _converterFactory.GetConverter(ConverterType.CsvToJson),
                    _ => null
                };


                if (converterService != null)
                {
                    WriteLine(
                        $"{Environment.NewLine}Conversion result is: {Environment.NewLine}{converterService.Convert(data)}");
                }
            } while (ch.Key == ConsoleKey.D0 || ch.Key == ConsoleKey.D1);
        }
    }
コード例 #6
0
 public ManagementController(ITextAttributeService attrService, IImageProcessor imageProcessor,
                             IConverterFactory factory, IAlbumService albumService, IPhotoService photoService,
                             ITagService tagService, IWatermarkService watermarkService)
 {
     _imageProcessor   = imageProcessor;
     _factory          = factory;
     _converterAttr    = _factory.GetConverter <ITextAttributeConverter>();
     _attrService      = attrService;
     _albumService     = albumService;
     _tagService       = tagService;
     _photoService     = photoService;
     _watermarkService = watermarkService;
 }
コード例 #7
0
        public async override Task Run()
        {
            await base.Run();

            try
            {
                IsContinue();
                var path = _paramDescriptors.ConvertStr(File);
                var date = _paramDescriptors.ConvertDate(RunDateTime);

                Log.Info($"Задача {TaskId} : Загрузка данных");
                var currencies = _cbrDownloader.DownloadCurrencies(path);
                var pack       = new PackCurrencies()
                {
                    ValidDate  = date,
                    Currencies = currencies
                };

                Log.Info($"Задача {TaskId} : Конвертация данных");
                var converter    = _converterFactory.GetConverter(typeof(PackCurrencies));
                var importedDate = converter.ConvertToPackValues(pack);
                IsContinue();

                Log.Info($"Задача {TaskId} : Сохранение данных");
                _saver.Save(importedDate);

                Finished();
            }
            catch (OperationCanceledException)
            {
                Log.Info($"Задача отменена {TaskId}");
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            finally
            {
                IsAliveTokenSource.Cancel();
            }
        }
コード例 #8
0
ファイル: Prompt.cs プロジェクト: johncrn/ScriptCs.Prompt
        /// <summary>
        /// Prompts the user for a valid value. Will continue to re-prompt until one is entered.
        /// </summary>
        /// <typeparam name="T">The type of value to be input. Supports structs.</typeparam>
        /// <param name="prompt">The prompt displayed to the user</param>
        /// <param name="defaultVal">The default value returned if no input is entered</param>
        /// <param name="defaultValLabel">If a defaultVal is supplied, this label will be used instead of the value in the prompt. (e.g. you may wish to display TODAY instead of the full date)</param>
        /// <param name="validator">Runs after the type conversion has taken place. If the function returns a string it will be displayed and the user will be reprompted for a valid value. </param>
        /// <param name="converter">Overrides the converter supplied by the converterFactory (which defaults to TypeDescriptor.GetConverter unless overriden in constructor)</param>
        /// <returns>A valid value in the specified type converted from user input.</returns>
        public T For <T>(string prompt, T?defaultVal = null, string defaultValLabel = null, Func <T, string> validator = null, IConverter <T> converter = null) where T : struct
        {
            T result = default(T);

            if (converter == null)
            {
                converter = _converterFactory.GetConverter <T>();
            }

            if (!converter.CanConvertFrom(typeof(string)))
            {
                throw new NotSupportedException(String.Format("{0} cannot convert from string to {1}", converter.GetType().ToString(), typeof(T).ToString()));
            }

            bool validInput = false;

            do
            {
                string promptLine = !defaultVal.HasValue ? String.Format("{0}: ", prompt) : String.Format("{0} (ENTER for {1}): ", prompt, (!String.IsNullOrWhiteSpace(defaultValLabel) ? defaultValLabel : String.Format("\"{0}\"", defaultVal.ToString())));
                _console.WriteLine(promptLine);
                _console.WriteLine();
                _console.Write("> ");

                var userInput = _console.ReadLine();

                // Return the default value if supplied and user hit ENTER
                if (defaultVal.HasValue && String.IsNullOrWhiteSpace(userInput))
                {
                    return(defaultVal.Value);
                }

                bool convertSuccess = false;

                if (String.IsNullOrWhiteSpace(userInput))
                {
                    _console.WriteLine("Please enter a value.");
                }
                else
                {
                    // Otherwise try to convert the string to the specified type
                    try
                    {
                        result         = converter.ConvertFromString(userInput);
                        convertSuccess = true;
                    }
                    catch
                    {
                        _console.WriteLine("Invalid input. Cannot convert \"{0}\" to {1}.", userInput, result.GetType().ToString());
                    }
                }
                if (convertSuccess)
                {
                    if (validator == null)
                    {
                        validInput = true;
                    }
                    else
                    {
                        var validatorMessage = validator(result);

                        if (String.IsNullOrWhiteSpace(validatorMessage))
                        {
                            validInput = true;
                        }
                        else
                        {
                            _console.WriteLine(validatorMessage);
                        }
                    }
                }
            } while (!validInput);

            return(result);
        }
コード例 #9
0
 public WatermarkService(IConverterFactory factory, BaseProvider <Watermark> provider)
 {
     _providerWatermark = provider;
     _factory           = factory;
     _converter         = _factory.GetConverter <IWatermarkConverter>();
 }
コード例 #10
0
ファイル: JobRunner.cs プロジェクト: ravisayal/PDFCreator
        /// <summary>
        ///     Runs the job and all actions
        /// </summary>
        public async Task RunJob(Job job, IOutputFileMover outputFileMover) //todo: Store OutputFileMover somewhere workflow dependant
        {
            _logger.Trace("Starting job");

            _logger.Debug("Output filename template is: {0}", job.OutputFileTemplate);
            _logger.Debug("Output format is: {0}", job.Profile.OutputFormat);
            _logger.Info("Converting " + job.OutputFileTemplate);

            SetTempFolders(job);

            try
            {
                // TODO: Use async/await
                _actionExecutor.CallPreConversionActions(job);

                _processingHelper.ApplyFormatRestrictionsToProfile(job);

                var converter      = _converterFactory.GetConverter(job.JobInfo.JobType);
                var reportProgress = new EventHandler <ConversionProgressChangedEventArgs>((sender, args) => job.ReportProgress(args.Progress));
                converter.OnReportProgress += reportProgress;

                var isPdf = job.Profile.OutputFormat.IsPdf();
                var isProcessingRequired = _processingHelper.IsProcessingRequired(job);
                converter.Init(isPdf, isProcessingRequired);

                converter.FirstConversionStep(job);

                _actionExecutor.CallConversionActions(job);

                converter.SecondConversionStep(job);

                converter.OnReportProgress -= reportProgress;

                await outputFileMover.MoveOutputFiles(job);

                if (job.OutputFiles.Count == 0)
                {
                    _logger.Error("No output files were created for unknown reason");
                    throw new ProcessingException("No output files were created for unknown reason", ErrorCode.Conversion_UnknownError);
                }

                LogOutputFiles(job);

                job.TokenReplacer = _tokenReplacerFactory.BuildTokenReplacerWithOutputfiles(job);

                _actionExecutor.CallPostConversionActions(job);

                CleanUp(job);

                job.IsSuccessful = true;
                _logger.Trace("Job finished successfully");
            }
            catch (Exception ex)
            {
                if (ex is ProcessingException processingException)
                {
                    _logger.Error($"The job failed: {processingException.Message} ({processingException.ErrorCode})");
                }
                else
                {
                    _logger.Error(ex, $"The job failed: {ex.Message}");
                }

                if (job.CleanUpOnError)
                {
                    CleanUp(job);
                }

                throw;
            }
            finally
            {
                _logger.Trace("Calling job completed event");
                job.CallJobCompleted();
            }
        }
コード例 #11
0
 public TextAttributeService(IConverterFactory factory, BaseProvider <TextAttributes> provider)
 {
     _providerAttr = provider;
     _factory      = factory;
     _converter    = _factory.GetConverter <ITextAttributeConverter>();
 }
コード例 #12
0
 public object ConvertFromString(
     Guid conversionId, string inputValue) =>
 _conversionStrategyFactory
 .GetConverter(conversionId)
 .ConvertGeneric(inputValue);
コード例 #13
0
        public void TestGetConverter()
        {
            var converter = _converterFactory.GetConverter(typeof(PackCurrencies));

            Assert.NotNull(converter);
        }