Ir para o conteúdo

Exemplo de Script – Arquivos em Lote para Download

Este plug-in suporta a capacidade de baixar vários arquivos de um painel de múltiplas linhas ou painel de quadro de uma só vez. Na execução do evento Business Object, o Plugin percorrerá todos os registros do Business Object ou da tabela para identificar e lote os arquivos apropriados para disponibilizar em um único download.

Quando o plug-in é executado, ele basicamente captura todos os valores de arquivo e nome de arquivo correspondentes e os coloca em um arquivo zip. O nome do arquivo zip gerado ao finalizar o Plugin será: "MM/dd/yyyy h:mm tt".zip", que reflete a data e hora em que foi executado e anexa a extensão .zip.

Com o exemplo de script fornecido, o script é executado em uma tabela ou objeto de negócios independente das ligações de nível de painel ou UI. Isso significa que uma ligação no nível do painel ou uma ligação de controle não afeta a tabela subjacente do plug-in. Isso também significa que tudo o que você deseja fazer, incluindo ligações no painel ou na tabela, deve ser feito no nível do objeto de negócios/tabela.

Caso de Uso

Este Plugin é útil quando você tem um painel em um aplicativo onde deseja disponibilizar vários arquivos para download em uma única ação.

Requisitos

Este Plugin requer que você tenha duas tabelas ou Business Objects existentes, e ambos devem ter colunas File e FileName. Um deles representa de onde o Plugin está sendo lido e o outro representa onde o Plugin está sendo inserido.

Preferências de Implementação

Você desejará revisar e modificar a sintaxe a seguir no script, para substituir os UUIDs no plug-in para refletir os UUIDs reais das tabelas ou objetos de negócios que você está referenciando em seu aplicativo.

var importFileTableFilter = tableService.GetTable(Guid.Parse("{{UUID da tabela que contém os arquivos que serão compactados}}")).CreateFilter();

var importZipTableFilter = tableService.GetTable(Guid.Parse("{{UUID da tabela onde o arquivo ZIP será inserido}}")).CreateFilter();

Referências de Plug-ins

Nota

É possível modificar o script do plug-in para obter outras colunas de conteúdo de arquivo e nome de arquivo, mas normalmente a metodologia de nomenclatura indica que a coluna de conteúdo seja "Arquivo" e o nome do arquivo seja "Nome do arquivo".

Coluna Tipo de dados Descrição
FileName String Coluna contendo nome e extensão do Arquivo.
File Binary Coluna com conteúdo do arquivo.

Exemplo de Script

using System.IO;
using System.IO.Compression;
using Vinyl.Sdk.Events;
using Vinyl.Sdk.Filtering;
using System.Linq;
using Vinyl.Sdk;
using System;

var tableService = Services.GetService<ITableService>();
var eventService = Services.GetService<IEventService>();

var importFileTableFilter = tableService.GetTable(Guid.Parse("Table UUID containing files to be compressed")).CreateFilter();
EventTable readFileTable = await eventService.InvokeEventAsync(importFileTableFilter, "filter");
importFileTableFilter.Limit = 0;
EventTable importFileTable = await eventService.InvokeFilterEventAsync(importFileTableFilter);
EventRow rowFile = await eventService.InvokeNewEventAsync(importFileTable);

var importZipTableFilter = tableService.GetTable(Guid.Parse("Table UUID where ZIP file will be inserted")).CreateFilter();
importZipTableFilter.Limit = 0;
EventTable importZipTable = await eventService.InvokeFilterEventAsync(importZipTableFilter);
EventRow rowZip = await eventService.InvokeNewEventAsync(importZipTable);

byte[] fileBytes;
var compressedFileStream = new MemoryStream();
string inspectionID;

using (compressedFileStream)
{
    compressedFileStream.Seek(0, SeekOrigin.Begin);
    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, false))
    {
       foreach (EventRow row1 in (EventTable)readFileTable)
       {

                //Create a zip entry for each attachment
                var zipEntry = zipArchive.CreateEntry(row1["FileName"].GetValueAsString());

                //Get the stream of the attachment
                using (var originalFileStream = new MemoryStream((byte[])row1["File"].Value))
                {
                    using (var zipEntryStream = zipEntry.Open())
                    {
                        //Copy the attachment stream to the zip entry stream
                        originalFileStream.CopyTo(zipEntryStream);
                    }
                }

        }
    }
  fileBytes = compressedFileStream.ToArray();
}

rowZip["FileName"].Value = DateTime.Now.ToString("MM/dd/yyyy h:mm tt") + ".zip";

rowZip["File"].Value = fileBytes;

await eventService.InvokeInsertEventAsync(rowZip);