Example #1
0
 public void AddTask(OcrSdkTask task)
 {
     lock (allTasks)
     {
         allTasks.Add(task.Id, task);
     }
 }
        /// <summary>
        /// Download task that has finished processing and save it to given path
        /// </summary>
        /// <param name="task">Id of a task</param>
        /// <param name="outputFile">Path to save a file</param>
        public void DownloadResult(OcrSdkTask task, string outputFile)
        {
            if (task.Status != TaskStatus.Completed)
            {
                throw new ArgumentException("Cannot download result for not completed task");
            }

            try
            {
                if (File.Exists(outputFile))
                {
                    File.Delete(outputFile);
                }


                if (task.DownloadUrls == null || task.DownloadUrls.Count == 0)
                {
                    throw new ArgumentException("Cannot download task without download url");
                }

                string url = task.DownloadUrls[0];
                DownloadUrl(url, outputFile);
            }
            catch (System.Net.WebException e)
            {
                throw new ProcessingErrorException(e.Message, e);
            }
        }
Example #3
0
        // This is the method that the underlying, free-threaded
        // asynchronous behavior will invoke.  This will happen on
        // a worker thread
        private void processCompletionMethod(
            OcrSdkTask task,
            Exception exception,
            bool canceled,
            AsyncOperation asyncOp)
        {
            // If the task was not previously canceled,
            // remove the task from the lifetime collection.
            if (!canceled)
            {
                lock (processJobs)
                {
                    processJobs.Remove(asyncOp.UserSuppliedState);
                }
            }

            // Package the results of the operation in EventArgs
            TaskEventArgs e = new TaskEventArgs(task, exception, canceled, asyncOp.UserSuppliedState);

            // End the task. The asyncOp object is responsible
            // for marshaling the call.
            asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, e);

            // Note that after the call to OperationCompleted,
            // asyncOp is no longer usable, and any attempt to use it
            // will cause an exception to be thrown.
        }
Example #4
0
        /// <summary>
        /// Upload a file to service synchronously and start processing
        /// </summary>
        /// <param name="filePath">Path to an image to process</param>
        /// <param name="settings">Language and output format</param>
        /// <returns>Id of the task. Check task status to see if you have enough units to process the task</returns>
        /// <exception cref="ProcessingErrorException">thrown when something goes wrong</exception>
        public OcrSdkTask ProcessImage(string filePath, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processImage?{1}", ServerUrl, settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            try
            {
                // Build post request
                WebRequest request = WebRequest.Create(url);
                setupPostRequest(url, request);
                writeFileToRequest(filePath, request);

                XDocument  response = performRequest(request);
                OcrSdkTask task     = ServerXml.GetTaskStatus(response);

                return(task);
            }
            catch (System.Net.WebException e)
            {
                throw new ProcessingErrorException("Cannot upload file: " + e.Message + ". Please make sure that application Id and password are correct.", e);
            }
        }
        /// <summary>
        /// Upload a file to service synchronously and start processing
        /// </summary>
        /// <param name="filePath">Path to an image to process</param>
        /// <param name="settings">Language and output format</param>
        /// <returns>Id of the task. Check task status to see if you have enough units to process the task</returns>
        /// <exception cref="ProcessingErrorException">thrown when something goes wrong</exception>
        public OcrSdkTask ProcessImage(string filePath, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processImage?{1}", ServerUrl, settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            try
            {
                // Build post request
                WebRequest request = createPostRequest(url);
                writeFileToRequest(filePath, request);

                XDocument  response = performRequest(request);
                OcrSdkTask task     = ServerXml.GetTaskStatus(response);

                return(task);
            }
            catch (System.Net.WebException e)
            {
                String friendlyMessage = retrieveFriendlyMessage(e);
                if (friendlyMessage != null)
                {
                    throw new ProcessingErrorException(friendlyMessage, e);
                }
                throw new ProcessingErrorException("Cannot upload file", e);
            }
        }
Example #6
0
        private void processFieldWorker(string filePath, IProcessingSettings settings,
                                        AsyncOperation asyncOp)
        {
            Exception e = null;

            OcrSdkTask task = new OcrSdkTask();

            try
            {
                if (settings is TextFieldProcessingSettings)
                {
                    task = _syncClient.ProcessTextField(filePath, settings as TextFieldProcessingSettings);
                }
                else if (settings is BarcodeFieldProcessingSettings)
                {
                    task = _syncClient.ProcessBarcodeField(filePath, settings as BarcodeFieldProcessingSettings);
                }
                else if (settings is CheckmarkFieldProcessingSettings)
                {
                    task = _syncClient.ProcessCheckmarkField(filePath, settings as CheckmarkFieldProcessingSettings);
                }
                else
                {
                    throw new ArgumentException("Invalid type of processing settings");
                }

                // Notify that upload was completed
                OcrSdkTask uploadedTask = new OcrSdkTask(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                // Wait until task finishes
                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);
                task = waitUntilTaskFinishes(task);
            }
            catch (Exception ex)
            {
                e = ex;
            }

            lock (processJobs)
            {
                processJobs.Remove(asyncOp.UserSuppliedState);
            }

            bool canceled = false;

            // Package the results of the operation in EventArgs
            TaskEventArgs ev = new TaskEventArgs(task, e, canceled, asyncOp.UserSuppliedState);

            // End the task. The asyncOp object is responsible
            // for marshaling the call.
            asyncOp.PostOperationCompleted(onProcessingCompleteDelegate, ev);
        }
        public OcrSdkTask GetTaskStatus(TaskId task)
        {
            string url = String.Format("{0}/getTaskStatus?taskId={1}", ServerUrl,
                                       Uri.EscapeDataString(task.ToString()));

            WebRequest request    = createGetRequest(url);
            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
        /// <summary>
        /// Recognize Machine-Readable Zone of an official document (Passport, ID, Visa etc)
        /// </summary>
        public OcrSdkTask ProcessMrz(string filePath)
        {
            string     url     = String.Format("{0}/processMRZ", ServerUrl);
            WebRequest request = createPostRequest(url);

            writeFileToRequest(filePath, request);

            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
Example #9
0
        public static OcrSdkTask[] GetAllTasks(XDocument xml)
        {
            List <OcrSdkTask> result    = new List <OcrSdkTask>();
            XElement          xResponse = xml.Root;

            foreach (XElement xTask in xResponse.Elements("task"))
            {
                OcrSdkTask task = getTaskInfo(xTask);
                result.Add(task);
            }

            return(result.ToArray());
        }
Example #10
0
        public OcrSdkTask ProcessBusinessCard(string filePath, BusCardProcessingSettings settings)
        {
            string url = String.Format("{0}/processBusinessCard?{1}", ServerUrl, settings.AsUrlParams);

            // Build post request
            WebRequest request = createPostRequest(url);

            writeFileToRequest(filePath, request);

            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
Example #11
0
        private void downloadFileWorker(OcrSdkTask task, string outputFilePath,
                                        AsyncOperation asyncOp)
        {
            Exception e = null;

            try
            {
                _syncClient.DownloadResult(task, outputFilePath);
            }
            catch (Exception ex)
            {
                e = ex;
            }

            downloadCompletionMethod(task, e, false, asyncOp);
        }
Example #12
0
        public bool IsTaskFinished(TaskId taskId)
        {
            TaskStatus status = TaskStatus.Unknown;

            lock (allTasks)
            {
                status = allTasks[taskId].Status;
            }

            if (status == TaskStatus.Unknown || OcrSdkTask.IsTaskActive(status))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Example #13
0
        /// <summary>
        /// Perform fields recognition of uploaded document.
        /// </summary>
        /// <param name="task">Task created by UploadAndAddFileToTask method</param>
        /// <param name="settingsPath">Path to file with xml processing settings.</param>
        public OcrSdkTask ProcessFields(OcrSdkTask task, string settingsPath)
        {
            if (!File.Exists(settingsPath))
            {
                throw new FileNotFoundException("Settings file doesn't exist.", settingsPath);
            }

            string url = String.Format("{0}/processFields?taskId={1}", ServerUrl, task.Id);

            WebRequest request = createPostRequest(url);

            writeFileToRequest(settingsPath, request);

            XDocument  response = performRequest(request);
            OcrSdkTask result   = ServerXml.GetTaskStatus(response);

            return(result);
        }
Example #14
0
        private void downloadCompletionMethod(
            OcrSdkTask task,
            Exception exception,
            bool canceled,
            AsyncOperation asyncOp)
        {
            if (!canceled)
            {
                lock (downloadJobs)
                {
                    downloadJobs.Remove(asyncOp.UserSuppliedState);
                }
            }

            TaskEventArgs e = new TaskEventArgs(task, exception, canceled, asyncOp.UserSuppliedState);

            asyncOp.PostOperationCompleted(onDownloadCompletedDelegate, e);
        }
Example #15
0
        public OcrSdkTask StartProcessingTask(TaskId taskId, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processDocument?taskId={1}&{2}", ServerUrl,
                                       Uri.EscapeDataString(taskId.ToString()),
                                       settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            // Build get request
            WebRequest request    = createGetRequest(url);
            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
Example #16
0
        /// <summary>
        /// Delete task on a server. This function cannot delete tasks that are being processed.
        /// </summary>
        public OcrSdkTask DeleteTask(OcrSdkTask task)
        {
            switch (task.Status)
            {
            case TaskStatus.Deleted:
            case TaskStatus.InProgress:
            case TaskStatus.Unknown:
                throw new ArgumentException("Invalid task status: " + task.Status + ". Cannot delete");
            }

            string     url     = String.Format("{0}/deleteTask?taskId={1}", ServerUrl, Uri.EscapeDataString(task.Id.ToString()));
            WebRequest request = createGetRequest(url);

            XDocument  response   = performRequest(request);
            OcrSdkTask serverTask = ServerXml.GetTaskStatus(response);

            return(serverTask);
        }
Example #17
0
        // This method performs the actual file processing.
        // It is executed on the worker thread.
        private void processFileWorker(string filePath, IProcessingSettings settings,
                                       AsyncOperation asyncOp)
        {
            Exception e = null;

            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.

            OcrSdkTask task = null;

            try
            {
                if (settings is ProcessingSettings)
                {
                    task = _syncClient.ProcessImage(filePath, settings as ProcessingSettings);
                }
                else if (settings is BusCardProcessingSettings)
                {
                    task = _syncClient.ProcessBusinessCard(filePath, settings as BusCardProcessingSettings);
                }
                else if (settings is ProcessMrzSettings)
                {
                    task = _syncClient.ProcessMrz(filePath);
                }

                // Notify subscriber that upload completed
                OcrSdkTask uploadedTask = new OcrSdkTask(task.Id, TaskStatus.Submitted);
                UploadCompletedEventArgs uploadCompletedEventArgs = new UploadCompletedEventArgs(uploadedTask, asyncOp.UserSuppliedState);
                asyncOp.Post(onUploadCompletedDelegate, uploadCompletedEventArgs);

                startTaskMonitorIfNecessary();

                _taskList.AddTask(task);

                task = waitUntilTaskFinishes(task); // task is modified on server
            }
            catch (Exception ex)
            {
                e = ex;
            }

            processCompletionMethod(task, e, false, asyncOp);
        }
Example #18
0
        public void DownloadResult(OcrSdkTask task, string outputFile)
        {
            if (task.Status != TaskStatus.Completed)
            {
                throw new ArgumentException("Cannot download result for not completed task");
            }

            try
            {
                if (task.DownloadUrl == null)
                {
                    throw new ArgumentException("Cannot download task without download url");
                }

                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (storage.FileExists(outputFile))
                    {
                        storage.DeleteFile(outputFile);
                    }

                    string url = task.DownloadUrl;

                    WebRequest request = WebRequest.Create(url);
                    setupGetRequest(url, request);

                    using (HttpWebResponse result = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream stream = result.GetResponseStream())
                        {
                            // Write result directly to file
                            using (Stream file = storage.OpenFile(outputFile, FileMode.Create))
                            {
                                copyStream(stream, file);
                            }
                        }
                    }
                }
            }
            catch (System.Net.WebException e)
            {
                throw new ProcessingErrorException(e.Message, e);
            }
        }
Example #19
0
        /// <summary>
        /// Download file asynchronously
        /// Performs DownloadFileCompleted callback
        /// </summary>
        public void DownloadFileAsync(OcrSdkTask task, string outputPath, object userTaskId)
        {
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userTaskId);

            lock (downloadJobs)
            {
                if (downloadJobs.ContainsKey(userTaskId))
                {
                    throw new ArgumentException("Task ID parameter must be unique", "userTaskId");
                }
                downloadJobs[userTaskId] = asyncOp;
            }

            // Start the asynchronous operation.
            downloadWorkerEventHandler workerDelegate = new downloadWorkerEventHandler(downloadFileWorker);

            workerDelegate.BeginInvoke(task, outputPath, asyncOp,
                                       null, null);
        }
Example #20
0
        /// <summary>
        /// Upload a file to service synchronously and start processing
        /// </summary>
        /// <param name="filePath">Path to an image to process</param>
        /// <param name="settings">Language and output format</param>
        /// <returns>Id of the task. Check task status to see if you have enough units to process the task</returns>
        /// <exception cref="ProcessingErrorException">thrown when something goes wrong</exception>
        public OcrSdkTask ProcessImage(string filePath, ProcessingSettings settings)
        {
            string url = String.Format("{0}/processImage?{1}", ServerUrl, settings.AsUrlParams);

            if (!String.IsNullOrEmpty(settings.Description))
            {
                url = url + "&description=" + Uri.EscapeDataString(settings.Description);
            }

            // Build post request
            WebRequest request = createPostRequest(url);

            writeFileToRequest(filePath, request);

            XDocument  response = performRequest(request);
            OcrSdkTask task     = ServerXml.GetTaskStatus(response);

            return(task);
        }
Example #21
0
        /// <summary>
        /// Submit and process image asynchronously.
        /// Performs callbacks:
        ///   UploadFileCompleted
        ///   TaskProcessingCompleted
        /// </summary>
        /// <param name="filePath">Path to file in isolated storage</param>
        /// <param name="settings"></param>
        /// <param name="userState"></param>
        public void ProcessImageAsync(string filePath, ProcessingSettings settings, object userState)
        {
            BackgroundWorker w = new BackgroundWorker();

            w.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                OcrSdkTask task = null;
                try
                {
                    task = _syncClient.ProcessImage(filePath, settings);
                    UploadCompletedEventArgs uploadArgs = new UploadCompletedEventArgs(task, userState);
                    onUploadFileCompleted(sender, uploadArgs);

                    // Wait until task finishes
                    while (true)
                    {
                        task = _syncClient.GetTaskStatus(task.Id);
                        if (!task.IsTaskActive())
                        {
                            break;
                        }
                        Thread.Sleep(1000);
                    }

                    if (task.Status == TaskStatus.NotEnoughCredits)
                    {
                        throw new Exception("Not enough credits to process image. Please add more pages to your application's account.");
                    }

                    TaskEventArgs taskArgs = new TaskEventArgs(task, null, false, userState);

                    onProcessingCompleted(sender, taskArgs);
                }
                catch (Exception ex)
                {
                    TaskEventArgs taskArgs = new TaskEventArgs(task, ex, false, userState);
                    onProcessingCompleted(sender, taskArgs);
                }
            }
                                               );

            w.RunWorkerAsync();
        }
Example #22
0
        /// <summary>
        /// Upload image of a multipage document to server.
        /// </summary>
        /// <param name="filePath">Path to an image to process</param>
        /// <param name="taskToAddFile">Id of multipage document. If null, a new document is created</param>
        /// <returns>Id of document to which image was added</returns>
        public OcrSdkTask UploadAndAddFileToTask(string filePath, TaskId taskToAddFile)
        {
            string url = String.Format("{0}/submitImage", ServerUrl);

            if (taskToAddFile != null)
            {
                url = url + "?taskId=" + Uri.EscapeDataString(taskToAddFile.ToString());
            }

            // Build post request
            WebRequest request = createPostRequest(url);

            writeFileToRequest(filePath, request);

            XDocument  response = performRequest(request);
            OcrSdkTask task     = ServerXml.GetTaskStatus(response);

            return(task);
        }
Example #23
0
        /// <summary>
        /// Download file asynchronously
        /// Performs DownloadFileCompleted callback
        /// </summary>
        public void DownloadFileAsync(OcrSdkTask task, string outputPath, object userState)
        {
            BackgroundWorker w = new BackgroundWorker();

            w.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    _syncClient.DownloadResult(task, outputPath);
                    TaskEventArgs taskArgs = new TaskEventArgs(task, null, false, userState);
                    onDownloadFileCompleted(sender, taskArgs);
                }
                catch (Exception ex)
                {
                    TaskEventArgs taskArgs = new TaskEventArgs(task, ex, false, userState);
                    onDownloadFileCompleted(sender, taskArgs);
                }
            }
                                               );

            w.RunWorkerAsync();
        }
Example #24
0
        /// <summary>
        /// Enter infinite loop and wait for task to complete
        /// </summary>
        /// <returns>Details about completed task</returns>
        private OcrSdkTask waitUntilTaskFinishes(OcrSdkTask task)
        {
            while (true)
            {
                if (_taskList.Error != null)
                {
                    _taskList.DeleteTask(task.Id);
                    throw new Exception(_taskList.Error.Message, _taskList.Error);
                }

                TaskStatus taskStatus = _taskList.GetTaskStatus(task.Id);
                if (_taskList.IsTaskFinished(task.Id))
                {
                    OcrSdkTask result = _taskList.GetTask(task.Id);
                    _taskList.DeleteTask(task.Id);

                    return(result);
                }

                Thread.Sleep(1000);
            }
        }
Example #25
0
 public UploadCompletedEventArgs(OcrSdkTask task, object userState) :
     base(50, userState)
 {
     _task = task;
 }
Example #26
0
        /// <summary>
        /// Get task data from xml node "task"
        /// </summary>
        private static OcrSdkTask getTaskInfo(XElement xTask)
        {
            TaskId     id     = new TaskId(xTask.Attribute("id").Value);
            TaskStatus status = statusFromString(xTask.Attribute("status").Value);

            OcrSdkTask task = new OcrSdkTask();

            task.Id     = id;
            task.Status = status;

            XAttribute xRegistrationTime = xTask.Attribute("registrationTime");

            if (xRegistrationTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xRegistrationTime.Value, out time))
                {
                    task.RegistrationTime = time;
                }
            }

            XAttribute xStatusChangeTime = xTask.Attribute("statusChangeTime");

            if (xStatusChangeTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xStatusChangeTime.Value, out time))
                {
                    task.StatusChangeTime = time;
                }
            }

            XAttribute xFilesCount = xTask.Attribute("filesCount");

            if (xFilesCount != null)
            {
                int filesCount;
                if (Int32.TryParse(xFilesCount.Value, out filesCount))
                {
                    task.FilesCount = filesCount;
                }
            }

            XAttribute xCredits = xTask.Attribute("credits");

            if (xCredits != null)
            {
                int credits;
                if (Int32.TryParse(xCredits.Value, out credits))
                {
                    task.Credits = credits;
                }
            }

            XAttribute xDescription = xTask.Attribute("description");

            if (xDescription != null)
            {
                task.Description = xDescription.Value;
            }

            XAttribute xResultUrl = xTask.Attribute("resultUrl");

            if (xResultUrl != null)
            {
                task.DownloadUrls = new List <string> {
                    xResultUrl.Value
                };
                for (int i = 2; i < 10; i++)
                {
                    XAttribute xResultUrlI = xTask.Attribute("resultUrl" + i);
                    if (xResultUrlI != null)
                    {
                        task.DownloadUrls.Add(xResultUrlI.Value);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            XAttribute xError = xTask.Attribute("error");

            if (xError != null)
            {
                task.Error = xError.Value;
            }

            return(task);
        }
Example #27
0
 public TaskEventArgs(OcrSdkTask task,
                      Exception e, bool canceled, object state)
     : base(e, canceled, state)
 {
     _task = task;
 }
Example #28
0
        /// <summary>
        /// Get task data from xml node "task"
        /// </summary>
        private static OcrSdkTask getTaskInfo(XElement xTask)
        {
            TaskId     id     = new TaskId(xTask.Attribute("id").Value);
            TaskStatus status = statusFromString(xTask.Attribute("status").Value);

            OcrSdkTask task = new OcrSdkTask();

            task.Id     = id;
            task.Status = status;

            XAttribute xRegistrationTime = xTask.Attribute("registrationTime");

            if (xRegistrationTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xRegistrationTime.Value, out time))
                {
                    task.RegistrationTime = time;
                }
            }

            XAttribute xStatusChangeTime = xTask.Attribute("statusChangeTime");

            if (xStatusChangeTime != null)
            {
                DateTime time;
                if (DateTime.TryParse(xStatusChangeTime.Value, out time))
                {
                    task.StatusChangeTime = time;
                }
            }

            XAttribute xPagesCount = xTask.Attribute("filesCount");

            if (xPagesCount != null)
            {
                int pagesCount;
                if (Int32.TryParse(xPagesCount.Value, out pagesCount))
                {
                    task.PagesCount = pagesCount;
                }
            }

            XAttribute xCredits = xTask.Attribute("credits");

            if (xCredits != null)
            {
                int credits;
                if (Int32.TryParse(xCredits.Value, out credits))
                {
                    task.Credits = credits;
                }
            }

            XAttribute xDescription = xTask.Attribute("description");

            if (xDescription != null)
            {
                task.Description = xDescription.Value;
            }

            XAttribute xResultUrl = xTask.Attribute("resultUrl");

            if (xResultUrl != null)
            {
                task.DownloadUrl = xResultUrl.Value;
            }

            return(task);
        }