Esempio n. 1
0
        private void CreateMasterForms(RasterImage Image, string masterformsdirectory, string masterformsname, string folderName)
        {
            try
            {
                IMasterFormsCategory parentCategory = null;
                string      _masterformsdirectory   = masterformsdirectory;
                string      _masterformsname        = masterformsname;
                RasterImage _masterformsimage       = Image;
                //nothing selected, add it to root category
                RasterCodecs rasterCodecs = StartUpRasterCodecs();
                DiskMasterFormsRepository workingRepository = new DiskMasterFormsRepository(rasterCodecs, _masterformsdirectory);
                //BuildMasterFormList(workingRepository.RootCategory, _tvMasterForms.Nodes, true);
                parentCategory = workingRepository.RootCategory;
                //parentCategoryNode = _tvMasterForms.Nodes[0];
                //Add master form to repository and tree view
                IMasterForm newForm = parentCategory.AddMasterForm(CreateMasterForm(_masterformsname), null, (RasterImage)null);

                if (_masterformsimage != null)
                {
                    AddMasterFormPages(_masterformsimage, newForm as DiskMasterForm, folderName);
                }
            }
            catch (Exception exp)
            {
                //Messager.ShowError(this, exp);
            }
        }
Esempio n. 2
0
        private bool IsFormsNameValid()
        {
            IMasterFormsCategory parentCategory = null;

            DiskMasterFormsRepository workingRepository = new DiskMasterFormsRepository(new RasterCodecs(), _txtMasterFormsDirectory.Text);

            parentCategory = workingRepository.RootCategory;

            //Build array of current form names
            string[] existingForms = new string[parentCategory.MasterForms.Count];
            for (int i = 0; i < parentCategory.MasterForms.Count; i++)
            {
                existingForms[i] = parentCategory.MasterForms[i].Name;
            }

            foreach (string existingForm in existingForms)
            {
                if (existingForm.ToUpper() == _txtMasterFormsName.Text.Trim().ToUpper())
                {
                    MessageBox.Show("That Master Forms already exist", "Error");
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 3
0
        public HttpResponseMessage CreateFiles(FormDataCollection Form)
        {
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Some problem in create master form set.");

            try
            {
                if (Form != null)
                {
                    string FileName     = Form["FileName"]?.ToString().Trim() ?? "";
                    string folderName   = Form["FolderName"]?.ToString().Trim() ?? "";
                    string FriendlyName = Form["FriendlyName"]?.ToString().Trim() ?? "";

                    string workingDirectory = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/" + FriendlyName);
                    string tempDirectory    = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/temp");
                    string filePath         = tempDirectory + @"\" + FileName;

                    if (Directory.Exists(workingDirectory) && Directory.Exists(tempDirectory) && File.Exists(filePath))
                    {
                        ServiceHelper.SetLicense();
                        RasterImage scannedImage = null;
                        using (RasterCodecs _codecs = new RasterCodecs())
                        {
                            //scannedImage = _codecs.Load(filePath);

                            CodecsImageInfo info           = _codecs.GetInformation(filePath, true);
                            int             infoTotalPages = info.TotalPages;
                            scannedImage = _codecs.Load(filePath, 0, CodecsLoadByteOrder.BgrOrGray, 1, info.TotalPages);
                            DirectoryInfo directoryInfo = new DirectoryInfo(workingDirectory);
                            if (directoryInfo.GetFiles("*").ToList().Count == 0)
                            {
                                CreateMasterForms(scannedImage, workingDirectory, FriendlyName, folderName);
                                File.Delete(filePath);
                                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Master form created successfully.");
                            }
                            else
                            {
                                workingRepository = new DiskMasterFormsRepository(_codecs, workingDirectory);
                                var diskMasterForm = workingRepository?.RootCategory?.MasterForms?.FirstOrDefault();
                                if (diskMasterForm != null)
                                {
                                    AddMasterFormPages(scannedImage, (DiskMasterForm)diskMasterForm, folderName);
                                }
                                File.Delete(filePath);
                                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Page added to master form set successfully.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Some problem in create master form set." + ex.Message.ToString());
            }
            return(httpResponseMessage);
        }
        private bool TryCreateRepository(string masterPath)
        {
            try
            {
                workingRepository = new DiskMasterFormsRepository(rasterCodecs, masterPath);

                MasterFormsLoaded = GetMasterFormCount(workingRepository.RootCategory);
            }
            catch (Exception ex)
            {
                //  log.Error(ex, "Error occurs during master forms loading.");
                return(false);
            }

            //  log.Info($"{MasterFormsLoaded} master forms loaded.");
            return(true);
        }
Esempio n. 5
0
        public HttpResponseMessage DeletePage(FormDataCollection Form)
        {
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Some problem in delete master form page.");

            if (Form != null)
            {
                string PageNumber = Form["PageNumber"]?.ToString().Trim() ?? "";
                string FolderName = Form["FolderName"]?.ToString().Trim() ?? "";
                string result     = DBHelper.GetFileFriendlyName(FolderName);

                string workingDirectory = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/" + result);
                if (Directory.Exists(workingDirectory))
                {
                    using (RasterCodecs _codecs = new RasterCodecs())
                    {
                        RasterDefaults.DitheringMethod = RasterDitheringMethod.None;
                        ServiceHelper.SetLicense();

                        workingRepository = new DiskMasterFormsRepository(_codecs, workingDirectory);
                        var masterForm = workingRepository?.RootCategory?.MasterForms?.FirstOrDefault();
                        if (masterForm != null)
                        {
                            DiskMasterForm            currentMasterForm = (DiskMasterForm)masterForm;
                            FormRecognitionAttributes attributes        = currentMasterForm.ReadAttributes();

                            int currentPageIdx = Convert.ToInt32(PageNumber);

                            FormPages   formPages = currentMasterForm.ReadFields();
                            RasterImage formImage = currentMasterForm.ReadForm();

                            //Delete page from master form attaributes
                            DeletePageFromMasterForm(currentPageIdx + 1, attributes); //page number here is 1 based
                                                                                      //Delete fields page
                            formPages.RemoveAt(currentPageIdx);
                            //Delete the page from the image
                            if (formImage.PageCount == 1)
                            {
                                formImage = null; //You cannot remove the only page from a rasterimage, an exception will occur
                            }
                            else
                            {
                                formImage.RemovePageAt(currentPageIdx + 1);
                            }

                            //We need to recreate the FormPages to ensure the page numbers are updated correctly
                            for (int i = 0; i < formPages.Count; i++)
                            {
                                FormPage currentPage = formPages[i];
                                FormPage newPage     = new FormPage(i + 1, currentPage.DpiX, currentPage.DpiY);
                                newPage.AddRange(currentPage.GetRange(0, currentPage.Count));
                                formPages[i] = newPage;
                            }
                            //Write the updated masterform to disk. Delete it first just in case the entire image was deleted
                            DiskMasterFormsCategory parentCategory = (workingRepository.RootCategory) as DiskMasterFormsCategory;
                            parentCategory.DeleteMasterForm(currentMasterForm);
                            parentCategory.AddMasterForm(attributes, formPages, formImage);
                            httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, "Page deleted from master set sucessfully.");
                            DBHelper.UpdateTifPageCount(formPages.Count.ToString(), FolderName);
                        }
                    }
                }
            }
            return(httpResponseMessage);
        }
        public List <string> ProcessFilesMultiThread(string FileOrDir)
        {
            //============================
            // root path
            string rootPath = Path.Combine("C:\\", "Lateetud");

            if (!Directory.Exists(rootPath))
            {
                Directory.CreateDirectory(rootPath);
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.License)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.License));
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRInput)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRInput));
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets));
            }
            //============================

            //============================
            // set the license
            RasterSupport.SetLicense(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic"),
                                     File.ReadAllText(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic.key")));

            // Ocr Engine started
            IOcrEngine    TheOcrEngine = null;
            OcrEngineType engineType;

            if (!Enum.TryParse("LEAD", true, out engineType))
            {
                return(null);
            }
            if (engineType == OcrEngineType.LEAD)
            {
                TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true);
                TheOcrEngine.Startup(null, null, null, null);

                TheOcrEngine.SettingManager.SetEnumValue("Recognition.Fonts.DetectFontStyles", 0);
                TheOcrEngine.SettingManager.SetBooleanValue("Recognition.Fonts.RecognizeFontAttributes", false);
                if (TheOcrEngine.SettingManager.IsSettingNameSupported("Recognition.RecognitionModuleTradeoff"))
                {
                    TheOcrEngine.SettingManager.SetEnumValue("Recognition.RecognitionModuleTradeoff", "Accurate");
                }
            }
            else
            {
                TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true);
                TheOcrEngine.Startup(null, null, null, null);
            }

            // initialize RasterCodecs instance
            RasterCodecs _RasterCodecs = new RasterCodecs();

            // initialize DiskMasterFormsRepository instance
            DiskMasterFormsRepository _DiskMasterFormsRepository = new DiskMasterFormsRepository(_RasterCodecs, Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets));

            var managers = AutoFormsRecognitionManager.Ocr | AutoFormsRecognitionManager.Default;
            // initialize AutoFormsEngine instance
            AutoFormsEngine _AutoFormsEngine = new AutoFormsEngine(_DiskMasterFormsRepository, TheOcrEngine, null, managers, 30, 80, false)
            {
                UseThreadPool = TheOcrEngine != null && TheOcrEngine.EngineType == OcrEngineType.LEAD
            };

            //============================

            // files to be processed
            string[] _files    = GetFiles(Path.Combine(rootPath, TheVarSubDir.OCRInput), FileOrDir);
            int      fileCount = _files.Length;

            List <string> _FileResults = new List <string>();

            // Event to notify us when all work is finished
            using (AutoResetEvent finishedEvent = new AutoResetEvent(false))
            {
                // Loop through all Files in the given Folder
                foreach (string _file in _files)
                {
                    string _FileResult = null;

                    // Process it in a thread
                    ThreadPool.QueueUserWorkItem((state) =>
                    {
                        try
                        {
                            // Process it
                            //var _result = _AutoFormsEngine.Run(_file, null).RecognitionResult;    // geting error with this statement


                            var imageInfo   = _RasterCodecs.GetInformation(_file, true);
                            var targetImage = _RasterCodecs.Load(_file, 0, CodecsLoadByteOrder.Bgr, 1, imageInfo.TotalPages);
                            targetImage.ChangeViewPerspective(RasterViewPerspective.TopLeft);
                            var _result = _AutoFormsEngine.Run(targetImage, null, targetImage, null).RecognitionResult;
                            if (_result == null)
                            {
                                _FileResult = "Not Recognized";
                            }
                            else
                            {
                                _FileResult = "Successfully Recognized";
                            }
                        }
                        catch (Exception ex)
                        {
                            _FileResult = "Not Recognized - " + ex.Message;
                        }
                        finally
                        {
                            _FileResults.Add(_FileResult);
                            if (Interlocked.Decrement(ref fileCount) == 0)
                            {
                                // We are done, inform the main thread
                                finishedEvent.Set();
                            }
                        }
                    });
                }

                // Wait till all operations are finished
                finishedEvent.WaitOne();
            }

            _AutoFormsEngine.Dispose();
            _RasterCodecs.Dispose();
            if (TheOcrEngine != null && TheOcrEngine.IsStarted)
            {
                TheOcrEngine.Shutdown();
            }

            return(_FileResults);
        }
Esempio n. 7
0
        private void UpdateData()
        {
            var recognitionEngineVersion = FormRecognitionEngine.Version;

#if FOR_DOTNET4
            var originalFullTextSearchManager = recognitionEngine.FullTextSearchManager;
#endif

            try
            {
                if (!Directory.Exists(_txtSrcFolder.Text))
                {
                    Invoke((MethodInvoker) delegate { Messager.Show(this, "Please select valid folder", MessageBoxIcon.Error, MessageBoxButtons.OK); });
                    return;
                }

                // Set the data version to latest, we want to update the data to use the latest
                FormRecognitionEngine.Version = FormRecognitionEngine.LatestVersion;

                // Set the full text search engine
                DiskMasterFormsRepository workingRepository = new DiskMasterFormsRepository(_codecs, _txtSrcFolder.Text);

#if FOR_DOTNET4
                if (_cbUseFullTextSearch.Checked)
                {
                    DiskFullTextSearchManager fullTextSearchManager = new DiskFullTextSearchManager();
                    fullTextSearchManager.IndexDirectory    = Path.Combine(workingRepository.Path, "index");
                    recognitionEngine.FullTextSearchManager = fullTextSearchManager;
                }
#endif
                IMasterFormsCategory parentCategory = workingRepository.RootCategory;
                Invoke((MethodInvoker) delegate { _prgbar.Maximum = parentCategory.MasterForms.Count; });

                for (int i = 0; i < _prgbar.Maximum; i++)
                {
                    if (!_isRunning)
                    {
                        return;
                    }

                    Invoke((MethodInvoker) delegate { _prgbar.Value++; });

                    //Get the Original Attributes
                    DiskMasterForm            originalMasterForm = parentCategory.MasterForms[i] as DiskMasterForm;
                    FormRecognitionAttributes originalAttributes = originalMasterForm.ReadAttributes();
                    recognitionEngine.OpenMasterForm(originalAttributes);
                    recognitionEngine.CloseMasterForm(originalAttributes);

                    FormRecognitionOptions    options    = new FormRecognitionOptions();
                    FormRecognitionAttributes attributes = recognitionEngine.CreateMasterForm(parentCategory.MasterForms[i].Name, new Guid(), options);
                    recognitionEngine.CloseMasterForm(attributes);

                    IMasterForm newForm = parentCategory.AddMasterForm(attributes, null, (RasterImage)null);

                    DiskMasterForm currentMasterForm = parentCategory.MasterForms[i] as DiskMasterForm;
                    attributes = currentMasterForm.ReadAttributes();
                    FormPages   formPages = currentMasterForm.ReadFields();
                    RasterImage formImage = currentMasterForm.ReadForm();

                    for (int j = 0; j < formImage.PageCount; j++)
                    {
                        //Get the Page Recognition Options for the original Attributes
                        PageRecognitionOptions pageOptions = GetPageOptions(j, originalAttributes);

                        //Add each new page to the masterform by creating attributes for each page
                        formImage.Page = j + 1;
                        recognitionEngine.OpenMasterForm(attributes);
                        recognitionEngine.DeleteMasterFormPage(attributes, j + 1);
                        recognitionEngine.InsertMasterFormPage(j + 1, attributes, formImage.Clone(), pageOptions, null);
#if FOR_DOTNET4
                        if (_cbUseFullTextSearch.Checked)
                        {
                            recognitionEngine.UpsertMasterFormToFullTextSearch(attributes, "index", null, null, null, null);
                        }
#endif

                        recognitionEngine.CloseMasterForm(attributes);
                    }

                    FormProcessingEngine tempProcessingEngine = new FormProcessingEngine();
                    tempProcessingEngine.OcrEngine     = ocrEngine;
                    tempProcessingEngine.BarcodeEngine = barcodeEngine;

                    for (int j = 0; j < recognitionEngine.GetFormProperties(attributes).Pages; j++)
                    {
                        tempProcessingEngine.Pages.Add(new FormPage(j + 1, formImage.XResolution, formImage.YResolution));
                    }

                    formPages = tempProcessingEngine.Pages;
                    currentMasterForm.WriteAttributes(attributes);

                    currentMasterForm.WriteFields(parentCategory.MasterForms[i].ReadFields());
                }
#if FOR_DOTNET4
                if (recognitionEngine.FullTextSearchManager != null)
                {
                    recognitionEngine.FullTextSearchManager.Index();
                }
#endif
                System.Diagnostics.Process.Start(_txtSrcFolder.Text);
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker) delegate { Messager.Show(this, ex, MessageBoxIcon.Error); });
            }
            finally
            {
                // Restore the original version
                FormRecognitionEngine.Version = recognitionEngineVersion;
#if FOR_DOTNET4
                recognitionEngine.FullTextSearchManager = originalFullTextSearchManager;
#endif
                _isRunning = false;
                Invoke((MethodInvoker) delegate
                {
                    _prgbar.Value = 0;
                    UpdateControls();
                });
            }
        }
Esempio n. 8
0
        public bool SaveXml([FromBody] XmlElement data, [FromUri] string FolderName)
        {
            try
            {
                #region Added by Prasanta, For saving XML in physical folder
                string strLogicalFolderName  = string.Empty;
                string strPhysicalFolderName = string.Empty;

                int start = FolderName.IndexOf("[[") + 2;
                int end   = FolderName.IndexOf("]]", start);
                strPhysicalFolderName = FolderName.Substring(start, end - start);
                strLogicalFolderName  = FolderName.Substring(0, FolderName.IndexOf("[["));
                #endregion

                //if (string.IsNullOrEmpty(Data))
                if (data == null)
                {
                    throw new ArgumentNullException("data");
                }

                // get an element from the string
                var    element  = data;
                string filePath = "";
                if (string.IsNullOrEmpty(FolderName))
                {
                    return(true);
                }
                //filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"MasterForm\Annotation\" + FolderName + ".xml");//commented By Prasanta
                filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"MasterForm\Annotation\" + strLogicalFolderName + ".xml");

                // Save the data
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent             = true;
                settings.OmitXmlDeclaration = false;
                settings.Encoding           = Encoding.UTF8;

                using (XmlWriter writer = XmlWriter.Create(filePath, settings))
                {
                    writer.WriteStartDocument();
                    element.WriteTo(writer);
                    writer.WriteEndDocument();
                }

                //string workingDirectory = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/" + FolderName);//Commented by Prasanta
                //string workingFile = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/Annotation/" + FolderName + ".xml");//Commented by Prasanta
                string workingDirectory = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/" + strPhysicalFolderName);
                string workingFile      = HttpContext.Current.Server.MapPath("~/" + RootFolderName + "/Annotation/" + strLogicalFolderName + ".xml");
                if (Directory.Exists(workingDirectory) && File.Exists(workingFile))
                {
                    using (RasterCodecs _codecs = new RasterCodecs())
                    {
                        RasterDefaults.DitheringMethod = RasterDitheringMethod.None;
                        ServiceHelper.SetLicense();
                        workingRepository = new DiskMasterFormsRepository(_codecs, workingDirectory);
                        var masterForm = workingRepository?.RootCategory?.MasterForms?.FirstOrDefault();


                        if (masterForm != null)
                        {
                            DiskMasterForm currentMasterForm = (DiskMasterForm)masterForm;
                            bool           result            = AddField(currentMasterForm, GetPoints(workingFile));
                        }
                    }
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }