public ApiResponse <List <Constant> > GetConstants(GetConstants req)
        {
            var result = null as List <Constant>;

            using (var connection = new SqlConnection(_connectionString.JapaneseLearning))
            {
                var cmd = new SqlCommand(p_Constants_Get, connection)
                {
                    CommandType = CommandType.StoredProcedure
                };

                cmd.Parameters.AddWithValue("@UserID", _requestInfo.UserId);

                cmd.Parameters.Add("@RetVal", SqlDbType.Int).Direction          = ParameterDirection.Output;
                cmd.Parameters.Add("@RetMsg", SqlDbType.VarChar, 500).Direction = ParameterDirection.Output;

                cmd.Parameters.AddWithValue("@ConstantID", req.ConstantId);
                cmd.Parameters.AddWithValue("@ParentID", req.ParentId);
                cmd.Parameters.AddWithValue("@Name", req.Name);
                cmd.Parameters.AddWithValue("@Description", req.Description);
                cmd.Parameters.AddWithValue("@IncludeDisabled", req.IncludeDisabled);

                connection.Open();

                using (var dr = cmd.ExecuteReader())
                {
                    result = new List <Constant>();
                    while (dr.Read())
                    {
                        result.Add(new Constant
                        {
                            ConstantId  = dr["ConstantID"].ToSafeInt32(),
                            ParentId    = dr["ParentID"].ToSafeInt32(),
                            Name        = dr["Name"].ToSafeString(),
                            Description = dr["Description"].ToSafeString(),
                            Disabled    = dr["Disabled"].ToSafeBool(),

                            CreatedId        = dr["CreatedID"].ToSafeInt32(),
                            CreatedBy        = dr["CreatedBy"].ToSafeString(),
                            CreatedDateTime  = dr["CreatedDateTime"].ToSafeDateTime(),
                            ModifiedId       = dr["ModifiedID"].ToSafeInt32(),
                            ModifiedBy       = dr["ModifiedBy"].ToSafeString(),
                            ModifiedDateTime = dr["ModifiedDateTime"].ToSafeDateTime()
                        });
                    }
                }
                return(new ApiResponse <List <Constant> >
                {
                    Content = result,
                    Status = new ReturnStatus(cmd.Parameters["@RetVal"].Value.ToSafeInt32(),
                                              cmd.Parameters["@RetMsg"].Value.ToSafeString())
                });
            }
        }
        public bool MoveFile(string fileName, string target)
        {
            string sourceFile = Path.Combine(GetConstants.Home(), GetConstants.Directory("indir"), fileName);
            string targetFile = Path.Combine(GetConstants.Home(), GetConstants.Directory(target), fileName);

            try
            {
                File.Move(sourceFile, targetFile);
            }
            catch
            { return(false); }
            return(true);
        }
        // GPA ** These need to be improved!
        public bool MoveFile(string fileName, string sourceDir, string targetDir)
        {
            // Need to check that the source file exists, and that target directory is valid.
            string sourceFile = Path.Combine(GetConstants.Home(), sourceDir, fileName);
            string targetFile = Path.Combine(GetConstants.Home(), targetDir, fileName);

            try
            {
                File.Move(sourceFile, targetFile);
            }
            catch
            { return(false); }
            return(true);
//            GetProcessedFromPath(fileName);
        }
        private void CreateTxtFromPDF(string filename)
        {
            //ScanPageStatus scanPageStatus = new ScanPageStatus();

            string tesseractPath = Path.Combine(AssemblyDirectory(), GetConstants.TesseractBinaries());
            string tesseractData = Path.Combine(AssemblyDirectory(), GetConstants.TesseractData());

            try {
                using (OCRProcessor processor = new OCRProcessor(tesseractPath))
                {
                    //Stream pdfStream2 = filename; // FileUpload1.PostedFile.InputStream;

                    // Read in PDF image file, and convert to searchable TXT pdf file
                    PdfLoadedDocument IDoc = new PdfLoadedDocument(filename);
                    processor.Settings.Language    = Languages.English;
                    processor.Settings.Performance = Performance.Slow;
                    // var zz = processor.Settings.Performance;
                    //string tessdata = tesseractPath + @"\\Tessdata\\";
                    processor.PerformOCR(IDoc, tesseractData);
                    string outFileName = Path.GetFileName(filename) + "_OCR" + Path.GetExtension(filename);
                    string homePath    = Path.GetDirectoryName(Path.GetDirectoryName(filename));
                    string savePath    = Path.Combine(homePath, GetConstants.Directory("out"), outFileName);

                    // If file exists - delete it first.
                    if (File.Exists(savePath))
                    {
                        File.SetAttributes(savePath, FileAttributes.Normal);
                        File.Delete(savePath);
                    }

                    IDoc.Save(savePath);
                    IDoc.Close(true);
                    IDoc.Dispose();

                    scanPageStatus.scannedFileName = savePath;
                    scanPageStatus.rc            = 0;
                    scanPageStatus.statusMessage = String.Format("File {0} scanned and saved to {1}", filename, scanPageStatus.scannedFileName);
                }
            }
            catch (Exception ex)
            {
                scanPageStatus.scannedFileName = "";
                scanPageStatus.statusMessage   = String.Format("Error {0} when running OCR on source file {1}", ex, filename);
                scanPageStatus.rc = -1;
            }

            // return scanPageStatus;
        }
        private string IdentifyCompanyAndPage(ref string[] s)
        {
            string[] companyNames = GetConstants.CompanyNames();
            string   companyData  = "";
            int      status       = -1;

            foreach (string company in companyNames)
            {
                KeyTerms keyTerms = new KeyTerms(company);
                status = FindInPage(keyTerms.ForCompanyName(), ref s);
                if (status >= 0)
                {
                    scanPageStatus.companyName = keyTerms.CurrentCompanyName();
                    int _dataPage = FindInPage(keyTerms.PageIdentification(), ref s);
                    //if (scanPageStatus.companyName == "contact") { _dataPage = 0; } // Test
                    if (_dataPage >= 0)
                    {
                        scanPageStatus.pageText = s[_dataPage]; // <<--- dont need to retain this string in the scanPageStatus object, just return it...
                        companyData             = s[_dataPage];
                        if (companyData.Length > 0)
                        {
                            scanPageStatus.rc            = 0;
                            scanPageStatus.statusMessage = String.Format("File {0} scanned and key page identified", scanPageStatus.scannedFileName);
                        }
                        else
                        {
                            scanPageStatus.rc            = 1;
                            scanPageStatus.statusMessage = String.Format("File {0} scanned but key data page empty", scanPageStatus.scannedFileName);
                        }
                    }
                    else
                    {
                        // Unable to find the key page for this company..
                        scanPageStatus.rc            = -1;
                        scanPageStatus.statusMessage = String.Format("Unable to locate key page for {0} bill (source file {1})", scanPageStatus.companyName, scanPageStatus.scannedFileName);
                        scanPageStatus.pageText      = "";
                    }
                    break; // Found company, so no need to continue
                }
            }
            if (status < 0)
            {
                // What if company not found in document .. not a valid file?
                scanPageStatus.rc            = -1;
                scanPageStatus.statusMessage = String.Format("Unable to identify company for source file {1} (source file {2})", scanPageStatus.companyName, scanPageStatus.scannedFileName);
            }
            return(companyData);
        }
        //private string inDir = GetConstants.Directory("indir");
        //private string processedDir = GetConstants.Directory("processed");
        //private string errorDir = GetConstants.Directory("error");
        //private string home = GetConstants.Home();

        //public const string inDir = "in";
        //public const string processedDir = "processed";
        //public const string errorDir = "error";

        public FileStatus CheckNextFile()
        {
            FileStatus fileStatus = new FileStatus();

            //FileProcessor tools = new FileProcessor();
            //string targetPath = Path.Combine(home, inDir);
            string targetPath = Path.Combine(GetConstants.Home(), GetConstants.Directory("indir"));

            if (Directory.Exists(targetPath))
            {
                fileStatus.fileName = GetNextFile(targetPath);
                if (fileStatus.fileName.Length == 0)
                {
                    fileStatus.rc            = 1;
                    fileStatus.statusMessage = String.Format("No more files in source directory {0}", targetPath);
                }
                else
                {
                    fileStatus.rc = CheckFile(fileStatus.fileName);
                    if (fileStatus.rc < 0)
                    {
                        if (MoveFile(Path.GetFileName(fileStatus.fileName), GetConstants.Directory("indir"), GetConstants.Directory("error")))
                        {
                            fileStatus.statusMessage = String.Format("Soure file {0} invalid. Moved to error directory", Path.GetFileName(fileStatus.fileName));
                        }
                        else
                        {
                            fileStatus.statusMessage = String.Format("Soure file {0} invalid; error moving to error directory", Path.GetFileName(fileStatus.fileName));
                        }
                    }
                }
            }
            else
            {
                fileStatus.statusMessage = String.Format("Invalid source directory {0}", targetPath);
                fileStatus.rc            = -10;
            }
            return(fileStatus);
        }
        public ScanPageStatus ReadFile(string filename)
        {
            // Look for file in common location
            // move to in process
            // scan
            // move to processed (archive)

            // Need to have multiple pages available
            ScanPageStatus scanPageStatus = new ScanPageStatus();

            try
            {
                // Database connection via DocumentScanningLibrary, this is intermediate table for data loads
                ScannedRecord scannedRecord = new ScannedRecord();
                // { CompanyName = "test", CustomerNumber = 1, InvoiceNumber = 1 };
                ////var test = db.ScannedRecords.Count();
                ////db.ScannedRecords.InsertOnSubmit(scannedRecord);
                ////db.SubmitChanges();

                if (!String.IsNullOrEmpty(filename))
                {
                    // ScanPDF useses the Tesseract public domain OCR tool set acting in PDF via Syncfusion toolset

                    switch (Path.GetExtension(filename).ToLower())
                    {
                    case ".pdf":
                        ScanPDF scanPDF = new ScanPDF();
                        scanPageStatus = scanPDF.Process(filename, ref scannedRecord);    //ScanPDF.Process(filename);
                        break;

                    case ".jpg":
                    case ".tiff":
                        // Scan Page uses the Accusoft.SmartZoneOCRSdk to process .jpg source files.
                        // Needs to return "scanPageStatus, if used in the future
                        var result = ScanImage.Main(filename);
                        //if (result.ToString().Length > 0) {}
                        break;

                    default:
                        break;
                    }

                    if (scanPageStatus.rc == 0)
                    {
                        // Persist record in the database, note in alert log if there are failed scans


                        if (scannedRecord.FailedMatches == 0)
                        {
                            scanPageStatus.rc            = 0;
                            scanPageStatus.statusMessage = String.Format("File {0} scanned and data persisted to database", filename);
                        }
                        else if (scannedRecord.FailedMatches <= GetConstants.ScanErrorLimit())
                        {
                            scanPageStatus.rc            = 1;
                            scanPageStatus.statusMessage = String.Format("Recorded {0} scan failures for source file {1}", scannedRecord.FailedMatches.ToString(), filename);
                        }
                        else
                        {
                            scanPageStatus.rc            = -1;
                            scanPageStatus.statusMessage = String.Format("Scan failures of {0} too high. No data saved for source file {1}", scannedRecord.FailedMatches.ToString(), filename);
                        }
                        if (scanPageStatus.rc >= 0)
                        {
                            // Persist data to database
                            //var test = scannedRecord.ScannedFileName.
                            scannedRecord.ScannedFileName = Path.GetFileName(filename);
                            scannedRecord.ScanDate        = DateTime.Now; // Will need to ensure this is correct time zone *** GPA
                            db.ScannedRecords.InsertOnSubmit(scannedRecord);
                            db.SubmitChanges();
                        }
                    }
                    //ss.Dispose();
                }
                else
                {
                    scanPageStatus.rc            = 1;
                    scanPageStatus.statusMessage = String.Format("Source file {0} null or empty", filename);
                }
            }
            catch (Exception ex)
            {
                scanPageStatus.rc            = -1;
                scanPageStatus.statusMessage = String.Format("Exception {0} when running OCR on source file {1}", ex, filename);
            }

            return(scanPageStatus);
        }
 public List <Constant> GetConstants(GetConstants req)
 {
     return(null);
 }