Saltar al contenido principal
Este ejemplo muestra cómo puede cargar al servidor solicitudes de apertura de cuentas bancarias y capturar los datos de los clientes. Descargue el proyecto y los materiales complementarios: Unattended.zip

El código de ejemplo realiza los siguientes pasos:

  • Se conecta al servicio
  • Abre una sesión
  • Abre el proyecto
  • Crea un nuevo lote
  • Añade imágenes al lote
  • Inicia el procesamiento del lote
  • Obtiene los resultados y muestra los datos capturados
  • Cierra la sesión

Para continuar con este ejemplo:

  • Cargue el archivo de proyecto UnattendedExample.fcproj en el servidor.
  • Abra UnattendedExample.sln en Visual Studio 2013 o una versión posterior

Conexión al servicio

// Crear una instancia del cliente del servicio web
var service = new FlexiCapture.FlexiCaptureWebServiceSoapClient();
// ======= AUTENTICACIÓN BÁSICA =======
// service.ClientCredentials.UserName.UserName = "username";
// service.ClientCredentials.UserName.Password = "password";

Iniciar una sesión

// Para proteger sus lotes contra el acceso no autorizado, especifique el usuario actual
// Primero, obtenga el nombre del usuario visible para el sistema
var username = service.GetCurrentUserIdentity();
// A continuación, búsquese entre los usuarios de FlexiCapture
var userId = service.FindUser(username.Name);
if (userId <= 0) throw new Exception("Current user not found");
// Abra una nueva sesión de procesamiento
const int roleType = 12; //El rol de operador en la estación del usuario
const int stationType = 10; //La estación del usuario
var sessionId = service.OpenSession(roleType, stationType);
if (sessionId <= 0) throw new Exception("Couldn't open the session");

Abrir el proyecto

// Obtener los proyectos
var projects = service.GetProjects();
var projectGuid = "";
if (projects != null && projects.Count > 0)
{
   foreach (var project in projects)
   {
      if (project.Name != "UnattendedExample") continue;
      projectGuid = project.Guid;
       break;
   }
}
if (string.IsNullOrEmpty(projectGuid))
{
   throw new Exception("Can't find the UnattendedExample project. You must upload this project to the server to be able to work with this example.");
}
// Abrir el primer proyecto llamado UnattendedExample
var projectId = service.OpenProject(sessionId, projectGuid);
if (projectId <= 0) throw new Exception("Couldn't open the project");

Crear un nuevo lote

// Especificar un nombre para el nuevo lote y mantener el resto de propiedades sin cambios
var batch = new FlexiCapture.Batch { Name = "Sample API Batch" };
var batchId = service.AddNewBatch(sessionId, projectId, batch, userId);
if (batchId <= 0) throw new Exception("Couldn't create the batch");

Añadir imágenes al lote

// Abrir el batch donde se agregarán las imágenes
service.OpenBatch(sessionId, batchId);

Carga de archivos de menos de 256 KB

service.AddNewImage(sessionId, batchId, new FlexiCapture.File()
{
   Bytes = File.ReadAllBytes(filename),
   Name = filename
});

Carga de archivos más grandes

Cargar archivos de más de 256 KB completos en Base64 tiene los siguientes inconvenientes:
  • La carga en la red aumenta un 33 %
  • IIS o el firewall pueden bloquear las solicitudes muy grandes
  • Si se pierde la conexión o se producen errores de red, tendrá que volver a enviar el archivo
Cargar archivos mediante la API del servicio de archivos es mucho más eficiente.
var doc = new FlexiCapture.Document { BatchId = batchId };
var file = new FlexiCapture.File { Name = filename };
var documentId = service.AddNewDocument(sessionId, doc, file, false, 0);
UploadFile(service, sessionId, projectId, batchId, documentId, filename).Wait();
private static async Task UploadFile(FlexiCapture.FlexiCaptureWebServiceSoapClient service, int sessionId, int projectId,
int batchId, int documentId, string filename)
{
   const int objectType = 0;
   var crc = new Crc32();
    using (var fs = File.OpenRead(filename))
   {
// Cargar el archivo en bloques de 1 MB
      var buffer = new byte[0x100000];
      var readed = fs.Read(buffer, 0, buffer.Length);
      var checksum = crc.Next(buffer, 0, readed);
      if (readed < buffer.Length)
      {
         // Cargar los archivos pequeños completos
         var resp = await FileRequest(service, "Save", objectType, sessionId, projectId, batchId, 0, documentId, 0, filename, 0,
         new ByteArrayContent(buffer, 0, readed));
         if (resp.StatusCode != HttpStatusCode.OK) throw new Exception("Server error");
      }
      else
      {
         var offset = 0;
         while (readed > 0)
         {
            var action = offset == 0 ? "BeginSaveChunked" : "Append";
            await FileRequest(service, action, objectType, sessionId, projectId, batchId, 0, documentId, 0, filename,
                            offset, new ByteArrayContent(buffer, 0, readed));
            offset += readed;
            readed = fs.Read(buffer, 0, buffer.Length);
            checksum = crc.Next(buffer, 0, readed);
         }
         var resp = await FileRequest(service, "Commit", objectType, sessionId, projectId, batchId, 0, documentId, 0, filename);
         if (resp.StatusCode != HttpStatusCode.OK) throw new Exception("Server error");
      }
      var response = await FileRequest(service, "Checksum", objectType, sessionId, projectId, batchId, 0, documentId, 0, filename);
      var text = await response.Content.ReadAsStringAsync();
      if (uint.Parse(text, NumberStyles.HexNumber) != checksum)
      {
         throw new Exception("Se produjo un error al cargar el archivo");
      }
   }
}
private static async Task<HttpResponseMessage> FileRequest(FlexiCapture.FlexiCaptureWebServiceSoapClient service, string action,
            int objectType, int sessionId, int projectId, int batchId, int parentId, int objectId, int version, string streamName, int offset, HttpContent file)
{
   var creds = CredentialCache.DefaultNetworkCredentials;
   if (!string.IsNullOrEmpty(service.ClientCredentials.UserName.UserName))
                creds = new NetworkCredential(service.ClientCredentials.UserName.UserName, service.ClientCredentials.UserName.Password);
   using (var handler = new HttpClientHandler { Credentials = creds })
   using (var client = new HttpClient(handler))
   {
      var uri = service.Endpoint.Address.Uri;
      var content = new MultipartFormDataContent
      {
         {new StringContent(action), "Action"},
         {new StringContent(objectType.ToString()), "objectType"},
         {new StringContent(sessionId.ToString()), "sessionId"},
         {new StringContent(projectId.ToString()), "projectId"},
         {new StringContent(batchId.ToString()), "batchId"},
         {new StringContent(parentId.ToString()), "parentId"},
         {new StringContent(objectId.ToString()), "objectId"},
         {new StringContent(version.ToString()), "version"},
         {new StringContent(Convert.ToBase64String(Encoding.Unicode.GetBytes(streamName))), "streamName"},
      };
      if (offset > 0)
      {
         content.Add(new StringContent(offset.ToString()), "offset");
      }
      content.Add(file, "blob", "data.txt");
      return await client.PostAsync(uri.OriginalString.Replace("/API/v1/Soap", "/FileService/v1"), content);
   }
}
private static async Task<HttpResponseMessage> FileRequest(FlexiCapture.FlexiCaptureWebServiceSoapClient service, string action,
   int objectType, int sessionId, int projectId, int batchId, int parentId, int objectId, int version, string streamName)
{
   var creds = CredentialCache.DefaultNetworkCredentials;
   if (!string.IsNullOrEmpty(service.ClientCredentials.UserName.UserName))
      creds = new NetworkCredential(service.ClientCredentials.UserName.UserName, service.ClientCredentials.UserName.Password);
   using (var handler = new HttpClientHandler { Credentials = creds })
   using (var client = new HttpClient(handler))
   {
      var uri = service.Endpoint.Address.Uri;
      var content = new FormUrlEncodedContent(new Dictionary<string, string>
      {
         {"Action", action},
         {"objectType", objectType.ToString()},
         {"sessionId", sessionId.ToString()},
         {"projectId", projectId.ToString()},
         {"batchId", batchId.ToString()},
         {"parentId", parentId.ToString()},
         {"objectId", objectId.ToString()},
         {"version", version.ToString()},
         {"streamName", streamName},
      });
      return await client.PostAsync(uri.OriginalString.Replace("/API/v1/Soap", "/FileService/v1"), content);
   }
}

Inicio y fin del procesamiento por lotes

// Iniciar el procesamiento del lote
service.ProcessBatch(sessionId, batchId);
Console.WriteLine("recognition task created, waiting ");
// Esperar a que el procesamiento finalice
var percentCompleted = 0;
while (percentCompleted < 100)
{
   Console.CursorLeft = 0;
   Console.Write(percentCompleted + "%");
   percentCompleted = service.GetBatchPercentCompleted(batchId);
   System.Threading.Thread.Sleep(500);
}
Console.CursorLeft = 0;
Console.WriteLine("complete...");

Obtener los resultados y mostrar los datos capturados

De cada documento, solo se muestran tres campos:
  • Dirección
  • Nombre
  • Apellido
// Obtener los resultados
var documents = service.GetDocuments(sessionId, batchId);
if (documents == null) return;
// Nombres XML necesarios para analizar los resultados XML
var docs = XName.Get("Documents", "https://www.abbyy.com/FlexiCapture/Schemas/Export/FormData.xsd");
var banking = XName.Get("_Banking_eng", "https://www.abbyy.com/FlexiCapture/Schemas/Export/Banking_eng.xsd");
// Iterar todos los resultados y mostrarlos en pantalla
foreach (var document in documents)
{
   if (document.Id == 0) continue;
   // Obtener el archivo XML con los datos reconocidos
   var attachedFile = service.LoadDocumentResult(sessionId, batchId, document.Id, "Result.xml");
   if (attachedFile.Bytes == null) continue;
   // Abrir los resultados en XML
   var xml = XDocument.Load(new MemoryStream(attachedFile.Bytes));
   var docsElement = xml.Element(docs); // Contenedor para los datos reconocidos
   if (docsElement == null) continue;
   var result = docsElement.Element(banking);
    if (result == null) continue;
   // Obtener los datos necesarios
   var addressing = result.Element("_Addressing");
   var surname = result.Element("_Last_Name");
   var name = result.Element("_First_Name");
   // Mostrar los datos
   Console.WriteLine("- " +
      (addressing == null ? "" : addressing.Value) + " " +
      (name == null ? "" : name.Value) + " " +
      (surname == null ? "" : surname.Value)
   );
}

Cierre de sesión

service.DeleteBatch(sessionId, batchId);
service.CloseProject(sessionId, projectId);
service.CloseSession(sessionId);