@page "/pageprojetoFileStream/{projetoCodigo:guid}"
@attribute [Authorize]
@rendermode InteractiveServer
@using System.ComponentModel.DataAnnotations
@using System.Text
@using System.Text.Encodings.Web
@using ConcursoProjetos.Service
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.WebUtilities
@using System;
@using System.IO;
@inject UserManager UserManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject ICandidatoService candidatoService
@inject IProjetoService projetoService
@inject IDocumentoService documentoService
@inject ITipoDocumentoService tipoDocumentoServico
@inject DialogService dialogService
@inject NotificationService notificationService
@inject NavigationManager Navigation
Cadastro de Projeto
Cadastro de Projeto
@if (_projeto != null && _candidato != null && _documentosModel != null)
{
Envio de Anexos
Tipo de Arquivo |
Escolher o Arquivo |
Status |
@foreach (var model in _documentosModel)
{
@model.TipoDocumento.Nome |
@if ((listaTipoDocumentoLoading.Count > 0) && listaTipoDocumentoLoading.Where(x => x.TipoDocumento.Id == model.TipoDocumento.Id).First().Uploading)
{
}
|
@if (model.Status)
{
}
else
{
}
|
}
}
@code {
bool popup;
Variant variant = Variant.Outlined;
bool Uploading = false;
bool UploadingLargeFile = false;
string LargeUploadMessage = "";
long UploadedBytes;
long TotalBytes;
async Task OnLargeFileInputFileChange(InputFileChangeEventArgs args, Candidato candidato, Projeto projeto, InputModelDocuments modelDocument)
{
Documento resultado;
// UploadedBytes = 0;
// Disable the file input field
//UploadingLargeFile = true;
var tipoDocumentoLoading = listaTipoDocumentoLoading.Where(x => x.TipoDocumento.Id == modelDocument.TipoDocumento.Id).First();
tipoDocumentoLoading.Uploading = true;
await InvokeAsync(StateHasChanged);
// calculate the chunks we have to send
TotalBytes = args.File.Size;
long percent = 0;
long chunkSize = 1000000;
long numChunks = TotalBytes / chunkSize;
long remainder = TotalBytes % chunkSize;
// get new filename with a bit of entropy
string justFileName = Path.GetFileNameWithoutExtension(args.File.Name);
string extension = Path.GetExtension(args.File.Name);
string newFileNameWithoutPath = $"Projeto_{projeto.Id}_{modelDocument.TipoDocumento.Nome}-{justFileName}-{DateTime.Now.Ticks.ToString()}{extension}";
//string projectPath = $"{Environment.CurrentDirectory}\\files\\{projeto.Id}";
string projectPath = projetoService.Path(projeto.Id);
string filename = $"{projectPath}\\{newFileNameWithoutPath}";
if (!Directory.Exists(projectPath))
{
Directory.CreateDirectory(projectPath);
GerarArquivoTextoParaProjeto(candidato, projeto, projectPath);
}
// Delete the file if it already exists in our \Files folder
if (File.Exists(filename))
{
File.Delete(filename);
}
// Open the input and output file streams
// using (var inStream = args.File.OpenReadStream(long.MaxValue))
// {
// using (var outStream = File.OpenWrite(filename))
// {
// while (UploadedBytes < TotalBytes)
// {
// var whatsLeft = TotalBytes - UploadedBytes;
// if (whatsLeft < chunkSize)
// chunkSize = remainder;
// // Read the next chunk
// var bytes = new byte[chunkSize];
// var buffer = new Memory(bytes);
// var read = await inStream.ReadAsync(buffer);
// // Write it
// await outStream.WriteAsync(bytes, 0, read);
// // Update our progress data and UI
// UploadedBytes += read;
// percent = UploadedBytes * 100 / TotalBytes;
// // Report progress with a string
// LargeUploadMessage = $"Uploading {args.File.Name} {percent}%";
// await InvokeAsync(StateHasChanged);
// }
// }
// }
var file = args.File;
var buffer = new byte[1 * 1024 * 1024]; // 80 KB buffer size 1 * 1024 * 1024
var totalRead = 0L;
using (var inStream = file.OpenReadStream(long.MaxValue))
using (var outStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
{
while (totalRead < file.Size)
{
var read = await inStream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
break;
await outStream.WriteAsync(buffer, 0, read);
totalRead += read;
// Atualize o progresso se necessário
percent = (int)((totalRead * 100) / file.Size);
LargeUploadMessage = $"Uploading {args.File.Name} {percent}%";
Console.WriteLine($"Uploading {file.Name} {percent}%");
}
}
LargeUploadMessage = "Upload Completo.";
//await ListFiles();
Documento documentoGravado = new()
{
Descricao = "",
ArquivoNomeOriginal = newFileNameWithoutPath,
ArquivoTamanhoBytes = TotalBytes,
ProjetoId = projeto.Id,
TipoDocumentoId = modelDocument.TipoDocumento.Id,
UploadCompleto = true
};
if (documentoGravado.Id > 0) // Alteração
{
documentoGravado.AtribuiId(modelDocument.DocumentoId);
}
resultado = documentoService.Gravar(documentoGravado);
//UploadingLargeFile = false;
tipoDocumentoLoading.Uploading = false;
bool uploadIncompletosAntes = _documentosModel.Any(x => !x.Status);
AtualizarListaDocumentos();
bool uploadIncompletosDepois = _documentosModel.Any(x => !x.Status);
if (uploadIncompletosAntes && !uploadIncompletosDepois)
{
//"Seu projeto foi enviado com sucesso.Caso deseje realizar alguma alteração, o projeto estará listado na área 'meus projetos'"
await dialogService.Alert("Seu projeto foi enviado com sucesso.
Caso deseje realizar alguma alteração, o projeto estará listado na área 'Meus Projetos'.",
"Projeto Enviado",
new AlertOptions() { OkButtonText = "Ok" });
Navigation.NavigateTo($"/gestaoprojetos");
return;
}
if (!uploadIncompletosAntes)
{
// "Deseja alterar mais algum anexo enviado?
// sim => permanece na tela
// não => exibe mensagem anterior "primeira vez que ele completa."
bool? result = await dialogService.Confirm("Deseja alterar mais algum anexo enviado?",
"Anexo Enviado com Sucesso",
new ConfirmOptions() { OkButtonText = "Yes", CancelButtonText = "No" });
if (result != true)
{
await dialogService.Alert("Seu projeto foi enviado com sucesso.
Caso deseje realizar alguma alteração, o projeto estará listado na área 'Meus Projetos'",
"Projeto Enviado",
new AlertOptions() { OkButtonText = "Ok" });
Navigation.NavigateTo($"/gestaoprojetos");
return;
}
return;
}
}
private void GerarArquivoTextoParaProjeto(Candidato candidato, Projeto projeto, string path)
{
string saudacao = $@"
Candidado:
Nome......: {candidato.NomeCompleto}
E-mail....: {candidato.Email}
Telefone..: {candidato.Email}
";
if (candidato.TipoPessoa) // Representa empresa
{
saudacao += $@"
Empresa:
Nome....: {candidato.EmpresaRazaoSocial}
E-mail..: {candidato.EmpresaEmail}
Telefone..: {candidato.EmpresaTelefone}";
}
saudacao += $@"
Projeto '{projeto.Nome}':
Responsável.....: {projeto.ResponsavelTecnicoNomeCompleto}
E-mail...: {projeto.ResponsavelTecnicoEmail}
Telefone.: {projeto.ResponsavelTecnicoTelefone}";
string fullPath = Path.Combine(path, "config.txt");
File.WriteAllText(fullPath, saudacao);
}
[Parameter]
public Guid projetoCodigo { get; set; }
private Candidato? _candidato;
private Projeto? _projeto;
private IEnumerable? _documentos;
private IEnumerable? _documentosModel;
private string _mensagem = "Loading...";
private long candidatoId;
private string rotuloBotaoGravar = "Enviar";
//private long projetoId = 5;
List listaTipoDocumentoLoading = new();
[SupplyParameterFromForm]
private InputModel Input { get; set; } = new();
private List listaDeUnidades = Enumerable.Range(2, 31).ToList();
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
var identityUser = await UserManager.GetUserAsync(user);
if (identityUser != null)
{
_candidato = candidatoService.ObterPorUserID(identityUser.Id);
}
}
if (projetoCodigo != Guid.Empty)
{
_projeto = projetoService.ObterPorCodigo(projetoCodigo);
_documentos = documentoService.Listar(_projeto.Id);
AtualizarModel(_projeto);
rotuloBotaoGravar = "Alterar Dados do Projeto Cadastrado";
}
AtualizarListaDocumentos();
var listaTipo = tipoDocumentoServico.Listar();
foreach (var tipo in listaTipo)
listaTipoDocumentoLoading.Add(new ModelTipoDocumento { TipoDocumento = tipo, Uploading = false });
}
private void AtualizarModel(Projeto projeto)
{
Input.Id = projeto.Id;
Input.Nome = projeto.Nome;
Input.NumeroUnidades = projeto.NumeroUnidades;
Input.ResponsavelTecnicoCpf = projeto.ResponsavelTecnicoCpf;
Input.ResponsavelTecnicoNomeCompleto = projeto.ResponsavelTecnicoNomeCompleto;
Input.ResponsavelTecnicoTelefone = projeto.ResponsavelTecnicoTelefone;
Input.ResponsavelTecnicoEmail = projeto.ResponsavelTecnicoEmail;
}
private async Task OnSubmit(InputModel model)
{
Projeto resultado;
Projeto projeto = new(_candidato.Id)
{
Codigo = Guid.NewGuid(),
Nome = Input.Nome,
NumeroUnidades = Input.NumeroUnidades,
ResponsavelTecnicoCpf = Input.ResponsavelTecnicoCpf.Replace(".", "").Replace("-", ""),
ResponsavelTecnicoNomeCompleto = Input.ResponsavelTecnicoNomeCompleto,
ResponsavelTecnicoTelefone = Input.ResponsavelTecnicoTelefone,
ResponsavelTecnicoEmail = Input.ResponsavelTecnicoEmail
};
if (_projeto != null) // Alteração
{
projeto.AtribuiId(_projeto.Id);
resultado = projetoService.Alterar(projeto);
}
else // Inclusão
{
resultado = projetoService.Adicionar(projeto);
rotuloBotaoGravar = "Alterar Dados do Projeto Cadastrado";
}
if (resultado != null)
{
_projeto = resultado;
projetoCodigo = resultado.Codigo;
MontarModelDocuments();
NotificationMessage message = new NotificationMessage
{
Severity = NotificationSeverity.Info,
Summary = "Projeto gravado com sucesso.",
Detail = "",
Duration = 3000
};
notificationService.Notify(message);
}
StateHasChanged();
}
private async void OnInvalidSubmit(FormInvalidSubmitEventArgs args)
{
//Log("InvalidSubmit", JsonSerializer.Serialize(args, new JsonSerializerOptions() { WriteIndented = true }));
}
private void AtualizarListaDocumentos()
{
if (_projeto == null || _projeto.Id <= 0)
return;
_documentos = documentoService.Listar(_projeto.Id);
MontarModelDocuments();
StateHasChanged();
}
private void MontarModelDocuments()
{
List resultado = new();
var listaTipo = tipoDocumentoServico.Listar();
foreach (TipoDocumento tipo in listaTipo)
{
long documentoId = 0;
bool status = false;
if (_documentos != null && _documentos.Count() > 0)
{
var ProjetoPossuiDocumento = _documentos.Where(d => d.TipoDocumentoId == tipo.Id).SingleOrDefault();
if (ProjetoPossuiDocumento != null)
{
documentoId = ProjetoPossuiDocumento.Id;
status = true;
}
}
resultado.Add(new InputModelDocuments
{
DocumentoId = documentoId,
TipoDocumento = tipo,
Status = status
});
}
_documentosModel = resultado;
}
private sealed class InputModel
{
public long Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 5)]
[Display(Name = "Nome do Projeto")]
public string Nome { get; set; } = "";
[Required]
[Range(2, 32, ErrorMessage = "O valor deve estar entre 2 e 32.")]
[Display(Name = "Número de Unidades Habitacionais por Pavimento")]
public int NumeroUnidades { get; set; } = 2;
[Required]
[MaxLength(100)]
[Display(Name = "Nome do Responsável Técnico da Empresa")]
public string ResponsavelTecnicoNomeCompleto { get; set; }
[Required]
[MaxLength(100)]
[EmailAddress]
[Display(Name = "E-mail do Responsável Técnico da Empresa")]
public string ResponsavelTecnicoEmail { get; set; }
[Required]
[MaxLength(14)]
[Display(Name = "CPF do Responsável Técnico da Empresa")]
public string ResponsavelTecnicoCpf { get; set; }
[Required]
[MaxLength(20)]
[Display(Name = "Telefone do Responsável Técnico da Empresa")]
public string ResponsavelTecnicoTelefone { get; set; }
}
private sealed class InputModelDocuments
{
public long DocumentoId { get; set; }
public TipoDocumento TipoDocumento { get; set; }
//public DateTime DataInclusao { get; set; }
public bool Status { get; set; }
}
private sealed class ModelTipoDocumento
{
public TipoDocumento TipoDocumento { get; set; }
public bool Uploading { get; set; }
}
}