Example #1
0
        private async void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_currentSettings.IsValid())
            {
                _showError("All settings are required");
                return;
            }

            try
            {
                ConversionEngine.AddJobs(ConversionJob.Create(SourceTextBox.Text, OutputTextBox.Text, _currentSettings));
                ConversionEngine.CreateScriptFile();
                ProgressBar.IsIndeterminate = true;
                var startTime = DateTime.Now;
                await ConversionEngine.Run();

                var endTime = DateTime.Now;
                ProgressBar.IsIndeterminate = false;
                System.Windows.MessageBox.Show($"Conversion job started at {startTime.ToString()}{Environment.NewLine}Finished at {endTime.ToString()}", "Conversion finished", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _showError(ex.Message + Environment.NewLine + ex.ParamName);
            }
            catch (DirectoryNotFoundException ex)
            {
                _showError(ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                _showError(ex.Message + Environment.NewLine + ex.FileName);
            }
        }
 private void runButton_Click(object sender, EventArgs e)
 {
     outbox.Text = ConversionEngine.Run(
         inbox.Text,
         inputFormatSelector.DataFormat,
         outputFormatSelector.DataFormat,
         operationSelector.Operation);
 }
Example #3
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Conversion/ConvertToDocument")] HttpRequestMessage req, TraceWriter log, ExecutionContext context)
        {
            try
            {
                if (!DemoConfiguration.UnlockSupport(log))
                {
                    return(GenerateErrorMessage(ApiError.LicenseNotSet, req));
                }

                var leadParameterObject = ParseLeadWebRequestParameters(req);
                if (!leadParameterObject.Successful)
                {
                    return(GenerateErrorMessage(ApiError.InvalidRequest, req));
                }

                var convertToDocuemntParameterObject = ParseConvertToDocumentParameters(req);
                if (!convertToDocuemntParameterObject.Successful)
                {
                    return(GenerateErrorMessage(ApiError.InvalidRequest, req));
                }

                var imageReturn = await GetImageStreamAsync(leadParameterObject.LeadWebRequest.fileUrl, req, DemoConfiguration.MaxUrlMbs);

                if (!imageReturn.Successful)
                {
                    return(GenerateErrorMessage(imageReturn.ErrorType.Value, req));
                }

                using (imageReturn.Stream)
                {
                    LoadDocumentOptions options = new LoadDocumentOptions()
                    {
                        FirstPageNumber = leadParameterObject.LeadWebRequest.FirstPage,
                        LastPageNumber  = leadParameterObject.LeadWebRequest.LastPage
                    };

                    ConversionEngine engine = new ConversionEngine
                    {
                        OcrEngine  = GetOcrEngine(),
                        Preprocess = false,
                        UseThreads = false
                    };
                    var filenamelist = engine.Convert(imageReturn.Stream, options, RasterImageFormat.Unknown, convertToDocuemntParameterObject.OutputFormat);

                    var returnRequest = req.CreateResponse(HttpStatusCode.OK);
                    returnRequest.Content = new StringContent(JsonConvert.SerializeObject(filenamelist));
                    return(returnRequest);
                }
            }
            catch (Exception ex)
            {
                log.Error($"API Error occurred for request: {context.InvocationId} \n Details: {JsonConvert.SerializeObject(ex)}");
                return(GenerateErrorMessage(ApiError.InternalServerError, req));
            }
        }
Example #4
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _enableLogging   = Properties.Settings.Default.EnableLogging;
            _scriptsLocation = String.IsNullOrEmpty(Properties.Settings.Default.ScriptsLocation) ? Environment.GetFolderPath(Environment.SpecialFolder.Desktop) : Properties.Settings.Default.ScriptsLocation;

            ExeManager.ScanForInstalls();
            ConversionEngine.StartNew(_scriptsLocation, _enableLogging);
            OriginalSinsRadioButton.IsEnabled = ExeManager.HasExeForEdition(GameEdition.OriginalSins);
            EntrenchmentRadioButton.IsEnabled = ExeManager.HasExeForEdition(GameEdition.Entrenchment);
            DiplomacyRadioButton.IsEnabled    = ExeManager.HasExeForEdition(GameEdition.Diplomacy);
            RebellionRadioButton.IsEnabled    = ExeManager.HasExeForEdition(GameEdition.Rebellion);
        }
Example #5
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();
 }
        public IActionResult ConvertFile(string fileName, string keywordsJSON, string application)
        {
            ResponseEntity respEntity = new ResponseEntity();

            try
            {
                ConversionEngine conversionEngine = new ConversionEngine(cache, settings);
                respEntity = conversionEngine.ConvertDocumentFromFile(fileName, keywordsJSON, application);

                if (respEntity.Success)
                {
                    return(Ok(new
                    {
                        filename = respEntity.FileName,
                        success = true,
                        message = respEntity.Message,
                        documentcontent = respEntity.DocumentContent,
                        parsedcontent = respEntity.ParsedContent,
                        requestid = respEntity.RequestID.ToString(),
                        doformula = respEntity.DoFormula
                    }));
                }
                else
                {
                    //this isn't quite the right response... but for now, ok
                    return(NotFound(new ProblemDetails()
                    {
                        Title = "Not found in ConvertFile Method",
                        Status = (int)HttpStatusCode.NotFound,
                        Detail = "No exception",
                        Type = "/api/problem/general-failure",
                        Instance = HttpContext.Request.Path
                    }));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Could not convert file: {fileName}");

                return(BadRequest(new ProblemDetails()
                {
                    Title = "Error in ConvertFile Method",
                    Status = (int)HttpStatusCode.BadRequest,
                    Detail = ex.Message,
                    Type = "/api/problem/bad-doc-type",
                    Instance = HttpContext.Request.Path
                }));
            }
        }
Example #7
0
        public void GlobalSetup()
        {
            _wpDoc             = WordprocessingDocument.Open(Utils.GetAssetPath("shareholders.docx"), false);
            _paragraphs        = _wpDoc.MainDocumentPart.Document.Body.Elements <Paragraph>().ToArray();
            _shortestParagraph =
                _paragraphs.Where(x => x.InnerText.Length > 0)
                .OrderBy(x => x.InnerText.Length)
                .Take(1)
                .ToArray();
            _longestParagraph =
                _paragraphs.Where(x => x.InnerText.Length > 0)
                .OrderByDescending(x => x.InnerText.Length)
                .Take(1)
                .ToArray();

            Console.WriteLine($"Total: {_paragraphs.Length}, shortest char: ${_shortestParagraph[0].InnerText.Length}, longest char: {_longestParagraph[0].InnerText.Length}");

            _conversionEngine = BuildConversionEngine();
        }
Example #8
0
        public async Task <HttpResponseMessage> ConvertToDocument([FromUri] DocumentConversionWebRequest request)
        {
            try
            {
                AuthenticateRequest();

                if (!VerifyCommonParameters(request))
                {
                    throw new Exception();
                }

                using (var stream = await GetImageStream(request.fileUrl))
                {
                    int lastPage = request.LastPage;
                    ValidateFile(stream, ref lastPage);
                    ConversionEngine conversion = new ConversionEngine()
                    {
                        WorkingDirectory = DemoConfiguration.OutputFileDirectory,
                        OcrEngine        = ocrEngine
                    };

                    LoadDocumentOptions options = new LoadDocumentOptions()
                    {
                        FirstPageNumber = request.FirstPage,
                        LastPageNumber  = lastPage
                    };

                    var fileNameList = conversion.Convert(stream, options, Leadtools.RasterImageFormat.Unknown, request.Format);
                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(JsonConvert.SerializeObject(fileNameList))
                    });
                }
            }
            catch (Exception e)
            {
                return(GenerateExceptionMessage(e));
            }
        }
        public IActionResult ConvertAndSearch(string keywordsFile, string application, string fileType)
        {
            ResponseEntity respEntity = new ResponseEntity();

            try
            {
                ConversionEngine conversionEngine = new ConversionEngine(cache, settings);

                int ibyteLength = (int)Request.ContentLength.GetValueOrDefault();

                byte[] bytes = new byte[ibyteLength];

                Request.Body.ReadAsync(bytes, 0, ibyteLength);

                string keywordsJSON = "keywords.json";

                if (!string.IsNullOrEmpty(keywordsFile))
                {
                    keywordsJSON = System.IO.File.ReadAllText($"{settings.KeywordsFolder}{keywordsFile}");
                }

                respEntity = conversionEngine.ConvertDocumentFromBytes(bytes, keywordsJSON, application, fileType);

                if (respEntity.Success)
                {
                    return(Ok(new
                    {
                        filename = respEntity.FileName,
                        success = true,
                        message = respEntity.Message,
                        documentcontent = respEntity.DocumentContent,
                        parsedcontent = respEntity.ParsedContent,
                        requestid = respEntity.RequestID.ToString(),
                        doformula = respEntity.DoFormula
                    }));
                }
                else
                {
                    return(BadRequest(new ProblemDetails()
                    {
                        Title = "Error in ConvertAndSearch Method",
                        Status = (int)HttpStatusCode.BadRequest,
                        Detail = "Could not convert byte array",
                        Type = "/api/problem/bad-doc-type",
                        Instance = HttpContext.Request.Path
                    }));
                }
            }
            catch (Exception ex)
            {
                var responseObject = new ProblemDetails()
                {
                    Title    = "Error in ConvertAndSearch Method",
                    Status   = (int)HttpStatusCode.BadRequest,
                    Detail   = ex.Message,
                    Type     = "/api/problem/general-failure",
                    Instance = HttpContext.Request.Path
                };

                return(StatusCode(StatusCodes.Status500InternalServerError, responseObject));
            }
        }
Example #10
0
        private async Task <HttpResponseMessage> ExtractBarcodes([FromUri] BarcodeWebRequest request, int barcodeAmount)
        {
            try
            {
                AuthenticateRequest();

                if (!VerifyCommonParameters(request))
                {
                    throw new MalformedRequestException();
                }

                var symbologyList = new List <BarcodeSymbology>();
                if (string.IsNullOrEmpty(request.symbologies))//If no symbology string is passed, default to all symbologies.
                {
                    symbologyList = Enum.GetValues(typeof(BarcodeSymbology)).OfType <BarcodeSymbology>().ToList();
                    symbologyList.Remove(BarcodeSymbology.Unknown);
                }
                else
                {
                    symbologyList = ExtractBarcodeSymbologies(request.symbologies);
                    //If the user did supply a list of symbologies, but they could not be parsed, we will deny the request.
                    if (symbologyList.Count == 0)
                    {
                        throw new MalformedRequestException();
                    }
                }


                using (var stream = await GetImageStream(request.fileUrl))
                {
                    int lastPage = request.LastPage;
                    ValidateFile(stream, ref lastPage);
                    ConversionEngine    conversion = new ConversionEngine();
                    LoadDocumentOptions options    = new LoadDocumentOptions()
                    {
                        FirstPageNumber = request.FirstPage,
                        LastPageNumber  = lastPage
                    };
                    RecognitionEngine recognitionEngine = new RecognitionEngine();
                    BarcodeEngine     barcodeEngine     = new BarcodeEngine();

                    var barcodeList = recognitionEngine.ExtractBarcode(stream, options, barcodeEngine, symbologyList.ToArray(), barcodeAmount, false);
                    List <BarcodeResultData> results = new List <BarcodeResultData>();
                    foreach (var obj in barcodeList)
                    {
                        foreach (var d in obj.BarcodeData)
                        {
                            var result = new BarcodeResultData(obj.PageNumber, d.Symbology.ToString(), d.Value, new Rectangle(d.Bounds.X, d.Bounds.Y, d.Bounds.Width, d.Bounds.Height), d.RotationAngle);;
                            results.Add(result);
                        }
                    }


                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(JsonConvert.SerializeObject(results))
                    });
                }
            }
            catch (Exception e)
            {
                return(GenerateExceptionMessage(e));
            }
        }