> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ejemplo de procesamiento automático

> Recorra un ejemplo de la API de ABBYY FlexiCapture que abre una sesión, crea un lote, carga imágenes de solicitudes bancarias, las procesa y lee los resultados.

Este ejemplo muestra cómo cargar al servidor solicitudes de apertura de cuentas bancarias y capturar los datos de los clientes.

<div id="what-the-example-does">
  ## Qué hace el ejemplo
</div>

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

<div id="set-up-the-example">
  ## Configurar el ejemplo
</div>

<Steps>
  <Step title="Cargar el archivo del proyecto en el servidor">
    Cargue el archivo de proyecto `UnattendedExample.fcproj` en el servidor.
  </Step>

  <Step title="Abrir la solución en Visual Studio">
    Abra `UnattendedExample.sln` en Visual Studio 2013 o posterior.
  </Step>
</Steps>

<div id="connect-to-the-service">
  ## Conectarse al servicio
</div>

```csharp theme={null}
// 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";
```

<div id="open-a-session">
  ## Iniciar una sesión
</div>

```csharp theme={null}
// 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");
```

<div id="open-the-project">
  ## Abrir el proyecto
</div>

```csharp theme={null}
// 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");
```

<div id="create-a-new-batch">
  ## Crear un nuevo lote
</div>

```csharp theme={null}
// 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");
```

<div id="add-images-to-the-batch">
  ## Añadir imágenes al lote
</div>

```csharp theme={null}
// Abrir el lote donde se agregarán las imágenes
service.OpenBatch(sessionId, batchId);
```

<div id="upload-files-smaller-than-256-kb">
  ### Carga de archivos de menos de 256 KB
</div>

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

<div id="upload-larger-files">
  ### Cargar archivos más grandes
</div>

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:

```csharp theme={null}
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();
```

<div id="upload-a-file-to-the-server">
  #### Cargar un archivo al servidor
</div>

El método `UploadFile` lee el archivo y lo envía al servicio de archivos en bloques de 1 MB y, a continuación, verifica la carga con una suma de comprobación:

```csharp theme={null}
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("An error occurred when uploading the file");
        }
    }
}
```

<div id="send-a-file-request-with-file-content">
  #### Enviar una solicitud de archivo con el contenido del archivo
</div>

El método `FileRequest` tiene dos sobrecargas para enviar una acción al servicio de archivos. La primera envía el contenido del archivo como datos de formulario multipart:

```csharp theme={null}
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);
    }
}
```

<div id="send-a-file-request-without-file-content">
  #### Enviar una solicitud de archivo sin contenido del archivo
</div>

La segunda sobrecarga envía una solicitud sin contenido del archivo, con codificación URL de formulario:

```csharp theme={null}
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);
    }
}
```

<div id="start-and-end-batch-processing">
  ## Inicio y fin del procesamiento por lotes
</div>

```csharp theme={null}
// 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...");
```

<div id="get-the-results-and-display-the-captured-data">
  ## Obtener los resultados y mostrar los datos capturados
</div>

De cada documento, solo se muestran tres campos:

* **Dirección**
* **Nombre**
* **Apellido**

```csharp theme={null}
// 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)
    );
}
```

<div id="close-the-session">
  ## Cerrar la sesión
</div>

```csharp theme={null}
service.DeleteBatch(sessionId, batchId);
service.CloseProject(sessionId, projectId);
service.CloseSession(sessionId);
```
