Long processes in C #

3

I need to do a routine where the user will upload a data load file, and C # will process it and save it to the database, without giving time-out and showing the progress of the process to the user .

My question is: how to do it?

I do not have the slightest idea how to do it or how to search on Google. Any suggestions?

    
asked by anonymous 25.03.2014 / 14:27

4 answers

1

In the case of TimeOut you can configure it on the web.config itself

<system.web>
<authentication mode="Forms">
      <forms timeout="50"/>
</authentication>
<sessionState timeout="60"  />
</system.web>

So setting the timeout for Session and Forms.

    
25.03.2014 / 17:27
1

I do not think it's the best solution to process a file already uploaded. Ideally, you should just move the file to a folder on your server and have a service do the processing for you.

This prevents you from crashing your application on the ISS and the Database doing very heavy processing, and takes away that responsibility from your WebSite or WinForms to do what it would not really be your responsibility to make future maintenance on a code that probably is complex.

There is no way I can suggest an implementation of how to save the file since I do not know if you use MVC, Web Forms or Win Forms.

But in the case of Windows Service you need to use a File System Watcher Type object to monitor the receipt of files in the server folder as the example:

public partial class ProcessadorDeArquivo
{
     protected FileSystemWatcher _fileSystemWatcher { get; set; }

     public ProcessadorDeArquivo()
     {
          _fileSystemWatcher = new FileSystemWatcher(@"C:\Arquivos"); //Pasta que será utilizada para salva os arquivos.
          _fileSystemWatcher.Filter = ".txt" //ExtensãoDoArquivo
          _fileSystemWatcher.Created += FileSystemWatcherCreated;
          _fileSystemWatcher.EnableRaisingEvents = true;
     }

     /// <summary>
     /// Quando um arquivo é criado na pasta assistida esse evento é disparado
     /// </summary>
     protected void FileSystemWatcherCreated(object sender, FileSystemEventArgs e)
     {
         ProcessarArquivos(e.FullPath); //Método que teria toda a regra de processar.
     }
}

EDIT (ASP.NET MVC)

//VIEW
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype ="multipart/form-    data" }))
{
<input type="arquivo" name="arquivo" />
<input type="submit" value="salvar" />
}

//CONTROLLER

    public ActionResult Index(HttpPostedFileBase arquivo)
{
    // Verify that the user selected a file
    if (arquivo != null) 
    {
        var nome = Path.GetFileName(arquivo.FileName);
        arquivo.SaveAs(@"C:\Arquivos\" + nome);
    }
    return View(); 
}
    
25.03.2014 / 18:07
0

Using AJAX upload. There is a NuGet package that configures jQuery for this:

  

Install-Package jQuery.AjaxUpload

Example:

<script>

    // Variável que guarda seus arquivos
    var files;

    // Eventos que adicionam arquivos à variável de arquivos
    $('input[type=file]').on('change', prepareUpload);

    function prepareUpload(event)
    {
      files = event.target.files;
    }

    $('form').on('submit', uploadFiles);

    function uploadFiles(event)
    {
        event.stopPropagation(); // Parar todos os processamentos
        event.preventDefault();

        // Coloque aqui sua barra de progresso ou seu ícone de loading...

        // Crie um objeto FormData e adicione os arquivos
        var data = new FormData();

        $.each(files, function(key, value)
        {
            data.append(key, value);
        });

        $.ajax({
            url: 'SeuController/Upload',
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, // Não processar os arquivos
            contentType: false, 
            success: function(data, textStatus, jqXHR)
            {
                if(typeof data.error === 'undefined')
                {
                    // Sucesso, envia dados para controller
                    submitForm(event, data);
                }
                else
                {
                    // Erros
                    console.log('ERROS: ' + data.error);
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                // Mais erros
                console.log('ERRORS: ' + textStatus);
                // Desligue seu ícone de loading aqui
            }
        });
    }
</script>
    
25.03.2014 / 16:59
0

Configuration

You will have to make some settings before allowing the user to upload a large amount to your system:

  • upload limit size

  • maximum request time

Configuration example:

<system.web> 
    <httpRuntime maxRequestLength="157286400" executionTimeout="900" /> 
</system.web>

<system.webServer> 
    <security> 
        <requestFiltering> 
                <requestLimits maxAllowedContentLength="157286400" /> 
             </requestFiltering> 
    </security> 
</system.webServer>

Plugin to upload with progress

I recommend a plugin for uploading files that supports tracking the upload progress: link

p>

I've used this plugin on some projects, it's really good.

    
25.03.2014 / 19:06