Ejemplo n.º 1
0
        public FileResult PDF(string html)
        {
            var host    = this.HttpContext.Request.Scheme + "://" + this.HttpContext.Request.Host.Value;
            var matches = Regex.Matches(html, @"href=""(\/.*)"">");

            foreach (Match match in matches)
            {
                var value = match.Groups[1].Value;
                html = html.Replace(value, host + value);
            }

            var wkhtmltopdf = new FileInfo(@"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe");
            var converter   = new HtmlToPdfConverter(wkhtmltopdf);
            var settings    = new ConversionSettings(
                pageSize: PageSize.A4,
                orientation: PageOrientation.Portrait,
                margins: new PageMargins(10, 5, 5, 5),
                grayscale: false,
                lowQuality: false,
                quiet: true,
                enableJavaScript: true,
                javaScriptDelay: null,
                enableExternalLinks: true,
                enableImages: true,
                executionTimeout: null);
            var    pdfBytes = converter.ConvertToPdf(html, Encoding.UTF8, settings);
            string result   = System.Text.Encoding.UTF8.GetString(pdfBytes);

            return(File(pdfBytes, "application/pdf", "magic.pdf"));
        }
        private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            ((Button)sender).Focus();

            Result = new ConversionSettings
            {
                Min  = MinValue,
                Max  = MaxValue,
                Mode = ConversionMode
            };

            if (ConversionMode == ConversionMode.Custom)
            {
                CustomConversionDialog dialog = new CustomConversionDialog(
                    _previousPattern ?? new RelativePositionCollection(),
                    _previousBeats ?? new [] { true, true });
                if (dialog.ShowDialog() != true)
                {
                    return;
                }

                _previousPattern = dialog.Positions;
                _previousBeats   = dialog.BeatPattern;

                Result.CustomPositions = dialog.Positions;
                Result.BeatPattern     = dialog.BeatPattern;
            }

            DialogResult = true;
        }
Ejemplo n.º 3
0
        static public ConversionSettings LoadSettings(string settingsPath)
        {
            //Load XML settings file
            XmlDocument settingsConfig = new XmlDocument();

            settingsConfig.Load(settingsPath);

            ConversionSettings conversionsSettings = new ConversionSettings();

            string jpegPath   = LoadElementFromXML(settingsConfig, _jpegInputPathString);
            string pdfPath    = LoadElementFromXML(settingsConfig, _pdfInputPathString);
            string outputPath = LoadElementFromXML(settingsConfig, _outputPathString);

            conversionsSettings.JPEGInputPath  = String.IsNullOrEmpty(jpegPath) ? Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "JPEG In") : jpegPath;
            conversionsSettings.PDFInputPath   = String.IsNullOrEmpty(pdfPath) ? Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "PDF In") : pdfPath;
            conversionsSettings.OutputPath     = String.IsNullOrEmpty(outputPath) ? Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Out") : outputPath;
            conversionsSettings.MoveSourcePath = LoadElementFromXML(settingsConfig, _moveSourcePath);

            int conversionFrequency = 0;

            Int32.TryParse(LoadElementFromXML(settingsConfig, _conversionFrequencyString), out conversionFrequency);
            conversionsSettings.ConversionFrequency = conversionFrequency < 5 ? 30 : conversionFrequency;

            return(conversionsSettings);
        }
        public string GetVocabularyVersion([FromBody] ConversionSettings settings)
        {
            const string query = "SELECT VOCABULARY_VERSION FROM vocabulary WHERE VOCABULARY_ID = 'None'";

            try
            {
                var cs = _configuration[settings.VocabularyEngine]
                         .Replace("{server}", settings.VocabularyServer)
                         .Replace("{database}", settings.VocabularyDatabase)
                         .Replace("{username}", settings.VocabularyUser)
                         .Replace("{password}", settings.VocabularyPassword);

                using var c      = new OdbcConnection(cs);
                using var cmd    = new OdbcCommand(query, c);
                using var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    return(reader.GetString(0));
                }
            }
            catch (Exception)
            {
                return("Unknown");
            }

            return("Unknown");
        }
Ejemplo n.º 5
0
        static public void SaveSettings(string settingsPath, ConversionSettings conversionSettings)
        {
            XmlDocument xDoc = new XmlDocument();
            // Create declaration
            XmlDeclaration xmlDeclaration = xDoc.CreateXmlDeclaration("1.0", null, null);

            xDoc.AppendChild(xmlDeclaration);

            // Create root element
            XmlElement root = xDoc.CreateElement(_conversionSettings);

            xDoc.AppendChild(root);

            //Add PDF path
            AddElementToXML(xDoc, root, _pdfInputPathString, conversionSettings.PDFInputPath);
            //Add JPEG path
            AddElementToXML(xDoc, root, _jpegInputPathString, conversionSettings.JPEGInputPath);
            //Add Output path
            AddElementToXML(xDoc, root, _outputPathString, conversionSettings.OutputPath);
            //Add conversion frequency
            AddElementToXML(xDoc, root, _conversionFrequencyString, conversionSettings.ConversionFrequency.ToString());
            //Add MoveSourcePath
            AddElementToXML(xDoc, root, _moveSourcePath, conversionSettings.MoveSourcePath);

            xDoc.Save(settingsPath);
        }
Ejemplo n.º 6
0
        private async System.Threading.Tasks.Task <byte[]> CreateFilePDFAsync <T>(IReportsGrandGridView <T> groupedList)
        {
            if (!RunSetCommonValuesForExport)
            {
                throw new InvalidOperationException("You forgot run SetCommonValuesForExport() for set common values.");
            }

            var pdfBytesResult = new byte[0];

            #region Set root paths and give names for files.

            var fileNameWkhtmltopdf   = "wkhtmltopdf.exe";
            var fileNamePDFMarkUpView = "PDFMarkUpView.cshtml";

            var contentRootPath = _environment.ContentRootPath;

            var pathContentPDF            = $"{contentRootPath}\\Content\\PDF";
            var pathContentPDFCssStyle    = $"{pathContentPDF}\\Site.css";
            var pathContentPDFWkhtmltopdf = $"{pathContentPDF}\\{fileNameWkhtmltopdf}";

            var pathFileInfo = new FileInfo(pathContentPDFWkhtmltopdf);

            #endregion

            if (File.Exists(pathContentPDFWkhtmltopdf))
            {
                var pdfModel = new ReportsPDFCommonView(pathContentPDFCssStyle, GroupById, GetPeriodPDFCell())
                {
                    PDFGrandModel = CreateReportsGrandGridModel(groupedList)
                };

                #region Parse view.

                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(pathContentPDF)
                             .UseMemoryCachingProvider()
                             .Build();

                var htmlFromParsedViewRazorLight = await engine.CompileRenderAsync(fileNamePDFMarkUpView, pdfModel);

                var settings = new ConversionSettings(
                    pageSize: PageSize.A4,
                    orientation: PageOrientation.Landscape,
                    margins: new WkWrap.Core.PageMargins(5, 10, 5, 10),
                    grayscale: false,
                    lowQuality: false,
                    quiet: false,
                    enableJavaScript: true,
                    javaScriptDelay: null,
                    enableExternalLinks: true,
                    enableImages: true,
                    executionTimeout: null);

                pdfBytesResult = new HtmlToPdfConverter(pathFileInfo).ConvertToPdf(htmlFromParsedViewRazorLight, Encoding.UTF8, settings);

                #endregion
            }

            return(pdfBytesResult);
        }
Ejemplo n.º 7
0
        public ConversionController(IBackgroundTaskQueue taskQueue, ConversionSettings settings, IConfiguration configuration, IHubContext <LogHub> logHub)
        {
            _logHub   = logHub;
            _settings = new Settings(settings, configuration);

            _settings.Load();
            _vocabulary = new Vocabulary(_settings, _logHub);
            _taskQueue  = taskQueue;
        }
Ejemplo n.º 8
0
        private static string SettingsAsXml(ConversionSettings settings)
        {
            StringWriter writer         = new StringWriter();
            var          writerSettings = new XmlWriterSettings {
                Indent = true, OmitXmlDeclaration = true
            };

            settingsSerialiser.Serialize(XmlWriter.Create(writer, writerSettings), settings);
            return(writer.ToString());
        }
 public InputScreenViewModel()
 {
     UIDispatcher    = Dispatcher.CurrentDispatcher;
     Input           = new ObservableCollection <string>();
     AutoFillBrushes = new ObservableCollection <BrushWrapper> {
         new BrushWrapper("None", Brushes.Transparent), new BrushWrapper("Black", Brushes.Black), new BrushWrapper("Red", Brushes.Red), new BrushWrapper("Blue", Brushes.Blue), new BrushWrapper("Green", Brushes.Green)
     };
     ConversionSettings = new ConversionSettings {
         AutoFill = AutoFillBrushes[0], XamlOutputEnabled = true, PathOutputEnabled = true, IsPreviewEnabled = true
     };
 }
Ejemplo n.º 10
0
        private async Task <byte[]> CreateFilePDFAsync(ReportTotalView reportTotalView)
        {
            var pdfBytesResult = new byte[0];

            #region Set root paths and give names for files.

            var fileNameWkhtmltopdf   = "wkhtmltopdf.exe";
            var fileNamePDFMarkUpView = "PDFMarkUpView.cshtml";

            var contentRootPath = _environment.ContentRootPath;

            var pathContentPDF            = $"{contentRootPath}\\Content\\PDF";
            var pathContentPDFCssStyle    = $"{pathContentPDF}\\Site.css";
            var pathContentPDFWkhtmltopdf = $"{pathContentPDF}\\{fileNameWkhtmltopdf}";

            var pathFileInfo = new FileInfo(pathContentPDFWkhtmltopdf);

            #endregion

            if (File.Exists(pathContentPDFWkhtmltopdf))
            {
                var reportsExportView = new ReportExportPDFView(pathContentPDFCssStyle, /*GetPeriodPDFCell(),*/ reportTotalView);

                #region Parse view.

                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(pathContentPDF)
                             .UseMemoryCachingProvider()
                             .Build();

                var htmlFromParsedViewRazorLight = await engine.CompileRenderAsync(fileNamePDFMarkUpView, reportsExportView);

                var settings = new ConversionSettings(
                    pageSize: PageSize.A4,
                    orientation: PageOrientation.Landscape,
                    margins: new WkWrap.Core.PageMargins(5, 10, 5, 10),
                    grayscale: false,
                    lowQuality: false,
                    quiet: false,
                    enableJavaScript: true,
                    javaScriptDelay: null,
                    enableExternalLinks: true,
                    enableImages: true,
                    executionTimeout: null);

                pdfBytesResult = new HtmlToPdfConverter(pathFileInfo).ConvertToPdf(htmlFromParsedViewRazorLight, Encoding.UTF8, settings);

                #endregion
            }

            return(pdfBytesResult);
        }
Ejemplo n.º 11
0
        private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            ((Button)sender).Focus();

            Result = new ConversionSettings
            {
                Min  = MinValue,
                Max  = MaxValue,
                Mode = ConversionMode
            };

            DialogResult = true;
        }
Ejemplo n.º 12
0
 private void _reset()
 {
     ConversionEngine.StartNew(_scriptsLocation, _enableLogging);
     SourceTextBox.Text                = "";
     InPlaceCheckBox.IsChecked         = false;
     OutputTextBox.Text                = "";
     ToBinRadioButton.IsChecked        = false;
     ToTxtRadioButton.IsChecked        = false;
     OriginalSinsRadioButton.IsChecked = false;
     EntrenchmentRadioButton.IsChecked = false;
     DiplomacyRadioButton.IsChecked    = false;
     RebellionRadioButton.IsChecked    = false;
     _currentSettings = new ConversionSettings();
 }
Ejemplo n.º 13
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            // ** Get request body data.
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  FileName    = data?.fileName;
            string  FileContent = data?.fileContent;

            byte[] convFile = null;

            DocumentConverterServiceClient client = null;

            try
            {
                byte[] sourceFile = Convert.FromBase64String(FileContent);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = FileName;
                openOptions.FileExtension    = Path.GetExtension(FileName);

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();
                conversionSettings.Fidelity = ConversionFidelities.Full;
                conversionSettings.Quality  = ConversionQuality.OptimizeForPrint;

                convFile = client.ConvertAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(new
                {
                    message = ex.ToString()
                }));
            }
            finally
            {
                CloseService(client);
            }
            return((ActionResult) new OkObjectResult(new
            {
                processed_file_content = convFile,
            }));
        }
        /*
         * Immediately convert file on a server
         * In case of success returned converted file as Stream
         * In case of any error exception will be throw
         */
        public async Task <Stream> Convert(DocType doctype, Stream file, ConversionOptions options)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(Url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            ConversionSettings settings = new ConversionSettings(Domain, Username, Password);

            settings.Options = options;

            // get file content
            using (MemoryStream ms = new MemoryStream())
            {
                file.CopyTo(ms);
                byte[] bytes = ms.ToArray();
                settings.Content = System.Convert.ToBase64String(bytes);
            }

            HttpResponseMessage response = await client.PostAsJsonAsync("api/convert/file/" + doctype.ToString(), settings);

            OASResponse resp = null;

            if (response.IsSuccessStatusCode)
            {
                resp = await response.Content.ReadAsAsync <OASResponse>();

                if (resp.ErrorCode == OASErrorCodes.Success)
                {
                    MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(resp.Content));
                    return(ms);
                }
                else
                {
                    OASConversionException ex = new OASConversionException(resp.Message);
                    ex.Source = resp.ErrorCode.ToString();
                    throw ex;
                }
            }
            else
            {
                OASWebServiceException ex = new OASWebServiceException(response.ReasonPhrase);
                ex.Source = response.StatusCode.ToString();
                throw ex;
            }
        }
Ejemplo n.º 15
0
        public IActionResult CheckVocabularyConnection([FromBody] ConversionSettings settings)
        {
            try
            {
                ChekConnectionString(settings.VocabularyEngine,
                                     settings.VocabularyServer,
                                     settings.VocabularyDatabase,
                                     settings.VocabularyUser,
                                     settings.VocabularyPassword);
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e));
            }

            return(Ok());
        }
        public IActionResult CheckDestinationConnection([FromBody] ConversionSettings settings)
        {
            try
            {
                ChekConnectionString(settings.DestinationEngine,
                                     settings.DestinationServer,
                                     settings.DestinationDatabase,
                                     settings.DestinationUser,
                                     settings.DestinationPassword,
                                     settings.DestinationPort.ToString());
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest, e.Message + e.InnerException));
            }

            return(Ok());
        }
        public IActionResult CheckVocabularyConnection([FromBody] ConversionSettings settings)
        {
            try
            {
                ChekConnectionString(settings.VocabularyEngine,
                                     settings.VocabularyServer,
                                     settings.VocabularyDatabase,
                                     settings.VocabularyUser,
                                     settings.VocabularyPassword,
                                     settings.VocabularyPort.ToString());
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest, e.Message));
            }

            return(Ok());
        }
Ejemplo n.º 18
0
        protected override void OnElementChanged(ElementChangedEventArgs <CustomWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                SetNativeControl(new UIWebView());
            }
            if (e.OldElement != null)
            {
                // Cleanup
            }
            if (e.NewElement != null)
            {
                var customWebView = Element as CustomWebView;

                string bundlePath = NSBundle.MainBundle.BundlePath;

                Document document = new Document();
                Section  section  = document.Sections.Add();

                XhtmlParagraph xhtmlParagraph = new XhtmlParagraph();

                ConversionSettings conversionSettings = new ConversionSettings();
                conversionSettings.FontPath      = Path.Combine(bundlePath, "fonts");
                conversionSettings.FontEmbedMode = TallComponents.PDF.Layout.Fonts.EmbedMode.Full;

                Console.WriteLine($"I am looking for fonts at {conversionSettings.FontPath}");

                xhtmlParagraph.Settings = conversionSettings;
                xhtmlParagraph.Text     = File.ReadAllText("test.html");
                section.Paragraphs.Add(xhtmlParagraph);

                // convert to PDF and save
                string pdfPath = Path.Combine(bundlePath, "out.pdf");
                using (FileStream fs = new FileStream(pdfPath, FileMode.Create))
                {
                    document.Write(fs);
                }

                Control.LoadRequest(new NSUrlRequest(new NSUrl(pdfPath, false)));
                Control.ScalesPageToFit = true;
            }
        }
        public IActionResult CheckSourceConnection([FromBody] ConversionSettings settings)
        {
            try
            {
                //AllowCrossOrigin();
                ChekConnectionString(settings.SourceEngine,
                                     settings.SourceServer,
                                     settings.SourceDatabase,
                                     settings.SourceUser,
                                     settings.SourcePassword,
                                     settings.SourcePort.ToString());
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest, e.Message + e.InnerException));
            }

            return(Ok());
        }
        public BeatConversionSettingsDialog(ConversionSettings initialValues = null)
        {
            ConversionModes = new List <ConversionMode>(Enum.GetValues(typeof(ConversionMode)).Cast <ConversionMode>());

            if (initialValues == null)
            {
                ConversionMode = ConversionMode.UpOrDown;
                MinValue       = 0;
                MaxValue       = 99;
            }
            else
            {
                ConversionMode = initialValues.Mode;
                MinValue       = initialValues.Min;
                MaxValue       = initialValues.Max;
            }

            InitializeComponent();
        }
        /*
         * Get converted file as result of convertion job
         * In case of not ready yet null value will be returned
         * In case of any error exception will the fired
         */
        public async Task <Stream> GetConvertedFile(string FileId)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(Url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            ConversionSettings settings = new ConversionSettings(Domain, Username, Password);

            HttpResponseMessage response = await client.PostAsJsonAsync("api/convert/getfile/" + FileId, settings);

            OASResponse resp = null;

            if (response.IsSuccessStatusCode)
            {
                resp = await response.Content.ReadAsAsync <OASResponse>();

                if (resp.ErrorCode == OASErrorCodes.Success)
                {
                    MemoryStream ms = null;
                    if (resp.Content != null)
                    {
                        ms = new MemoryStream(System.Convert.FromBase64String(resp.Content));
                    }
                    return(ms);
                }
                else
                {
                    OASConversionException ex = new OASConversionException(resp.Message);
                    ex.Source = resp.ErrorCode.ToString();
                    throw ex;
                }
            }
            else
            {
                OASWebServiceException ex = new OASWebServiceException(response.ReasonPhrase);
                ex.Source = response.StatusCode.ToString();
                throw ex;
            }
        }
Ejemplo n.º 22
0
Archivo: ParseT9.cs Proyecto: iOgre/T9
 private Keypress ParseCharToKeypress(char input, ConversionSettings cs = ConversionSettings.Default)
 {
     //ConversionSettings cs = ConversionSettings.Default;
     if (T9Mappings.CharToDigits.TryGetValue(input, out var keypress))
     {
         return(keypress);
     }
     else
     {
         if (cs.HasFlag(ConversionSettings.FailOnUnconvertable))
         {
             var message = $"Cannot convert character {input} to T9";
             Log.Warn(message);
             throw new T9ConversionException(message);
         }
         else
         {
             Log.Warn($"Unsuccesful attempt to convert {input} into T9 sequence");
         }
         keypress = new Keypress(-1, -1, input);
         return(keypress);
     }
 }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            DocumentConverterServiceClient client = null;

            try
            {
                // ** Determine the source file and read it into a byte array.
                string sourceFileName = null;
                if (args.Length == 0)
                {
                    // ** If nothing is specified then read the first PDF file from the current folder.
                    string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf");
                    if (sourceFiles.Length > 0)
                    {
                        sourceFileName = sourceFiles[0];
                    }
                    else
                    {
                        Console.WriteLine("Please specify a document to convert to PDF/A.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    sourceFileName = args[0];
                }

                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
                openOptions.FileExtension    = "pdf";

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();

                // ** Set output to PDF/A
                conversionSettings.PDFProfile = PDFProfile.PDF_A2B;

                // ** Specify output settings as we want to force post processing of files.
                OutputFormatSpecificSettings_PDF osf = new OutputFormatSpecificSettings_PDF();
                osf.PostProcessFile = true;
                // ** We need to specify ALL values of an object, so use these for PDF/A
                osf.FastWebView   = false;
                osf.EmbedAllFonts = true;
                osf.SubsetFonts   = false;
                conversionSettings.OutputFormatSpecificSettings = osf;

                // ** Carry out the conversion.
                Console.WriteLine("Converting file " + sourceFileName + " to PDF/A.");
                byte[] convFile = client.ProcessChangesAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult();

                // ** Write the converted file back to the file system with a PDF extension.
                string destinationFileName = Path.GetFileNameWithoutExtension(sourceFileName) + "_PDFA.pdf";
                using (FileStream fs = File.Create(destinationFileName))
                {
                    fs.Write(convFile, 0, convFile.Length);
                    fs.Close();
                }

                Console.WriteLine("File converted to " + destinationFileName);
            }
            catch (FaultException <WebServiceFaultException> ex)
            {
                Console.WriteLine("FaultException occurred: ExceptionType: " +
                                  ex.Detail.ExceptionType.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                CloseService(client);
            }
        }
Ejemplo n.º 24
0
Archivo: ParseT9.cs Proyecto: iOgre/T9
 public ParseT9(ConversionSettings cs)
 {
     _cs = cs;
 }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            DocumentConverterServiceClient client = null;

            try
            {
                // ** Delete any processed files from a previous run
                foreach (FileInfo f in new DirectoryInfo(".").GetFiles("*_ocr.pdf"))
                {
                    f.Delete();
                }

                // ** Determine the source file and read it into a byte array.
                string sourceFileName = null;
                if (args.Length == 0)
                {
                    // ** If nothing is specified then read the first PDF file from the current folder.
                    string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf");
                    if (sourceFiles.Length > 0)
                    {
                        sourceFileName = sourceFiles[0];
                    }
                    else
                    {
                        Console.WriteLine("Please specify a document to OCR.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    sourceFileName = args[0];
                }

                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
                openOptions.FileExtension    = Path.GetExtension(sourceFileName);

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();

                // ** OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR
                OCRSettings ocr = new OCRSettings();
                ocr.Language    = OCRLanguage.English.ToString();
                ocr.Performance = OCRPerformance.Slow;
                ocr.WhiteList   = string.Empty;
                ocr.BlackList   = string.Empty;
                conversionSettings.OCRSettings = ocr;
                // ** OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR OCR

                // ** Carry out the conversion.
                Console.WriteLine("Processing file " + sourceFileName + ".");
                byte[] convFile = client.ProcessChanges(sourceFile, openOptions, conversionSettings);

                // ** Write the processed file back to the file system with a PDF extension.
                string destinationFileName = Path.GetFileNameWithoutExtension(sourceFileName) + "_ocr.pdf";
                using (FileStream fs = File.Create(destinationFileName))
                {
                    fs.Write(convFile, 0, convFile.Length);
                    fs.Close();
                }

                Console.WriteLine("File written to " + destinationFileName);

                // ** Open the generated PDF file in a PDF Reader
                Console.WriteLine("Launching file in PDF Reader");
                Process.Start(destinationFileName);
            }
            catch (FaultException <WebServiceFaultException> ex)
            {
                Console.WriteLine("FaultException occurred: ExceptionType: " +
                                  ex.Detail.ExceptionType.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                CloseService(client);
            }
            Console.ReadKey();
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            DocumentConverterServiceClient client = null;

            try
            {
                // ** Determine the source file and read it into a byte array.
                string sourceFileName = null;
                if (args.Length == 0)
                {
                    // ** Only .docx, .xlsx or .pptx filea are accepted
                    string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.docx");
                    if (sourceFiles.Length > 0)
                    {
                        sourceFileName = sourceFiles[0];
                    }
                    else
                    {
                        Console.WriteLine("Please specify a document to convert and watermark.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    sourceFileName = args[0];
                }

                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
                openOptions.FileExtension    = Path.GetExtension(sourceFileName);

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();
                // ** Format must be the same as the input format.
                // ** Resolve by parsing the extension into OtputFormat enum.
                // ** Leading dot (.) must be removed to make the parsing work.
                string format = Path.GetExtension(sourceFileName).TrimStart(new char[] { '.' });
                conversionSettings.Format   = (OutputFormat)Enum.Parse(typeof(OutputFormat), format, true);
                conversionSettings.Fidelity = ConversionFidelities.Full;
                conversionSettings.Quality  = ConversionQuality.OptimizeForPrint;

                // ** Get the list of watermarks to apply.
                conversionSettings.Watermarks = CreateWatermarks();

                // ** Carry out the watermarking.
                Console.WriteLine("Watermarking file " + sourceFileName);
                byte[] watermarkedFile = client.ApplyWatermark(sourceFile, openOptions, conversionSettings);

                // ** Write the watermarked file back to the file system with.
                string destinationFileName = Path.GetDirectoryName(sourceFileName) + @"\" +
                                             Path.GetFileNameWithoutExtension(sourceFileName) +
                                             "_Watermarked." + conversionSettings.Format;
                using (FileStream fs = File.Create(destinationFileName))
                {
                    fs.Write(watermarkedFile, 0, watermarkedFile.Length);
                    fs.Close();
                }

                Console.WriteLine("File watermarked to " + destinationFileName);

                // ** Open the generated file
                Console.WriteLine("Opening result document.");
                Process.Start(destinationFileName);
            }
            catch (FaultException <WebServiceFaultException> ex)
            {
                Console.WriteLine("FaultException occurred: ExceptionType: " +
                                  ex.Detail.ExceptionType.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                CloseService(client);
            }
            Console.ReadKey();
        }
        public void GenerateAndUploadPDFtoSharePoint(string RelativeUrl, string PatientId, ConsentType ConsentFormType)
        {
            DocumentConverterServiceClient client = null;
            try
            {
                string sourceFileName = null;
                byte[] sourceFile = null;
                client = OpenService("http://localhost:41734/Muhimbi.DocumentConverter.WebService/");
                OpenOptions openOptions = new OpenOptions();

                //** Specify optional authentication settings for the web page
                openOptions.UserName = "";
                openOptions.Password = "";

                // ** Specify the URL to convert
                openOptions.OriginalFileName = RelativeUrl;
                openOptions.FileExtension = "html";

                //** Generate a temp file name that is later used to write the PDF to
                sourceFileName = Path.GetTempFileName();
                File.Delete(sourceFileName);

                // ** Enable JavaScript on the page to convert.
                openOptions.AllowMacros = MacroSecurityOption.All;

                // ** Set the various conversion settings
                ConversionSettings conversionSettings = new ConversionSettings();
                conversionSettings.Fidelity = ConversionFidelities.Full;
                conversionSettings.PDFProfile = PDFProfile.PDF_1_5;
                conversionSettings.Quality = ConversionQuality.OptimizeForOnScreen;

                // ** Carry out the actual conversion
                byte[] convertedFile = client.Convert(sourceFile, openOptions, conversionSettings);

                //try
                //{
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (var site = new SPSite(SiteUrl))
                    {
                        using (var web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            var list = web.Lists.TryGetList(DocumentLibary);
                            if (list != null)
                            {
                                var libFolder = list.RootFolder;

                                var patientDetails = GetPatientDetail(PatientId, ConsentFormType.ToString());

                                if (patientDetails != null)
                                {
                                    string fileName = ConsentFormType + patientDetails.MRHash + patientDetails.name + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                    switch (ConsentFormType)
                                    {
                                        case ConsentType.Surgical:
                                            {
                                                fileName = "SUR_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.BloodConsentOrRefusal:
                                            {
                                                fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.Cardiovascular:
                                            {
                                                fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.Endoscopy:
                                            {
                                                fileName = "ENDO_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.OutsideOR:
                                            {
                                                fileName = "OUTSDE_OR_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.PICC:
                                            {
                                                fileName = "PICC_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                        case ConsentType.PlasmanApheresis:
                                            {
                                                fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                break;
                                            }
                                    }

                                    if (libFolder.RequiresCheckout) { try { SPFile fileOld = libFolder.Files[fileName]; fileOld.CheckOut(); } catch { } }
                                    var spFileProperty = new Hashtable();
                                    spFileProperty.Add("MR#", patientDetails.MRHash);
                                    spFileProperty.Add("Patient#", PatientId);
                                    spFileProperty.Add("Patient Name", patientDetails.name);
                                    spFileProperty.Add("DOB#", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(patientDetails.DOB));
                                    spFileProperty.Add("Procedure Type", patientDetails.ProcedureName);
                                    spFileProperty.Add("Patient Information", patientDetails.name + " " + DateTime.Now.ToShortDateString());

                                    SPFile spfile = libFolder.Files.Add(fileName, convertedFile, spFileProperty, true);

                                    list.Update();

                                    if (libFolder.RequiresCheckout)
                                    {
                                        spfile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
                                        spfile.Publish("Publish Comment");
                                    }
                                }
                            }

                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            finally
            {
                CloseService(client);
            }
        }
        static void Main(string[] args)
        {
            DocumentConverterServiceClient client = null;

            try
            {
                // ** Determine the source file and read it into a byte array.
                string sourceFileName = null;
                if (args.Length == 0)
                {
                    string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.doc*");
                    if (sourceFiles.Length > 0)
                    {
                        sourceFileName = sourceFiles[0];
                    }
                    else
                    {
                        Console.WriteLine("Please specify a document to convert and watermark.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    sourceFileName = args[0];
                }

                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
                openOptions.FileExtension    = Path.GetExtension(sourceFileName);

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();
                conversionSettings.Fidelity = ConversionFidelities.Full;
                conversionSettings.Quality  = ConversionQuality.OptimizeForPrint;

                // ** Get the list of watermarks to apply.
                conversionSettings.Watermarks = CreateWatermarks();

                // ** Carry out the conversion.
                Console.WriteLine("Converting file " + sourceFileName);
                byte[] convFile = client.ConvertAsync(sourceFile, openOptions, conversionSettings).GetAwaiter().GetResult();

                // ** Write the converted file back to the file system with a PDF extension.
                string destinationFileName = Path.Combine(Path.GetDirectoryName(sourceFileName),
                                                          Path.GetFileNameWithoutExtension(sourceFileName) + "." + conversionSettings.Format);
                using (FileStream fs = File.Create(destinationFileName))
                {
                    fs.Write(convFile, 0, convFile.Length);
                    fs.Close();
                }

                Console.WriteLine("File converted to " + destinationFileName);
            }
            catch (FaultException <WebServiceFaultException> ex)
            {
                Console.WriteLine("FaultException occurred: ExceptionType: " +
                                  ex.Detail.ExceptionType.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                CloseService(client);
            }
        }
        public void GenerateAndUploadPdFtoSharePoint(string relativeUrl, string patientId, ConsentType consentFormType, string location)
        {
            DocumentConverterServiceClient client = null;
            try
            {
                // creating the folder if it is not exits in the drive.
                var folderPath = GetPdFFolderPath(consentFormType);

                if (!string.IsNullOrEmpty(folderPath))
                {
                    byte[] sourceFile = null;
                    client = OpenService("http://localhost:41734/Muhimbi.DocumentConverter.WebService/");
                    var openOptions = new OpenOptions
                                          {
                                              UserName = "",
                                              Password = "",
                                              OriginalFileName = relativeUrl,
                                              FileExtension = "html",
                                              AllowMacros = MacroSecurityOption.All
                                          };

                    // ** Set the various conversion settings
                    var conversionSettings = new ConversionSettings
                                                 {
                                                     Fidelity = ConversionFidelities.Full,
                                                     PDFProfile = PDFProfile.PDF_1_5,
                                                     Quality = ConversionQuality.OptimizeForOnScreen
                                                 };

                    // ** Carry out the actual conversion
                    byte[] convertedFile = client.Convert(sourceFile, openOptions, conversionSettings);

                    var patientDetails = GetPatientDetail(patientId, consentFormType.ToString(), location);

                    string fileName = consentFormType + patientDetails.MRHash + patientDetails.name +
                                      DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";

                    switch (consentFormType)
                    {
                        case ConsentType.Surgical:
                            {
                                fileName = "SUR_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.BloodConsentOrRefusal:
                            {
                                fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.Cardiovascular:
                            {
                                fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.Endoscopy:
                            {
                                fileName = "ENDO_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.OutsideOR:
                            {
                                fileName = "OUTSDE_OR_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.PICC:
                            {
                                fileName = "PICC_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                        case ConsentType.PlasmanApheresis:
                            {
                                fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash +
                                           DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                break;
                            }
                    }

                    if (!new Uri(folderPath).IsUnc)
                    {
                        CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "Generating in local folder");
                        if (!Directory.Exists(folderPath))
                            Directory.CreateDirectory(folderPath);
                        fileName = Path.Combine(folderPath, fileName);
                        File.WriteAllBytes(fileName, convertedFile);
                    }
                    else
                    {
                        var credentials = GetPdFPathCredentials();
                        if (credentials != null)
                        {
                            using (var unc = new UNCAccessWithCredentials())
                            {
                                unc.NetUseDelete();
                                if (unc.NetUseWithCredentials(folderPath, credentials.Username.Trim(), credentials.Domain.Trim(),
                                                              credentials.Password.Trim()))
                                {
                                    if (!Directory.Exists(folderPath))
                                        Directory.CreateDirectory(folderPath);
                                    fileName = Path.Combine(folderPath, fileName);
                                    File.WriteAllBytes(fileName, convertedFile);
                                }
                                else
                                {
                                    CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint",
                                      "Not able to connect the UNC path with the given credentials using [" + folderPath + "],[" + credentials.Domain.Trim() + "],[" + credentials.Username.Trim() + "],[" + credentials.Password.Trim() + "]");
                                }
                            }
                        }
                        else
                        {
                            CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint",
                                      "The export credentials not found.");
                        }
                    }
                    /*

                    //try
                    //{
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (var site = new SPSite(SiteUrl))
                        {
                            using (var web = site.OpenWeb())
                            {
                                web.AllowUnsafeUpdates = true;

                                var list = web.Lists.TryGetList(DocumentLibary);
                                if (list != null)
                                {
                                    var libFolder = list.RootFolder;

                                    var patientDetails = GetPatientDetail(PatientId, ConsentFormType.ToString());

                                    if (patientDetails != null)
                                    {
                                        string fileName = ConsentFormType + patientDetails.MRHash + patientDetails.name + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                        switch (ConsentFormType)
                                        {
                                            case ConsentType.Surgical:
                                                {
                                                    fileName = "SUR_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.BloodConsentOrRefusal:
                                                {
                                                    fileName = "BLOOD_FEFUSAL_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.Cardiovascular:
                                                {
                                                    fileName = "CARDIAC_CATH_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.Endoscopy:
                                                {
                                                    fileName = "ENDO_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.OutsideOR:
                                                {
                                                    fileName = "OUTSDE_OR_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.PICC:
                                                {
                                                    fileName = "PICC_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                            case ConsentType.PlasmanApheresis:
                                                {
                                                    fileName = "PLASMA_APHERESIS_CONSENT_" + patientDetails.MRHash + DateTime.Now.ToString("MMddyyyyHHmmss") + ".pdf";
                                                    break;
                                                }
                                        }

                                        if (libFolder.RequiresCheckout) { try { SPFile fileOld = libFolder.Files[fileName]; fileOld.CheckOut(); } catch { } }
                                        var spFileProperty = new Hashtable();
                                        spFileProperty.Add("MR#", patientDetails.MRHash);
                                        spFileProperty.Add("Patient#", PatientId);
                                        spFileProperty.Add("Patient Name", patientDetails.name);
                                        spFileProperty.Add("DOB#", Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(patientDetails.DOB));
                                        spFileProperty.Add("Procedure Type", patientDetails.ProcedureName);
                                        spFileProperty.Add("Patient Information", patientDetails.name + " " + DateTime.Now.ToShortDateString());

                                        SPFile spfile = libFolder.Files.Add(fileName, convertedFile, spFileProperty, true);

                                        list.Update();

                                        if (libFolder.RequiresCheckout)
                                        {
                                            spfile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
                                            spfile.Publish("Publish Comment");
                                        }
                                    }
                                }

                                web.AllowUnsafeUpdates = false;
                            }
                        }
                    });
                     */
                }
                else
                {
                    CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", "The folder path not found.");
                }
            }
            catch (Exception ex)
            {
                CreateLog("unKnown", LogType.E, "GenerateAndUploadPdFtoSharePoint", ex.Message + "," + ex.StackTrace);
            }
            finally
            {
                CloseService(client);
            }
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            DocumentConverterServiceClient client = null;

            try
            {
                // ** Determine the source file and read it into a byte array.
                string sourceFileName = null;
                if (args.Length == 0)
                {
                    //** Delete any split files from a previous test run.
                    foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory(), "spf-*.pdf"))
                    {
                        File.Delete(file);
                    }

                    // ** If nothing is specified then read the first PDF file from the current folder.
                    string[] sourceFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pdf");
                    if (sourceFiles.Length > 0)
                    {
                        sourceFileName = sourceFiles[0];
                    }
                    else
                    {
                        Console.WriteLine("Please specify a document to split.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    sourceFileName = args[0];
                }

                byte[] sourceFile = File.ReadAllBytes(sourceFileName);

                // ** Open the service and configure the bindings
                client = OpenService(SERVICE_URL);

                //** Set the absolute minimum open options
                OpenOptions openOptions = new OpenOptions();
                openOptions.OriginalFileName = Path.GetFileName(sourceFileName);
                openOptions.FileExtension    = "pdf";

                // ** Set the absolute minimum conversion settings.
                ConversionSettings conversionSettings = new ConversionSettings();

                // ** Create the ProcessingOptions for the splitting task.
                ProcessingOptions processingOptions = new ProcessingOptions()
                {
                    MergeSettings = null,
                    SplitOptions  = new FileSplitOptions()
                    {
                        FileNameTemplate = "spf-{0:D3}",
                        FileSplitType    = FileSplitType.ByNumberOfPages,
                        BatchSize        = 5,
                        BookmarkLevel    = 0
                    },
                    SourceFiles = new SourceFile[1]
                    {
                        new SourceFile()
                        {
                            MergeSettings      = null,
                            OpenOptions        = openOptions,
                            ConversionSettings = conversionSettings,
                            File = sourceFile
                        }
                    }
                };

                // ** Carry out the splittng.
                Console.WriteLine("Splitting file " + sourceFileName);
                BatchResults batchResults = client.ProcessBatch(processingOptions);

                // ** Process the returned files
                foreach (BatchResult result in batchResults.Results)
                {
                    Console.WriteLine("Writing split file " + result.FileName);
                    File.WriteAllBytes(result.FileName, result.File);
                }

                Console.WriteLine("Finished.");
            }
            catch (FaultException <WebServiceFaultException> ex)
            {
                Console.WriteLine("FaultException occurred: ExceptionType: " +
                                  ex.Detail.ExceptionType.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                CloseService(client);
            }
            Console.ReadKey();
        }
Ejemplo n.º 31
0
Archivo: Program.cs Proyecto: iOgre/T9
        public static async Task Main(string[] args)
        {
            if (args == null)
            {
                Help();
                return;
            }


            var inputFileIndex  = Array.IndexOf(args, "-i") + 1;
            var outputFileIndex = Array.IndexOf(args, "-o") + 1;

            if (inputFileIndex == 0 || outputFileIndex == 0)
            {
                Help();
                return;
            }
            var inputFile = new FileInfo(args[inputFileIndex]);

            if (!inputFile.Exists)
            {
                Console.WriteLine($"Input file not found on path {inputFile.FullName}");
                return;
            }
            var  outputFile = new FileInfo(args[outputFileIndex]);
            bool overwrite  = Array.IndexOf(args, "/overwrite") != -1;

            if (outputFile.Exists && !overwrite)
            {
                Console.WriteLine($"Output file already exists on path {outputFile.FullName}");
                Console.WriteLine("Use /overwrite switch if you want to overwrite existing file");
                return;
            }
            ConversionSettings cs = ConversionSettings.Default;

            if (args.Any(t => t == "/lowercase"))
            {
                cs = cs | ConversionSettings.LowercaseAll;
            }

            if (args.Any(t => t == "/strict"))
            {
                cs = cs | ConversionSettings.FailOnUnconvertable;
            }
            var  parser  = new ParseT9(cs);
            bool success = true;

            try
            {
                using (var stream = inputFile.OpenText())
                {
                    Console.WriteLine($"Conversion started at {DateTime.Now.ToLongTimeString()}");
                    using (var writer = new StreamWriter(outputFile.FullName))
                    {
                        string currentString;
                        int    step = 0;
                        while ((currentString = await stream.ReadLineAsync()) != null)
                        {
                            // first line (step == 0) is number of test cases
                            if (step > 0)
                            {
                                var parsed = parser.Parse(currentString);
                                var output = $"Case #{step}: {parsed}";

                                await writer.WriteLineAsync(output);
                            }

                            step++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                _log.Error($"Exception occured during conversion");
                _log.Error($"{ex.Message}");
                _log.Error($"{ex.StackTrace}");
            }
            finally
            {
                if (success)
                {
                    Console.WriteLine($"Conversion ended at {DateTime.Now.ToLongTimeString()}");
                }
                else
                {
                    Console.WriteLine($"Conversion failed at {DateTime.Now.ToLongTimeString()}");
                    Console.WriteLine("Check logfile for detailed information");
                }
            }
        }
        public async Task <HttpResponseMessage> Post(CancellationToken cancellationToken, [FromBody] ConversionSettings settings)
        {
            var authorization = this.HttpContext.Request.Headers["Authorization"].ToString();
            HttpResponseMessage returnMessage = new HttpResponseMessage();

            try
            {
                _queue.Aborted = false;


                if (settings.DestinationEngine.ToLower() == "mysql")
                {
                    settings.DestinationEngine = "MySql";
                    settings.DestinationSchema = null;
                }

                if (settings.SourceEngine.ToLower() == "mysql")
                {
                    settings.SourceEngine = "MySql";
                    settings.SourceSchema = null;
                }

                _queue.QueueBackgroundWorkItem(async token =>
                {
                    await Task.Run(() =>
                    {
                        try
                        {
                            WriteLog(authorization, Status.Started, string.Empty, 0);
                            _queue.State = "Running";

                            var conversion = new ConversionController(_queue, settings, _configuration, _logHub, authorization);
                            conversion.Start();

                            _queue.State = "Idle";
                            WriteLog(authorization, Status.Finished, string.Empty, 100);
                        }
                        catch (Exception e)
                        {
                            WriteLog(authorization, Status.Failed, e.Message, 100);
                        }
                    });
                });
            }
            catch (Exception ex)
            {
                WriteLog(authorization, Status.Failed, ex.Message, 100);
            }

            //WriteLog("conversion done");
            return(await Task.FromResult(returnMessage));
        }