static OcrImageInfo ___downloadImage(OcrImageInfo ocr)
        {
            try
            {
                string file = Path.GetFileName(ocr.Url);

                ocr.FileName = file.Substring(0, file.Length - 4) + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".jpg";

                file = Path.Combine(Program.PATH_OCR_IMAGE, ocr.FileName);
                ImageFormat format = ImageFormat.Jpeg;

                WebClient client = new WebClient();
                Stream    stream = client.OpenRead(ocr.Url);
                Bitmap    bitmap = new Bitmap(stream);

                if (bitmap != null)
                {
                    bitmap.Save(file, format);
                }

                stream.Flush();
                stream.Close();
                client.Dispose();

                ocr.DownloadSuccess = true;
            }

            catch (Exception ex)
            {
                ocr.DownloadSuccess = false;
                ocr.StateOcr        = STATE_OCR.OCR_FAIL_DOWNLOAD_FILE;
                ocr.TextError       = ex.Message;
            }

            return(ocr);
        }
        // This method is required by Katana:
        public void Configuration(IAppBuilder app)
        {
            // Adding to the pipeline with our own middleware
            app.Use(async(context, next) =>
            {
                // Add Header
                context.Response.Headers["Product"] = "Web Api and Owin Middleware";

                string file = context.Request.Query["file"];
                if (!string.IsNullOrWhiteSpace(file))
                {
                    OcrImageInfo ocr = new OcrImageInfo();
                    try
                    {
                        ocr.TextError = string.Empty;
                        ocr.TimeStart = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));


                        ocr.IsUrl = file.ToLower().StartsWith("http");
                        if (ocr.IsUrl)
                        {
                            ocr.Url = file;
                        }
                        else
                        {
                            ocr.FileName = file;
                        }

                        if (ocr.IsUrl)
                        {
                            ocr = ___downloadImage(ocr);
                        }

                        ocr = Program.goo_ocr_uploadFile(ocr);
                    }
                    catch (Exception e1) {
                        ocr.TextError = e1.Message;
                    }
                    string json = ocr.app_getJsonResult();

                    context.Response.StatusCode  = (int)HttpStatusCode.OK;
                    context.Response.ContentType = "application/json";
                    context.Response.Write(json);
                }
                else
                {
                    // Call next middleware
                    await next.Invoke();
                }
            });

            // Custom Middleare
            app.Use(typeof(SimpleMiddleware));

            // Configure Web API for self-host.
            var config = ConfigureWebApi();

            // Web Api
            app.UseWebApi(config);

            ////////// File Server
            ////////var options = new FileServerOptions
            ////////{
            ////////    EnableDirectoryBrowsing = true,
            ////////    EnableDefaultFiles = true,
            ////////    DefaultFilesOptions = { DefaultFileNames = { "home.html" } },
            ////////    FileSystem = new PhysicalFileSystem("StaticFiles"),
            ////////    StaticFileOptions = { ContentTypeProvider = new FileExtensionContentTypeProvider() }
            ////////};
            ////////app.UseFileServer(options);


            if (!Directory.Exists("htdocs"))
            {
                Directory.CreateDirectory("htdocs");
            }

            var physicalFileSystem = new PhysicalFileSystem("./htdocs");

            // file server options
            var options = new FileServerOptions
            {
                EnableDefaultFiles      = true,
                FileSystem              = physicalFileSystem, // register file system
                EnableDirectoryBrowsing = false
            };

            options.StaticFileOptions.FileSystem            = physicalFileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            options.DefaultFilesOptions.DefaultFileNames    = new[] { "index.html" };
            //app.Use<DefaultFileRewriterMiddleware>(physicalFileSystem);  // middleware to direct non-existing file URLs to index.html
            app.UseFileServer(options);
        }
        public static OcrImageInfo goo_ocr_uploadFile(OcrImageInfo ocr)
        {
            string file = Path.Combine(PATH_OCR_IMAGE, ocr.FileName);

            if (File.Exists(file) == false)
            {
                ocr.StateOcr = STATE_OCR.OCR_FAIL_MISS_FILE;
                return(ocr);
            }

            DataFile body = new DataFile()
            {
                Title       = ocr.FileName,
                Description = ocr.Url,
                //body.MimeType = "application/vnd.ms-excel";
                MimeType = "image/jpeg"
            };

            byte[] byteArray = File.ReadAllBytes(file);
            using (MemoryStream stream = new MemoryStream(byteArray))
            {
                try
                {
                    //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet");
                    FilesResource.InsertMediaUpload request = gooService.Files.Insert(body, stream, "application/vnd.google-apps.photo");
                    request.Ocr         = true;
                    request.OcrLanguage = "vi";
                    request.Convert     = true;

                    request.Upload();
                    DataFile imgFile = request.ResponseBody;
                    string   fileId  = imgFile.Id;

                    // Copy image and paste as document
                    var textMetadata = new DataFile();
                    //textMetadata.Name = inputFile.Name;
                    //textMetadata.Parents = new List<string> { folderId };
                    textMetadata.MimeType = "application/vnd.google-apps.document";
                    FilesResource.CopyRequest requestCopy = gooService.Files.Copy(textMetadata, fileId);
                    requestCopy.Fields      = "id";
                    requestCopy.OcrLanguage = "vi";
                    var textFile = requestCopy.Execute();

                    // Now we export document as plain text
                    FilesResource.ExportRequest requestExport = gooService.Files.Export(textFile.Id, "text/plain");
                    string output = requestExport.Execute();

                    ocr.TextResult = output;
                    ocr.StateOcr   = STATE_OCR.OCR_SUCCESS;

                    //writeLogMessage("OK: " + ocr.FileName);

                    if (ocr.WriteToFile)
                    {
                        if (!string.IsNullOrEmpty(ocr.TextResult))
                        {
                            File.WriteAllText(PATH_OCR_IMAGE + @"log\" + ocr.FileName + ".txt", ocr.TextResult);
                        }
                    }
                }
                catch (Exception e)
                {
                    ocr.TextError = e.Message;
                    ocr.StateOcr  = STATE_OCR.OCR_FAIL_THROW_ERROR;
                }
            }

            return(ocr);
        }