/// <summary> /// Salva o arquivo na SYS_Arquivo, como arquivo temporário. /// </summary> /// <param name="bmp">Imagem a ser salva como arquivo</param> /// <returns>ID do arquivo gerado</returns> private static string SalvarArquivo(Bitmap bmp) { MemoryStream stream = new MemoryStream(); // Enviando email para Response. bmp.Save ( stream, System.Drawing.Imaging.ImageFormat.Jpeg ); stream.Seek(0, SeekOrigin.Begin); byte[] arquivo = stream.GetBuffer(); stream.Dispose(); string nome = DateTime.Now.ToString("yyyyMMdd-HH_mm_ss") + ".jpg"; SYS_Arquivo entArquivo = new SYS_Arquivo { arq_nome = nome , arq_tamanhoKB = arquivo.Length , arq_typeMime = "Image/jpeg" , arq_data = arquivo , arq_situacao = (byte)SYS_ArquivoSituacao.Temporario }; SYS_ArquivoBO.Save(entArquivo); return(entArquivo.arq_id.ToString()); }
/// <summary> /// Parâmetros para efetuar a exclusão lógica. /// </summary> protected override void ParamDeletar(QueryStoredProcedure qs, SYS_Arquivo entity) { Param = qs.NewParameter(); Param.DbType = DbType.Int32; Param.ParameterName = "@arq_id"; Param.Size = 4; Param.Value = entity.arq_id; qs.Parameters.Add(Param); if (!__STP_DELETE.Equals("STP_SYS_Arquivo_DELETE")) { Param = qs.NewParameter(); Param.DbType = DbType.Byte; Param.ParameterName = "@arq_situacao"; Param.Size = 1; Param.Value = 3; qs.Parameters.Add(Param); Param = qs.NewParameter(); Param.DbType = DbType.DateTime; Param.ParameterName = "@arq_dataAlteracao"; Param.Size = 8; Param.Value = DateTime.Now; qs.Parameters.Add(Param); } }
/// <summary> /// Deleta os arquivos temporários que foram criados /// </summary> private void DeletaArquivoTemporario() { try { if (!string.IsNullOrEmpty(hdnArqExcluir.Value) && (!hdnArqExcluir.Value.Equals(";"))) { int i = 1; while (i != 0) { if (!String.IsNullOrEmpty(hdnArqExcluir.Value.Split(';')[i])) { int id = Convert.ToInt32(hdnArqExcluir.Value.Split(';')[i]); SYS_Arquivo arq = new SYS_Arquivo { arq_id = id }; SYS_ArquivoBO.GetEntity(arq); SYS_ArquivoBO.ExcluiFisicamente(arq); i++; } else { i = 0; } } } } catch (Exception ex) { ApplicationWEB._GravaErro(ex); } }
/// <summary> /// Override do método alterar /// </summary> protected override void ParamAlterar(QueryStoredProcedure qs, SYS_Arquivo entity) { base.ParamAlterar(qs, entity); qs.Parameters.RemoveAt("@arq_dataCriacao"); qs.Parameters["@arq_dataAlteracao"].Value = DateTime.Now; }
/// <summary> /// Método sobrescrito para retirar o limite do timeout /// </summary> /// <param name="entity">Entidade</param> /// <returns>True em caso de sucesso</returns> public override bool Carregar(SYS_Arquivo entity) { QuerySelectStoredProcedure qs = new QuerySelectStoredProcedure(this.__STP_LOAD, this._Banco); qs.TimeOut = 0; try { ParamCarregar(qs, entity); qs.Execute(); if (qs.Return.Rows.Count > 0) { entity = this.DataRowToEntity(qs.Return.Rows[0], entity, false); return(true); } return(false); } catch (DbException err) { throw err; } catch (Exception err) { throw err; } finally { qs.Parameters.Clear(); } }
protected void btnAdicionarArquivo_Click(object sender, EventArgs e) { try { if (!fupArquivo.HasFile) { throw new ValidationException("É obrigatório selecionar um arquivo."); } SYS_Arquivo entArquivo = SYS_ArquivoBO.CriarAnexo(fupArquivo.PostedFile); entArquivo.arq_situacao = (byte)SYS_ArquivoSituacao.Temporario; SYS_ArquivoBO.Save(entArquivo, ApplicationWEB.TamanhoMaximoArquivo, ApplicationWEB.TiposArquivosPermitidos); entArquivo.IsNew = false; Label lblArqId = (Label)rptDocumentos.Items[VS_indiceArquivo].FindControl("lblArqId"); lblArqId.Text = entArquivo.arq_id.ToString(); Label lblArqNome = (Label)rptDocumentos.Items[VS_indiceArquivo].FindControl("lblArqNome"); lblArqNome.Text = entArquivo.arq_nome; HyperLink hplDocumento = (HyperLink)rptDocumentos.Items[VS_indiceArquivo].FindControl("hplDocumento"); hplDocumento.NavigateUrl = String.Format("~/FileHandler.ashx?file={0}", lblArqId.Text); hplDocumento.Text = entArquivo.arq_nome; hplDocumento.Visible = true; } catch (ValidationException ex) { lblMensagem.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta); } catch (Exception ex) { ApplicationWEB._GravaErro(ex); lblMensagem.Text = UtilBO.GetErroMessage(RetornaResource("ErroCarregar"), UtilBO.TipoMensagem.Erro); } }
/// <summary> /// Retorna a entidade pelo ID. /// </summary> /// <param name="arq_id">ID do arquivo.</param> /// <returns></returns> private SYS_Arquivo RetornaArquivoPorID(long arq_id) { SYS_Arquivo arquivo = new SYS_Arquivo { arq_id = arq_id }; arquivo = SYS_ArquivoBO.GetEntity(arquivo); return(arquivo); }
protected void btnAddAnexo_Click(object sender, ImageClickEventArgs e) { try { if (string.IsNullOrEmpty(txtTituloAnexo.Text) && fupAnexo.HasFile) { throw new ValidationException(GetGlobalResourceObject("Configuracao", "RelatorioAtendimento.Cadastro.TituloAnexoObrigatorio").ToString()); } if (fupAnexo.HasFile) { string nomeArquivoSemExtensao = Path.GetFileNameWithoutExtension(fupAnexo.PostedFile.FileName); string nomeArquivo = fupAnexo.PostedFile.FileName; int tamanhoArquivo = fupAnexo.PostedFile.ContentLength; string typeMime = fupAnexo.PostedFile.ContentType; Stream arquivo = CopiarArquivo(fupAnexo.PostedFile.InputStream); SYS_Arquivo arq = CriarAnexo(arquivo, nomeArquivo, tamanhoArquivo, typeMime); arq.arq_situacao = (byte)SYS_ArquivoSituacao.Temporario; SYS_ArquivoBO.Save(arq, ApplicationWEB.TamanhoMaximoArquivo, ApplicationWEB.TiposArquivosPermitidos); VS_arquivo = arq.arq_id; hplAnexo.Text = txtTituloAnexo.Text; hplAnexo.NavigateUrl = String.Format("~/FileHandler.ashx?file={0}", arq.arq_id); divAddAnexo.Visible = false; divAnexoAdicionado.Visible = true; } else { throw new ValidationException(GetGlobalResourceObject("Configuracao", "RelatorioAtendimento.Cadastro.SelecioneArquivo").ToString()); } } catch (ValidationException ex) { ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "ScrollToTop", "setTimeout('window.scrollTo(0,0);', 0);", true); lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta); } catch (Exception ex) { ApplicationWEB._GravaErro(ex); ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "ScrollToTop", "setTimeout('window.scrollTo(0,0);', 0);", true); lblMessage.Text = UtilBO.GetErroMessage(GetGlobalResourceObject("Configuracao", "RelatorioAtendimento.Cadastro.ErroAdicionarArquivo").ToString(), UtilBO.TipoMensagem.Erro); } }
/// <summary> /// Envia o conteúdo da imagem no response. /// </summary> /// <param name="sArq_id">ID do arquivo que representa a imagem.</param> /// <param name="context">HttpContext</param> private static void EnviaImagem(string sArq_id, HttpContext context) { long arq_id; if ((Int64.TryParse(sArq_id, out arq_id)) && (arq_id > 0)) { SYS_Arquivo arquivo = RetornaArquivoPorID(arq_id); if (!arquivo.IsNew) { try { byte[] bufferData = arquivo.arq_data; MemoryStream stream = new MemoryStream(bufferData); Image img = Image.FromStream(stream); context.Response.Clear(); context.Response.ContentType = arquivo.arq_typeMime; context.Response.BinaryWrite(bufferData); context.Response.Flush(); img.Dispose(); stream.Dispose(); } catch (Exception ex) { ApplicationWEB._GravaErro(ex); context.ApplicationInstance.CompleteRequest(); context.Server.ClearError(); } finally { context.ApplicationInstance.CompleteRequest(); } } } }
/// <summary> /// Salva o relatório de atendimento /// </summary> /// <param name="rea">Entidade do relatório de atendimento</param> /// <param name="lstGrupo">Lista de grupos</param> /// <param name="lstCargo">Lista de cargos</param> /// <param name="lstQuestionario">Lista de questionários</param> /// <param name="postedFile">Arquivo anexo</param> /// <returns></returns> public static bool Salvar(CLS_RelatorioAtendimento rea, List <CLS_RelatorioAtendimentoGrupo> lstGrupo, List <CLS_RelatorioAtendimentoCargo> lstCargo, List <CLS_RelatorioAtendimentoQuestionario> lstQuestionario, List <CLS_RelatorioAtendimentoPeriodo> lstRelatorioPeriodo, long arquivo, int TamanhoMaximoArquivo, string[] TiposArquivosPermitidos) { CLS_RelatorioAtendimentoDAO dao = new CLS_RelatorioAtendimentoDAO(); dao._Banco.Open(IsolationLevel.ReadCommitted); try { rea.arq_idAnexo = arquivo; if (arquivo > 0) { SYS_Arquivo arq = new SYS_Arquivo { arq_id = arquivo }; SYS_ArquivoBO.GetEntity(arq, dao._Banco); arq.arq_situacao = (byte)SYS_ArquivoSituacao.Ativo; SYS_ArquivoBO.Save(arq, dao._Banco); } bool isNew = rea.IsNew; if (!Save(rea, dao._Banco)) { throw new ValidationException("Erro ao salvar o relatório de atendimento."); } List <CLS_RelatorioAtendimentoQuestionario> lstQuestionarioBanco = CLS_RelatorioAtendimentoQuestionarioBO.SelectBy_rea_id(rea.rea_id); if (!isNew) { CLS_RelatorioAtendimentoCargoBO.DeleteBy_rea_id(rea.rea_id, dao._Banco); CLS_RelatorioAtendimentoGrupoBO.DeleteBy_rea_id(rea.rea_id, dao._Banco); //Exclui todos os questionários que não estão mais ligados ao relatório foreach (CLS_RelatorioAtendimentoQuestionario raq in lstQuestionarioBanco.Where(b => !lstQuestionario.Any(q => q.raq_id == b.raq_id && q.raq_situacao == (byte)CLS_RelatorioAtendimentoQuestionarioSituacao.Ativo && !q.IsNew))) { if (raq.emUso) { throw new ValidationException(string.Format("O questionário ({0}) possui lançamentos no relatório e não pode ser excluído.", raq.qst_titulo)); } raq.raq_situacao = (byte)CLS_RelatorioAtendimentoQuestionarioSituacao.Excluido; if (!CLS_RelatorioAtendimentoQuestionarioBO.Delete(raq, dao._Banco)) { throw new ValidationException("Erro ao remover questionário do relatório de atendimento."); } } } if (lstRelatorioPeriodo.Any()) { lstRelatorioPeriodo.ForEach(p => p.rea_id = rea.rea_id); CLS_RelatorioAtendimentoPeriodoBO.AtualizarPeriodos(lstRelatorioPeriodo, dao._Banco); } foreach (CLS_RelatorioAtendimentoGrupo rag in lstGrupo) { rag.rea_id = rea.rea_id; if (!CLS_RelatorioAtendimentoGrupoBO.Save(rag, dao._Banco)) { throw new ValidationException("Erro ao salvar grupo do relatório de atendimento."); } } foreach (CLS_RelatorioAtendimentoCargo rac in lstCargo) { rac.rea_id = rea.rea_id; if (!CLS_RelatorioAtendimentoCargoBO.Save(rac, dao._Banco)) { throw new ValidationException("Erro ao salvar cargo do relatório de atendimento."); } } foreach (CLS_RelatorioAtendimentoQuestionario raq in lstQuestionario.Where(q => q.raq_situacao == (byte)CLS_RelatorioAtendimentoQuestionarioSituacao.Ativo)) { raq.rea_id = rea.rea_id; if (raq.IsNew) { raq.raq_id = -1; } if (!CLS_RelatorioAtendimentoQuestionarioBO.Save(raq, dao._Banco)) { throw new ValidationException("Erro ao salvar questionário do relatório de atendimento."); } } } catch (Exception ex) { dao._Banco.Close(ex); throw; } finally { dao._Banco.Close(); } return(true); }
public static bool Salvar ( int tad_id, Guid uad_idSuperior, int esc_id, List <ACA_ArquivoArea> listDocumentos ) { //Inicio do processo de Registro no BD. ACA_ArquivoAreaDAO dao = new ACA_ArquivoAreaDAO(); //Abertura de BEGIN TRAN para Salvar Documentos. dao._Banco.Open(IsolationLevel.ReadCommitted); SYS_EntidadeDAO entDao = new SYS_EntidadeDAO(); entDao._Banco.Open(IsolationLevel.ReadCommitted); try { List <ACA_ArquivoArea> listaBanco; using (DataTable dtBanco = GetSelectBy_Id_Dre_Escola(tad_id, esc_id, uad_idSuperior, -1, true, false, dao._Banco)) { listaBanco = dtBanco.Rows.Count > 0 ? dtBanco.Rows.Cast <DataRow>().Select(p => dao.DataRowToEntity(p, new ACA_ArquivoArea())).ToList() : new List <ACA_ArquivoArea>(); } foreach (ACA_ArquivoArea entityArquivoArea in listDocumentos) { ACA_ArquivoAreaBO.Save(entityArquivoArea, dao._Banco); if (entityArquivoArea.arq_id > 0) { SYS_Arquivo arq = new SYS_Arquivo { arq_id = entityArquivoArea.arq_id }; SYS_ArquivoBO.GetEntity(arq, dao._Banco); arq.arq_situacao = (byte)SYS_ArquivoSituacao.Ativo; SYS_ArquivoBO.Save(arq, dao._Banco); } } bool teste = listaBanco.Where(p => !listDocumentos.Exists(q => q.aar_id == p.aar_id && q.tad_id == p.tad_id)) .ToList() .Aggregate(true, (deletou, doc) => deletou & Delete(doc, dao._Banco)); return(true); } catch (Exception err) { //Roolback da transação dao._Banco.Close(err); entDao._Banco.Close(err); throw; } finally { //Fechamento da transação if (dao._Banco.ConnectionIsOpen) { dao._Banco.Close(); } if (entDao._Banco.ConnectionIsOpen) { entDao._Banco.Close(); } } }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that /// implements the IHttpHandler interface. /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { if (!String.IsNullOrEmpty(context.Request.QueryString["file"])) { try { string sArq_id = context.Server.UrlDecode(context.Request.QueryString["file"]); long arq_id; if ((Int64.TryParse(sArq_id, out arq_id)) && (arq_id > 0)) { SYS_Arquivo arquivo = RetornaArquivoPorID(arq_id); if (!arquivo.IsNew) { try { context.Response.Clear(); context.Response.ClearHeaders(); context.Response.ClearContent(); context.Response.Buffer = false; context.Response.BufferOutput = false; context.Response.AppendHeader("Content-Disposition", "inline; filename=\"" + arquivo.arq_nome + "\""); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Length", arquivo.arq_tamanhoKB.ToString()); int length = 0; // Total bytes to read: long dataToRead = arquivo.arq_data.LongLength; byte[] bufferData = arquivo.arq_data; // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (context.Response.IsClientConnected) { context.Response.OutputStream.Write(bufferData, length, (size > dataToRead ? (int)dataToRead : size)); context.Response.Flush(); length += size; dataToRead = dataToRead - size; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { ApplicationWEB._GravaErro(ex); context.ApplicationInstance.CompleteRequest(); context.Server.ClearError(); } finally { context.Response.Close(); } } } } catch (Exception ex) { ApplicationWEB._GravaErro(ex); } } }
protected void btnConfirmar_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(hdnArq.Value) && string.IsNullOrEmpty(fupAnexo.FileName)) // Nao foi tirada nenhuma foto ou carregada. { if (imgAntiga.Visible) { __SessionWEB.PostMessages = UtilBO.GetErroMessage("Foto do aluno salva com sucesso.", UtilBO.TipoMensagem.Sucesso); Redireciona(); } else { lblMessage.Text = UtilBO.GetErroMessage("Nenhuma imagem foi carregada.", UtilBO.TipoMensagem.Alerta); } } else { try { // Se houver imagem capturada e escolhida para upload, salvará a que foi capturada. if (!string.IsNullOrEmpty(fupAnexo.FileName) && string.IsNullOrEmpty(hdnArq.Value)) { HttpPostedFile arquivo = fupAnexo.PostedFile; if (arquivo != null && arquivo.ContentLength > 0) { string fileNameApplication = System.IO.Path.GetFileName(arquivo.FileName); if (fileNameApplication != String.Empty) { if (fupAnexo.PostedFile.FileName.Substring(fupAnexo.PostedFile.FileName.Length - 3, 3).ToUpper() != "JPG") { throw new ValidationException("Foto tem que estar no formato \".jpg\"."); } SYS_Arquivo entArquivo = SYS_ArquivoBO.CriarAnexo(arquivo); entArquivo.arq_data = ACA_AlunoBO.RedimensionaFoto(entArquivo.arq_data, true); SYS_ArquivoBO.Save(entArquivo); VS_arq_id = entArquivo.arq_id; } } string tam = SYS_ParametroBO.ParametroValor(SYS_ParametroBO.eChave.TAMANHO_MAX_FOTO_PESSOA); if (!string.IsNullOrEmpty(tam)) { if (fupAnexo.PostedFile.ContentLength > Convert.ToInt32(tam) * 1000) { throw new ValidationException("Foto é maior que o tamanho máximo permitido."); } if (fupAnexo.PostedFile.FileName.Substring(fupAnexo.PostedFile.FileName.Length - 3, 3).ToUpper() != "JPG") { throw new ValidationException("Foto tem que estar no formato \".jpg\"."); } } } if (ACA_AlunoBO.SalvarFotoAluno(VS_alu_id, VS_arq_id)) { ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "alu_id: " + VS_alu_id + ", arq_id: " + VS_arq_id); __SessionWEB.PostMessages = UtilBO.GetErroMessage("Foto do aluno salva com sucesso.", UtilBO.TipoMensagem.Sucesso); DeletaArquivoTemporario(); Redireciona(); } else { lblMessage.Text = UtilBO.GetErroMessage("Não foi possível salvar a foto do aluno.", UtilBO.TipoMensagem.Erro); } } catch (ValidationException ex) { lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta); } catch (Exception ex) { ApplicationWEB._GravaErro(ex); lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar foto do aluno.", UtilBO.TipoMensagem.Erro); } } }
/// <summary> /// Método alterado para que o update não faça a alteração da data de criação /// </summary> /// <param name="entity"> Entidade ORC_Objetivo</param> /// <returns>true = sucesso | false = fracasso</returns> protected override bool Alterar(SYS_Arquivo entity) { __STP_UPDATE = "NEW_SYS_Arquivo_UPDATE"; return(base.Alterar(entity)); }
/// <summary> /// Método que faz a exclusão física. /// </summary> /// <param name="entity"> Entidade SYS_Arquivo</param> /// <returns>true = sucesso | false = fracasso</returns> public bool ExcluiFisicamente(SYS_Arquivo entity) { __STP_DELETE = "STP_SYS_Arquivo_DELETE"; return(base.Delete(entity)); }
/// <summary> /// Método alterado para que o delete não faça exclusão física e sim lógica (update). /// </summary> /// <param name="entity"> Entidade SYS_Arquivo</param> /// <returns>true = sucesso | false = fracasso</returns> public override bool Delete(SYS_Arquivo entity) { __STP_DELETE = "NEW_SYS_Arquivo_UPDATE_Situacao"; return(base.Delete(entity)); }