private void decodeXML() { using (var conexion = new DataModelFE()) { List <WSRecepcionPOST> lista = conexion.WSRecepcionPOST. Where(x => x.comprobanteXml.Substring(0, 3) == "PD9").ToList(); foreach (var item in lista) { WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(item.clave); if (dato.comprobanteXml != null) { dato.comprobanteXml = XMLUtils.base64Decode(dato.comprobanteXml); } if (dato.comprobanteRespXML != null) { if (dato.comprobanteRespXML.Substring(0, 3) == "PD9") { dato.comprobanteRespXML = XMLUtils.base64Decode(dato.comprobanteRespXML); } } conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); } } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { // se declara el objeto a insertar ConfiguracionCorreo dato = new ConfiguracionCorreo(); //llena el objeto con los valores de la pantalla dato.codigo = e.NewValues["codigo"] != null ? e.NewValues["codigo"].ToString() : null; //busca el objeto dato = conexion.ConfiguracionCorreo.Find(dato.codigo); if (e.NewValues["password"] != null) { dato.password = e.NewValues["password"] != null?Ale5Util.Encriptar(e.NewValues["password"].ToString()) : null; } dato.codigo = e.NewValues["codigo"] != null ? e.NewValues["codigo"].ToString() : null; dato.ssl = e.NewValues["ssl"] != null ? e.NewValues["ssl"].ToString() : null; dato.port = e.NewValues["port"] != null ? e.NewValues["port"].ToString().ToUpper() : null; dato.user = e.NewValues["user"] != null ? e.NewValues["user"].ToString(): null; dato.host = e.NewValues["host"] != null ? e.NewValues["host"].ToString() : null; dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); ((ASPxGridView)sender).JSProperties["cpUpdatedMessage"] = "Los datos se modificaron correctamente, puede continuar."; } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { EmisorReceptorIMEC dato = new EmisorReceptorIMEC(); dato.identificacion = e.NewValues["identificacion"] != null ? e.NewValues["identificacion"].ToString().ToUpper() : null; //busca el objeto dato = conexion.EmisorReceptorIMEC.Find(dato.identificacion); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); } } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { // se declara el objeto a insertar Ubicacion dato = new Ubicacion(); //llena el objeto con los valores de la pantalla dato.codigo = Int32.Parse(e.NewValues["codigo"].ToString()); //busca el objeto dato = conexion.Ubicacion.Find(dato.codigo); dato.codProvincia = e.NewValues["codProvincia"] != null ? e.NewValues["codProvincia"].ToString().ToUpper() : null; dato.codCanton = e.NewValues["codCanton"] != null ? e.NewValues["codCanton"].ToString().ToUpper() : null; dato.codDistrito = e.NewValues["codDistrito"] != null ? e.NewValues["codDistrito"].ToString().ToUpper() : null; dato.codBarrio = e.NewValues["codBarrio"] != null ? e.NewValues["codBarrio"].ToString().ToUpper() : null; dato.nombreProvincia = e.NewValues["nombreProvincia"] != null ? e.NewValues["nombreProvincia"].ToString().ToUpper() : null; dato.nombreCanton = e.NewValues["nombreCanton"] != null ? e.NewValues["nombreCanton"].ToString().ToUpper() : null; dato.nombreDistrito = e.NewValues["nombreDistrito"] != null ? e.NewValues["nombreDistrito"].ToString().ToUpper() : null; dato.nombreBarrio = e.NewValues["nombreBarrio"] != null ? e.NewValues["nombreBarrio"].ToString().ToUpper() : null; dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { // se declara el objeto a insertar ConsecutivoDocElectronico dato = new ConsecutivoDocElectronico(); //llena el objeto con los valores de la pantalla dato.emisor = e.NewValues["emisor"] != null ? e.NewValues["emisor"].ToString().ToUpper() : null; dato.sucursal = e.NewValues["sucursal"] != null ? e.NewValues["sucursal"].ToString().PadLeft(3, '0') : "001"; dato.caja = e.NewValues["caja"] != null ? e.NewValues["caja"].ToString().PadLeft(3, '0') : "00001"; dato.tipoDocumento = e.NewValues["tipoDocumento"] != null ? e.NewValues["tipoDocumento"].ToString() : "01"; //busca el objeto object[] key = new object[] { dato.emisor, dato.sucursal, dato.caja, dato.tipoDocumento }; dato = conexion.ConsecutivoDocElectronico.Find(key); dato.digitoVerificador = e.NewValues["digitoVerificador"].ToString(); dato.consecutivo = e.NewValues["consecutivo"] != null?long.Parse(e.NewValues["consecutivo"].ToString()) : 0; dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { // se declara el objeto a insertar ProductoImpuesto dato = new ProductoImpuesto(); //llena el objeto con los valores de la pantalla dato.idProducto = e.NewValues["idProducto"] != null?int.Parse(e.NewValues["idProducto"].ToString()) : 0; dato.tipoImpuesto = e.NewValues["tipoImpuesto"] != null ? e.NewValues["tipoImpuesto"].ToString().ToUpper() : null; object[] key = new object[] { dato.idProducto, dato.tipoImpuesto }; //busca el objeto dato = conexion.ProductoImpuesto.Where(x => x.idProducto == dato.idProducto).Where(x => x.tipoImpuesto == dato.tipoImpuesto).FirstOrDefault(); dato.porcentaje = e.NewValues["porcentaje"] != null?decimal.Parse(e.NewValues["porcentaje"].ToString()) : 0; dato.emisor = Session["emisor"].ToString(); dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); ((ASPxGridView)sender).JSProperties["cpUpdatedMessage"] = "Los datos se modificaron correctamente, puede continuar."; } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { //busca el objeto Plan dato = conexion.Plan.Find(e.NewValues["emisor"].ToString()); dato.plan = e.NewValues["plan"] != null ? e.NewValues["plan"].ToString().ToUpper() : null; dato.cantidadDocEmitido = e.NewValues["cantidadDocEmitido"] != null?int.Parse(e.NewValues["cantidadDocEmitido"].ToString()) : 0; dato.cantidadDocPlan = e.NewValues["cantidadDocPlan"] != null?int.Parse(e.NewValues["cantidadDocPlan"].ToString()) : 0; dato.fechaInicio = e.NewValues["fechaInicio"] != null?DateTime.Parse(e.NewValues["fechaInicio"].ToString()) : Date.DateTimeNow(); dato.fechaFin = e.NewValues["fechaFin"] != null?DateTime.Parse(e.NewValues["fechaFin"].ToString()) : Date.DateTimeNow(); dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// guardar el consecutivo utilizado /// </summary> protected void actualizarConsecutivo() { //genera el consecutivo del documento string emisor = Session["emisor"].ToString(); string sucursal = ConsecutivoDocElectronico.DEFAULT_SUCURSAL;; string caja = ConsecutivoDocElectronico.DEFAULT_CAJA; string tipoDocumento = ""; if (this.cmbMensaje.Value.Equals(TipoConsecutivo.ACEPTADO.ToString())) { tipoDocumento = TipoConsecutivo.DOCUMENTO_ACEPTADO; } else { if (this.cmbMensaje.Value.Equals(TipoConsecutivo.RECHAZADO_PARCIAL.ToString())) { tipoDocumento = TipoConsecutivo.DOCUMENTO_RECHAZADO_PARCIAL; } else { tipoDocumento = TipoConsecutivo.DOCUMENTO_RECHAZADO; } } using (var conexion = new DataModelFE()) { object[] key = new object[] { emisor, sucursal, caja, tipoDocumento }; ConsecutivoDocElectronico consecutivo = conexion.ConsecutivoDocElectronico.Find(key); if (consecutivo != null) { consecutivo.consecutivo += 1; conexion.Entry(consecutivo).State = EntityState.Modified; conexion.SaveChanges(); } } }
protected async void btnActualizar_Click(object sender, EventArgs e) { try { using (var conexion = new DataModelFE()) { EmisorReceptorIMEC emisor = (EmisorReceptorIMEC)Session["elEmisor"]; string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); string clave = Session["clave"].ToString(); string respuestaJSON = await Services.getRecepcion(config.token, clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON); if (!string.IsNullOrWhiteSpace(respuesta.respuestaXml)) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); using (var conexionWS = new DataModelFE()) { WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(clave); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Session["usuario"].ToString(); //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; dato.comprobanteRespXML = respuestaXML; if (mensajeHacienda.montoTotalFactura == 0) { string xml = XMLUtils.base64Decode(dato.comprobanteXml); dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml)); dato.montoTotalFactura = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml)); } conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); Session["indEstado"] = dato.indEstado; } } else { if (respuesta.indEstado.Equals("recibido")) { using (var conexionWS = new DataModelFE()) { WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(clave); dato.indEstado = 8 /*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } this.alertMessages.Attributes["class"] = "alert alert-info"; this.alertMessages.InnerText = String.Format("Documento eléctronico se encuentra RECIBIDO pero aún pendiente de ser ACEPTADO"); } } } } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) { try { using (var conexion = new DataModelFE()) { //se declara el objeto a insertar EmisorReceptorIMEC dato = new EmisorReceptorIMEC(); //llena el objeto con los valores de la pantalla dato.identificacionTipo = e.NewValues["identificacionTipo"].ToString(); dato.identificacion = e.NewValues["identificacion"].ToString(); dato.nombre = e.NewValues["nombre"].ToString(); dato.nombreComercial = e.NewValues["nombreComercial"] != null ? e.NewValues["nombreComercial"].ToString().ToUpper() : null; if (e.NewValues["telefono"] != null) { //dato.telefonoCodigoPais = e.NewValues["telefonoCodigoPais"].ToString(); dato.telefonoCodigoPais = "506"; dato.telefono = e.NewValues["telefono"].ToString(); } dato.correoElectronico = e.NewValues["correoElectronico"] != null ? e.NewValues["correoElectronico"].ToString() : null; if (e.NewValues["fax"] != null) { //dato.faxCodigoPais = e.NewValues["faxCodigoPais"].ToString(); dato.faxCodigoPais = "506"; dato.fax = e.NewValues["fax"].ToString(); } ASPxPageControl tabs = (ASPxPageControl)ASPxGridView1.FindEditFormTemplateControl("pageControl"); ASPxFormLayout form = (ASPxFormLayout)tabs.FindControl("formLayoutUbicacion"); /* PROVINCIA */ ASPxComboBox comboProvincia = (ASPxComboBox)form.FindControl("cmbProvincia"); /* CANTON */ ASPxComboBox comboCanton = (ASPxComboBox)form.FindControl("cmbCanton"); /* DISTRITO */ ASPxComboBox comboDistrito = (ASPxComboBox)form.FindControl("cmbDistrito"); /* BARRIO */ ASPxComboBox comboBarrio = (ASPxComboBox)form.FindControl("cmbBarrio"); ASPxMemo otraSena = (ASPxMemo)form.FindControl("txtOtraSenas"); dato.provincia = comboProvincia.Value.ToString(); dato.canton = comboCanton.Value.ToString(); dato.distrito = comboDistrito.Value.ToString(); dato.barrio = comboBarrio.Value.ToString(); dato.otraSena = otraSena.Text; dato.estado = e.NewValues["estado"].ToString(); dato.usuarioCreacion = Session["usuario"].ToString(); dato.fechaCreacion = Date.DateTimeNow(); //agregar cliente var existeEmisor = conexion.EmisorReceptorIMEC.Find(dato.identificacion); if (existeEmisor == null) { conexion.EmisorReceptorIMEC.Add(dato); } else { conexion.Entry(dato).State = EntityState.Modified; } conexion.SaveChanges(); //asociar cliente object[] key = new object[] { Session["emisor"].ToString(), dato.identificacion }; var cliente = conexion.Cliente.Find(key); if (cliente == null) { cliente = new Cliente(); cliente.emisor = Session["emisor"].ToString(); cliente.receptor = dato.identificacion; conexion.Cliente.Add(cliente); conexion.SaveChanges(); } //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); ((ASPxGridView)sender).JSProperties["cpUpdatedMessage"] = "Los datos se agregaron correctamente, puede continuar."; } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
public async Task <IHttpActionResult> respuestamesajehacienda(string clave) { using (var conexion = new DataModelFE()) { WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave); if (dato.montoTotalFactura > 0) { return(Ok(new WSDomain.WSRespuestaGET(dato))); } else { EmisorReceptorIMEC elEmisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN); string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = elEmisor.usernameOAuth2; config.password = elEmisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); string respuestaJSON = await ServicesHacienda.getRecepcion(config.token, clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.EncondeXML.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); dato = conexion.WSRecepcionPOST.Find(clave); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); return(Ok(new WSRespuestaGET(dato))); } else { if (respuesta.indEstado.ToLower().Equals("recibido")) { using (var conexionWS = new DataModelFE()) { dato = conexionWS.WSRecepcionPOST.Find(clave); dato.indEstado = 8 /*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); return(Ok(new WSRespuestaGET(dato))); } } } } } } return(NotFound()); }
public static string enviarProforma(ProformaElectronica documento, string tipoDocumento, string usuario) { String responsePostProforma = ""; try { string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documento); using (var conexion = new DataModelFE()) { WSDomain.WSRecepcionPOSTProforma trama = new WSDomain.WSRecepcionPOSTProforma(); trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile); trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00", System.Globalization.CultureInfo.InvariantCulture); string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile); trama.emisor.tipoIdentificacion = emisorIdentificacion.Substring(0, 2); trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2); trama.emisorTipo = trama.emisor.tipoIdentificacion; trama.emisorIdentificacion = trama.emisor.numeroIdentificacion; string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile); if (!string.IsNullOrWhiteSpace(receptorIdentificacion)) { trama.receptor.tipoIdentificacion = receptorIdentificacion.Substring(0, 2); trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2); } else { trama.receptor.tipoIdentificacion = "99"; trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile); } trama.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xmlFile)); trama.montoTotalFactura = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xmlFile)); trama.receptorTipo = trama.receptor.tipoIdentificacion; trama.receptorIdentificacion = trama.receptor.numeroIdentificacion; trama.tipoDocumento = tipoDocumento; trama.consecutivoReceptor = null; trama.comprobanteXml = xmlFile; trama.indEstado = 1; WSRecepcionPOSTProforma tramaExiste = conexion.WSRecepcionPOSTProforma.Find(trama.clave); if (tramaExiste != null) {// si existe trama.fechaModificacion = Date.DateTimeNow(); trama.usuarioModificacion = usuario; trama.indEstado = 1; trama.cargarEmisorReceptor(); conexion.Entry(tramaExiste).State = EntityState.Modified; } else//si no existe { trama.fechaCreacion = Date.DateTimeNow(); trama.usuarioCreacion = usuario; trama.cargarEmisorReceptor(); conexion.WSRecepcionPOSTProforma.Add(trama); } conexion.SaveChanges(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } return(responsePostProforma); }
//Colocar el metodo del botón protected void btnEnviar_Click(object sender, EventArgs e) { try { //Si el captcha es correcto realizar lo del envio de datos if (Captcha.IsValid == true && txtUserName.Text != "") { //Genera posible contraseña Usuario usuario = new Usuario(); usuario.codigo = this.txtUserName.Text; usuario.correo = this.txtCorreo.Text; using (var conexion = new DataModelFE()) { usuario = conexion.Usuario.Where(x => x.codigo == usuario.codigo && x.correo == usuario.correo).FirstOrDefault(); if (usuario != null) { string password = Utilidades.generarContrasena(10); usuario.contrasena = MD5Util.getMd5Hash(password); usuario.intentos = 0; usuario.estado = Estado.ACTIVO.ToString(); conexion.Entry(usuario).State = EntityState.Modified; conexion.SaveChanges(); usuario.contrasena = password; if (enviaCorreoCambioContrasena(usuario)) { this.alertMessages.Attributes["class"] = "alert alert-info"; this.alertMessages.InnerText = "La nueva contraseña ha sido enviada a la cuenta registrada"; } else { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = "En este momento tenemos problemas en enviar el correo, favor intente dentro de unos minutos"; } } else { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = "No existe un usuario con la información suministrada"; } } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex); this.alertMessages.Attributes["class"] = "alert alert-danger"; } }
public async Task <IHttpActionResult> respuestamesajehacienda(string clave) { try { using (var conexion = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave); if (dato != null) { if (dato.montoTotalFactura == 0) { return(Ok(new Models.WS.WSRespuestaGET(dato))); } else { string respuestaJSON = await ServicesHacienda.getRecepcion(await this.getToken(), clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); //dato = conexion.WSRecepcionPOST.Where(x=>x.clave==clave).FirstOrDefault(); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); return(Ok(new Models.WS.WSRespuestaGET(dato))); } else { if (respuesta.indEstado.ToLower().Equals("recibido")) { using (var conexionWS = new DataModelFE()) { dato = conexionWS.WSRecepcionPOST.Find(clave); dato.indEstado = 8 /*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); return(Ok(new Models.WS.WSRespuestaGET(dato))); } } } } } } } return(NotFound()); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. //return fullErrorMessage; return(Ok(fullErrorMessage)); } catch (Exception ex) { return(Ok(ex.Message)); } }
protected async void btnEnviar_Click(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(this.txtNumConsecutivoReceptor.Text)) { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = "Número de consecutivo requerido"; return; } Thread.CurrentThread.CurrentCulture = Utilidades.getCulture(); MensajeReceptor dato = new MensajeReceptor(); dato.clave = this.txtClave.Text; dato.fechaEmisionDoc = txtFechaEmisor.Text; dato.numeroCedulaEmisor = this.txtNumCedEmisor.Text; dato.numeroCedulaReceptor = this.txtNumCedReceptor.Text; dato.mensajeDetalle = this.txtDetalleMensaje.Text; dato.mensaje = int.Parse(this.cmbMensaje.Value.ToString()); dato.numeroConsecutivoReceptor = this.txtNumConsecutivoReceptor.Text; dato.montoTotalImpuesto = decimal.Parse(this.txtMontoTotalImpuesto.Text); dato.montoTotalFactura = decimal.Parse(this.txtTotalFactura.Text); EmisorReceptorIMEC elEmisor = (EmisorReceptorIMEC)Session["elEmisor"]; string xml = EncodeXML.XMLUtils.getXMLFromObject(dato); //string xmlSigned = FirmaXML.getXMLFirmadoWeb(xml, elEmisor.llaveCriptografica, elEmisor.claveLlaveCriptografica); //Habilitar solo cuando funcione el servicio string responsePost = await Services.enviarMensajeReceptor(xml, elEmisor, Session["receptor.tipoIdentificacion"].ToString()); if (responsePost.Equals("Success")) { this.alertMessages.Attributes["class"] = "alert alert-info"; this.alertMessages.InnerText = "Los datos fueron enviados correctamente!!!"; using (var conexion = new DataModelFE()) { elEmisor.consecutivo += 1; conexion.Entry(elEmisor).State = EntityState.Modified; conexion.SaveChanges(); Session["elEmisor"] = elEmisor; } string correo = Session["receptor.CorreoElectronico"].ToString(); if (!string.IsNullOrWhiteSpace(correo)) { string nombre = Session["receptor.Nombre"].ToString(); Utilidades.sendMail(Session["emisor"].ToString(), correo, string.Format("{0} - {1}", dato.clave.Substring(21, 20), nombre), Utilidades.mensageGenerico(), "Factura Electrónica", xml, dato.clave.Substring(21, 20), dato.clave, null); } } else { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = String.Format("Factura #{0} con errores.", dato.clave); } this.guardarDocumentoReceptor(); this.alertMessages.Attributes["class"] = "alert alert-info"; this.alertMessages.InnerText = "Los datos se guardaron correctamente!!!"; //Limpiar la página //this.CleanControl(this.Controls); Response.Redirect("~/Pages/Facturacion/FrmCargarXMLReceptor.aspx"); } catch (Exception ex) { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { // se declara el objeto a insertar Empresa dato = new Empresa(); //llena el objeto con los valores de la pantalla dato.codigo = e.NewValues["codigo"] != null ? e.NewValues["codigo"].ToString() : null; //busca el objeto dato = conexion.Empresa.Find(dato.codigo); dato.idioma = e.NewValues["idioma"] != null ? e.NewValues["idioma"].ToString().ToUpper() : null; dato.tipoImpresion = e.NewValues["tipoImpresion"] != null ? e.NewValues["tipoImpresion"].ToString().ToUpper() : null; dato.leyenda = e.NewValues["leyenda"] != null ? e.NewValues["leyenda"].ToString().ToUpper() : null; dato.descripcion = e.NewValues["descripcion"] != null ? e.NewValues["descripcion"].ToString().ToUpper() : null; dato.medioPago = e.NewValues["medioPago"].ToString(); dato.condicionVenta = e.NewValues["condicionVenta"].ToString(); dato.plazoCredito = int.Parse(e.NewValues["plazoCredito"].ToString()); dato.moneda = e.NewValues["moneda"].ToString(); dato.estado = e.NewValues["estado"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); if (Session["logo"] != null) { dato.logo = (byte[])Session["logo"]; } //modifica objeto conexion.Entry(dato).State = EntityState.Modified; conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // conexion.Empresa.Remove(conexion.Empresa.Last() ); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// actualiza un registro /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { try { using (var conexion = new DataModelFE()) { //busca el objeto Producto dato = conexion.Producto.Find(long.Parse(e.NewValues["id"].ToString())); dato.codigo = e.NewValues["codigo"] != null ? e.NewValues["codigo"].ToString() : null; dato.precioVenta1 = e.NewValues["precioVenta1"] != null?decimal.Parse(e.NewValues["precioVenta1"].ToString()) : 0; dato.emisor = Session["emisor"].ToString(); dato.tipo = e.NewValues["tipo"] != null ? e.NewValues["tipo"].ToString().ToUpper() : null; dato.tipoServMerc = e.NewValues["tipoServMerc"] != null ? e.NewValues["tipoServMerc"].ToString().ToUpper() : null; dato.unidadMedida = e.NewValues["unidadMedida"] != null ? e.NewValues["unidadMedida"].ToString() : null; dato.descripcion = e.NewValues["descripcion"] != null ? e.NewValues["descripcion"].ToString().ToUpper() : null; dato.orden = e.NewValues["orden"] != null?int.Parse(e.NewValues["orden"].ToString()) : 0; dato.estado = e.NewValues["estado"].ToString(); dato.aplicaIV = e.NewValues["aplicaIV"].ToString(); dato.aplicaIS = e.NewValues["aplicaIS"].ToString(); dato.cargaAutFactura = e.NewValues["cargaAutFactura"].ToString(); dato.usuarioModificacion = Session["usuario"].ToString(); dato.fechaModificacion = Date.DateTimeNow(); //modifica objeto conexion.Entry(dato).State = EntityState.Modified; if (dato.aplicaIV.Equals(Confirmacion.SI.ToString())) { ProductoImpuesto impuesto = conexion.ProductoImpuesto.Where(x => x.idProducto == dato.id).Where(x => x.tipoImpuesto == ProductoImpuesto.IMPUESTO_VENTAS).FirstOrDefault(); if (impuesto == null) { impuesto = new ProductoImpuesto(); impuesto.idProducto = dato.id; impuesto.tipoImpuesto = ProductoImpuesto.IMPUESTO_VENTAS; impuesto.porcentaje = 13; impuesto.emisor = Session["emisor"].ToString(); impuesto.estado = Estado.ACTIVO.ToString(); impuesto.usuarioCreacion = Session["usuario"].ToString(); impuesto.fechaCreacion = Date.DateTimeNow(); conexion.ProductoImpuesto.Add(impuesto); } } else { ProductoImpuesto impuesto = conexion.ProductoImpuesto.Where(x => x.idProducto == dato.id).Where(x => x.tipoImpuesto == ProductoImpuesto.IMPUESTO_VENTAS).FirstOrDefault(); if (impuesto != null) { conexion.ProductoImpuesto.Remove(impuesto); } } if (dato.aplicaIS.Equals(Confirmacion.SI.ToString())) { ProductoImpuesto impuesto = conexion.ProductoImpuesto.Where(x => x.idProducto == dato.id).Where(x => x.tipoImpuesto == ProductoImpuesto.IMPUESTO_SERVICIO).FirstOrDefault(); if (impuesto == null) { impuesto = new ProductoImpuesto(); impuesto.idProducto = dato.id; impuesto.tipoImpuesto = ProductoImpuesto.IMPUESTO_SERVICIO; impuesto.porcentaje = 10; impuesto.emisor = Session["emisor"].ToString(); impuesto.estado = Estado.ACTIVO.ToString(); impuesto.usuarioCreacion = Session["usuario"].ToString(); impuesto.fechaCreacion = Date.DateTimeNow(); conexion.ProductoImpuesto.Add(impuesto); } } else { ProductoImpuesto impuesto = conexion.ProductoImpuesto.Where(x => x.idProducto == dato.id).Where(x => x.tipoImpuesto == ProductoImpuesto.IMPUESTO_SERVICIO).FirstOrDefault(); if (impuesto != null) { conexion.ProductoImpuesto.Remove(impuesto); } } conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); ((ASPxGridView)sender).JSProperties["cpUpdatedMessage"] = "Los datos se modificaron correctamente, puede continuar."; } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// /// </summary> /// <param name="tieneFirma">determina si el XML esta firmado o no</param> /// <param name="documento">puede ser cualquer tipo de documento electronico</param> /// <param name="responsePost">respuesta del webs ervices</param> /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param> public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documento, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario) { String responsePost = ""; try { string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documento); using (var conexion = new DataModelFE()) { OAuth2.OAuth2Config config = null; if (System.Web.HttpContext.Current.Session["token"] != null) { config = (OAuth2.OAuth2Config)System.Web.HttpContext.Current.Session["token"]; } if (requiereNuevoToken(config)) { //Sessison["horaToken"] string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); System.Web.HttpContext.Current.Session["token"] = config; System.Web.HttpContext.Current.Session["tokenTime"] = Date.DateTimeNow(); } Models.WS.WSRecepcionPOST trama = new Models.WS.WSRecepcionPOST(); trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile); trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00", System.Globalization.CultureInfo.InvariantCulture); string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile); trama.emisor.tipoIdentificacion = emisorIdentificacion.Substring(0, 2); trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2); trama.emisorTipo = trama.emisor.tipoIdentificacion; trama.emisorIdentificacion = trama.emisor.numeroIdentificacion; string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile); if (!string.IsNullOrWhiteSpace(receptorIdentificacion)) { trama.receptor.tipoIdentificacion = receptorIdentificacion.Substring(0, 2); trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2); } else { trama.receptor.tipoIdentificacion = "99"; trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile); } trama.receptorTipo = trama.receptor.tipoIdentificacion; trama.receptorIdentificacion = trama.receptor.numeroIdentificacion; trama.tipoDocumento = tipoDocumento; //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString(); if (!tieneFirma) { xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString()); } trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile); string jsonTrama = JsonConvert.SerializeObject(trama); if (config.token.access_token != null) { responsePost = await postRecepcion(config.token, jsonTrama); Models.WS.WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave); if (tramaExiste != null) {// si existe trama.fechaModificacion = Date.DateTimeNow(); trama.usuarioModificacion = usuario; trama.indEstado = 0; trama.cargarEmisorReceptor(); conexion.Entry(tramaExiste).State = EntityState.Modified; documento.resumenFactura.clave = documento.clave; conexion.Entry(documento.resumenFactura).State = EntityState.Modified; } else//si no existe { trama.fechaCreacion = Date.DateTimeNow(); trama.usuarioCreacion = usuario; trama.cargarEmisorReceptor(); conexion.WSRecepcionPOST.Add(trama); //trama documento.resumenFactura.clave = documento.clave; //resumen conexion.ResumenFactura.Add(documento.resumenFactura); } conexion.SaveChanges(); } else { // error de conexion de red responsePost = "net_error"; return(responsePost); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } return(responsePost); }
/// <summary> /// /// </summary> /// <param name="tieneFirma">determina si el XML esta firmado o no</param> /// <param name="documento">puede ser cualquer tipo de documento electronico</param> /// <param name="responsePost">respuesta del webs ervices</param> /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param> public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documentoElectronico, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario) { String responsePost = ""; try { string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documentoElectronico); using (var conexion = new DataModelFE()) { string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST(); trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile); trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00", System.Globalization.CultureInfo.InvariantCulture); string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile); trama.emisor.tipoIdentificacion = emisorIdentificacion.Substring(0, 2); trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2); trama.emisorTipo = trama.emisor.tipoIdentificacion; trama.emisorIdentificacion = trama.emisor.numeroIdentificacion; string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile); if (!string.IsNullOrWhiteSpace(receptorIdentificacion)) { trama.receptor.tipoIdentificacion = receptorIdentificacion.Substring(0, 2); trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2); } else { trama.receptor.tipoIdentificacion = "99"; trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile); } trama.receptorTipo = trama.receptor.tipoIdentificacion; trama.receptorIdentificacion = trama.receptor.numeroIdentificacion; trama.tipoDocumento = tipoDocumento; //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString(); if (!tieneFirma) { xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString()); } trama.consecutivoReceptor = null; // SE CODIFICA ENVIO HACIENDA trama.comprobanteXml = XMLUtils.base64Encode(xmlFile); string jsonTrama = JsonConvert.SerializeObject(trama); if (config.token.access_token != null) { responsePost = await Services.postRecepcion(config.token, jsonTrama); } else { // facturar guardada para envio en linea trama.indEstado = 9; } // SE DECODIFICA PARA GUARDAR A BASE DE DATOS trama.comprobanteXml = xmlFile; WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave); documentoElectronico.resumenFactura.clave = documentoElectronico.clave; trama.cargarEmisorReceptor(); if (tramaExiste != null) {// si existe trama.fechaModificacion = Date.DateTimeNow(); trama.usuarioModificacion = usuario; trama.indEstado = 0; conexion.Entry(tramaExiste).State = EntityState.Modified; conexion.Entry(documentoElectronico.resumenFactura).State = EntityState.Modified; } else//si no existe { trama.fechaCreacion = Date.DateTimeNow(); trama.usuarioCreacion = usuario; conexion.WSRecepcionPOST.Add(trama); conexion.ResumenFactura.Add(documentoElectronico.resumenFactura); Plan plan = conexion.Plan.Find(emisor.identificacion); if (plan != null) { plan.cantidadDocEmitido += 1; conexion.Entry(plan).State = EntityState.Modified; } } conexion.SaveChanges(); //guarda la relacion de clientes asociados al emisor Cliente cliente = conexion.Cliente.Where(x => x.emisor == trama.emisor.numeroIdentificacion).Where(x => x.receptor == trama.receptor.numeroIdentificacion).FirstOrDefault(); if (cliente == null && !string.IsNullOrWhiteSpace(trama.receptor.numeroIdentificacion)) { cliente = new Cliente(); cliente.emisor = trama.emisor.numeroIdentificacion; cliente.receptor = trama.receptor.numeroIdentificacion; conexion.Cliente.Add(cliente); conexion.SaveChanges(); } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } return(responsePost); }
protected void btnLogin_Click(object sender, EventArgs e) { try { using (var conexion = new DataModelFE()) { Usuario usuario = conexion.Usuario.Find(tbUserName.Text); if (usuario != null) { if (usuario.contrasena.Equals(MD5Util.getMd5Hash(this.tbPassword.Text))) { if (usuario.estado.Equals(Estado.INACTIVO.ToString())) { this.alertMessages.InnerText = "El usuario se encuentra inactivo, contacte al administrador"; return; } if (usuario.Rol.estado.Equals(Estado.INACTIVO.ToString())) { this.alertMessages.InnerText = "El perfil al que pertenece el usuario, se encuentra inactivo, contacte al administrador"; this.alertMessages.Attributes["class"] = "alert alert-danger"; return; } Session.RemoveAll(); EmisorReceptorIMEC emisor = conexion.EmisorReceptorIMEC.Find(usuario.emisor); Session["usuario"] = usuario.codigo; Session["elUsuario"] = usuario; Session["emisor"] = emisor.identificacion; Session["elEmisor"] = emisor; usuario.intentos = 0; conexion.Entry(usuario).State = EntityState.Modified; conexion.SaveChanges(); FormsAuthentication.SetAuthCookie(usuario.nombre, false); if (usuario.rol == Rol.SUPERVISOR) { Response.Redirect("~/Pages/SeleccionarEmisor"); } else { Response.Redirect("~/"); } } else { usuario.intentos += 1; conexion.Entry(usuario).State = EntityState.Modified; if (usuario.intentos > 3) { this.alertMessages.InnerText = "Ha superado la mayor cantidad de intentos posibles, su cuenta ha sido bloqueada, contacte al administrador"; this.alertMessages.Attributes["class"] = "alert alert-danger"; usuario.estado = Estado.INACTIVO.ToString(); } else { this.alertMessages.InnerText = "Intento fallidos : " + usuario.intentos; this.alertMessages.Attributes["class"] = "alert alert-danger"; } this.tbUserName.ErrorText = "Usuario invalido"; conexion.SaveChanges(); } } } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex); this.alertMessages.Attributes["class"] = "alert alert-danger"; } }
/// <summary> /// Se actualizan los mensajes del ministerio de hacienda que esten pendientes /// </summary> /// <returns></returns> public async Task<bool> actualizarMensajesHacienda() { try { EmisorReceptorIMEC emisor = null; OAuth2.OAuth2Config config = null; using (var conexion = new DataModelFE()) { // se buscan los paquetes que esten enviados y esten esperando un respuesta de hacienda (indEstado == 8) o esten enviandas (indEstado == 0) List<Models.WS.WSRecepcionPOST> lista = conexion.WSRecepcionPOST.Where(x => x.indEstado == 0 || x.indEstado == 8 ).ToList(); foreach (var item in lista) { if (config == null) { emisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN); string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); } string respuestaJSON = await ServicesHacienda.getRecepcion(config.token, item.clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject<WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); using (var conexionWS = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } else { if (respuesta.indEstado.Equals("recibido")) { using (var conexionWS = new DataModelFE()) { Models.WS.WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.indEstado = 8/*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } } } } } } catch (Exception e) { String data = e.Message; } return true; }
protected async void btnCrearNota_Click(object sender, EventArgs e) { try { Thread.CurrentThread.CurrentCulture = Utilidades.getCulture(); List <string> cc = new List <string>(); Regex validator = new Regex(@"\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*"); foreach (var correo in this.txtCorreoReceptor.Tokens) { if (validator.IsMatch(correo)) { cc.Add(correo); } else { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = String.Format("Favor verifique el formato de la dirección {0}", correo); return; } } cc.RemoveAt(0); DetalleServicio detalle = (DetalleServicio)Session["detalleServicio"]; if (detalle.lineaDetalle.Count == 0) { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = "Debe agregar almenos una linea de detalle a la factura"; return; } // datos de la factura original FacturaElectronica factura = new FacturaElectronica(); string clave = Session["clave"].ToString(); using (var conexion = new DataModelFE()) { WSRecepcionPOST datoPost = conexion.WSRecepcionPOST.Find(clave); string xmlFactura = datoPost.comprobanteXml; factura = (FacturaElectronica)EncodeXML.XMLUtils.getObjetcFromXML(xmlFactura, typeof(FacturaElectronica)); DocumentoElectronico dato = null; if (TipoDocumento.NOTA_CREDITO.Equals(Session["tipoNota"].ToString())) { dato = new NotaCreditoElectronica(); } else { dato = new NotaDebitoElectronica(); } /* ENCABEZADO */ dato.medioPago = factura.medioPago; dato.plazoCredito = factura.plazoCredito; dato.condicionVenta = factura.condicionVenta; dato.fechaEmision = Date.DateTimeNow().ToString("yyyy-MM-ddTHH:mm:ss") + "-06:00"; /* DETALLE */ dato.detalleServicio = detalle; /* EMISOR */ dato.emisor = factura.emisor; /* RECEPTOR */ dato.receptor = factura.receptor; /* INFORMACION DE REFERENCIA */ InformacionReferencia informacionReferencia = new InformacionReferencia(); informacionReferencia.numero = factura.clave; informacionReferencia.fechaEmision = factura.fechaEmision; informacionReferencia.codigo = this.cmbCodigoReferencia.Value.ToString(); informacionReferencia.razon = this.txtRazón.Text; informacionReferencia.tipoDocumento = TipoDocumento.FACTURA_ELECTRONICA; dato.informacionReferencia.Add(informacionReferencia); /* RESUMEN */ dato.resumenFactura.tipoCambio = factura.resumenFactura.tipoCambio; dato.resumenFactura.codigoMoneda = factura.resumenFactura.codigoMoneda; foreach (var item in dato.detalleServicio.lineaDetalle) { if (item.tipoServMerc == null) { Producto producto = conexion.Producto.Where(x => x.codigo == item.codigo.codigo && x.emisor == dato.emisor.identificacion.numero).FirstOrDefault(); item.tipoServMerc = producto.tipoServMerc; item.producto = producto.codigo; } } dato.resumenFactura.calcularResumenFactura(dato.detalleServicio.lineaDetalle); /* VERIFICA VACIOS PARA XML */ dato.verificaDatosParaXML(); //genera el consecutivo del documento string sucursal = this.cmbSucursalCaja.Value.ToString().Substring(0, 3); string caja = this.cmbSucursalCaja.Value.ToString().Substring(3, 5); object[] key = new object[] { dato.emisor.identificacion.numero, sucursal, caja, this.cmbTipoDocumento.Value.ToString() }; ConsecutivoDocElectronico consecutivo = conexion.ConsecutivoDocElectronico.Find(key); if (consecutivo != null) { dato.clave = consecutivo.getClave(Date.DateTimeNow().ToString("yyyyMMdd")); dato.numeroConsecutivo = consecutivo.getConsecutivo(); consecutivo.consecutivo += 1; conexion.Entry(consecutivo).State = EntityState.Modified; } else { consecutivo = new ConsecutivoDocElectronico(); consecutivo.sucursal = ConsecutivoDocElectronico.DEFAULT_SUCURSAL; consecutivo.caja = ConsecutivoDocElectronico.DEFAULT_CAJA; consecutivo.digitoVerificador = ConsecutivoDocElectronico.DEFAULT_DIGITO_VERIFICADOR; consecutivo.emisor = dato.emisor.identificacion.numero; consecutivo.tipoDocumento = this.cmbTipoDocumento.Value.ToString(); consecutivo.consecutivo = 1; consecutivo.estado = Estado.ACTIVO.ToString(); consecutivo.fechaCreacion = Date.DateTimeNow(); dato.clave = consecutivo.getClave(Date.DateTimeNow().ToString("yyyyMMdd")); dato.numeroConsecutivo = consecutivo.getConsecutivo(); consecutivo.consecutivo += 1; conexion.ConsecutivoDocElectronico.Add(consecutivo); } EmisorReceptorIMEC elEmisor = (EmisorReceptorIMEC)Session["elEmisor"]; string responsePost = await Services.enviarDocumentoElectronico(false, dato, elEmisor, this.cmbTipoDocumento.Value.ToString(), Session["usuario"].ToString()); if (responsePost.Equals("Success")) { this.alertMessages.Attributes["class"] = "alert alert-info"; this.alertMessages.InnerText = String.Format("Documento #{0} enviada.", dato.numeroConsecutivo); if (!string.IsNullOrWhiteSpace(dato.receptor.correoElectronico) || this.txtCorreoReceptor.Tokens.Count > 0) { string xml = EncodeXML.XMLUtils.getXMLFromObject(dato); Utilidades.sendMail(Session["emisor"].ToString(), dato.receptor.correoElectronico, string.Format("{0} - {1}", dato.numeroConsecutivo, elEmisor.nombre), Utilidades.mensageGenerico(), "Documento Electrónico", xml, dato.numeroConsecutivo, dato.clave, cc); } } else if (responsePost.Equals("Error")) { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = String.Format("Documento #{0} con errores.", dato.numeroConsecutivo); return; } else { this.alertMessages.Attributes["class"] = "alert alert-warning"; this.alertMessages.InnerText = String.Format("Documento #{0} pendiente de envío", dato.numeroConsecutivo); } conexion.SaveChanges(); Response.Redirect("~/Pages/Consulta/" + dato.clave); } } catch (Exception ex) { this.alertMessages.Attributes["class"] = "alert alert-danger"; this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex); } finally { //refescar los datos this.refreshData(); } }
/// <summary> /// Se actualizan los mensajes del ministerio de hacienda que esten pendientes /// </summary> /// <returns></returns> public async Task <bool> actualizarMensajesHacienda() { try { EmisorReceptorIMEC emisor = null; OAuth2.OAuth2Config config = null; Thread.CurrentThread.CurrentCulture = Utilidades.getCulture(); using (var conexion = new DataModelFE()) { List <WSRecepcionPOST> lista = conexion.WSRecepcionPOST. Where(x => x.indEstado == 0 /*ENVIADO*/ || x.indEstado == 8 /*RECIBIDO*/ || x.indEstado == 9 /*PENDIENTE || * x.comprobanteRespXML == null*/).ToList(); foreach (var item in lista) { if (config == null) { emisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN); string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString(); config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault(); config.username = emisor.usernameOAuth2; config.password = emisor.passwordOAuth2; await OAuth2.OAuth2Config.getTokenWeb(config); } string respuestaJSON = await Services.getRecepcion(config.token, item.clave); if (!string.IsNullOrWhiteSpace(respuestaJSON)) { WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON); if (respuesta.respuestaXml != null) { string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml); MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML); using (var conexionWS = new DataModelFE()) { WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.mensaje = mensajeHacienda.mensajeDetalle; dato.indEstado = mensajeHacienda.mensaje; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; dato.montoTotalFactura = mensajeHacienda.montoTotalFactura; dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto; dato.comprobanteRespXML = respuestaXML; if (mensajeHacienda.montoTotalFactura == 0) { string xml = XMLUtils.base64Decode(dato.comprobanteXml); try { dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml)); dato.montoTotalFactura = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml)); } catch (Exception ex) { dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml).Replace(".", ",")); dato.montoTotalFactura = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml).Replace(".", ",")); } } conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } else { if (respuesta.indEstado.Equals("recibido")) { using (var conexionWS = new DataModelFE()) { WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave); dato.indEstado = 8 /*recibido por hacienda*/; dato.fechaModificacion = Date.DateTimeNow(); dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO; conexionWS.Entry(dato).State = EntityState.Modified; conexionWS.SaveChanges(); } } } } } } } catch (Exception e) { String data = e.Message; } return(true); }
/// <summary> /// inserta un registro nuevo /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) { try { using (var conexion = new DataModelFE()) { //se declara el objeto a insertar EmisorReceptorIMEC dato = new EmisorReceptorIMEC(); //llena el objeto con los valores de la pantalla dato.identificacionTipo = e.NewValues["identificacionTipo"].ToString(); dato.identificacion = e.NewValues["identificacion"].ToString(); dato.nombre = e.NewValues["nombre"].ToString(); dato.nombreComercial = e.NewValues["nombreComercial"] != null ? e.NewValues["nombreComercial"].ToString().ToUpper() : null; if (e.NewValues["telefono"] != null) { //dato.telefonoCodigoPais = e.NewValues["telefonoCodigoPais"].ToString(); dato.telefonoCodigoPais = "506"; dato.telefono = e.NewValues["telefono"].ToString(); } dato.correoElectronico = e.NewValues["correoElectronico"] != null ? e.NewValues["correoElectronico"].ToString() : null; if (e.NewValues["fax"] != null) { //dato.faxCodigoPais = e.NewValues["faxCodigoPais"].ToString(); dato.faxCodigoPais = "506"; dato.fax = e.NewValues["fax"].ToString(); } ASPxPageControl tabs = (ASPxPageControl)ASPxGridView1.FindEditFormTemplateControl("pageControl"); ASPxFormLayout form = (ASPxFormLayout)tabs.FindControl("formLayoutUbicacion"); /* PROVINCIA */ ASPxComboBox comboProvincia = (ASPxComboBox)form.FindControl("cmbProvincia"); /* CANTON */ ASPxComboBox comboCanton = (ASPxComboBox)form.FindControl("cmbCanton"); /* DISTRITO */ ASPxComboBox comboDistrito = (ASPxComboBox)form.FindControl("cmbDistrito"); /* BARRIO */ ASPxComboBox comboBarrio = (ASPxComboBox)form.FindControl("cmbBarrio"); ASPxMemo otraSena = (ASPxMemo)form.FindControl("txtOtraSenas"); /* PLAN */ ASPxComboBox combPlan = (ASPxComboBox)form.FindControl("cmbPlan"); dato.provincia = comboProvincia.Value.ToString(); dato.canton = comboCanton.Value.ToString(); dato.distrito = comboDistrito.Value.ToString(); dato.barrio = comboBarrio.Value.ToString(); dato.otraSena = otraSena.Text; dato.usernameOAuth2 = e.NewValues["usernameOAuth2"] != null ? e.NewValues["usernameOAuth2"].ToString() : null; dato.passwordOAuth2 = e.NewValues["passwordOAuth2"] != null ? e.NewValues["passwordOAuth2"].ToString() : null; dato.claveLlaveCriptografica = e.NewValues["claveLlaveCriptografica"] != null ? e.NewValues["claveLlaveCriptografica"].ToString() : null; if (Session["LlaveCriptograficap12"] != null) { dato.llaveCriptografica = (byte[])Session["LlaveCriptograficap12"]; } dato.estado = e.NewValues["estado"].ToString(); dato.usuarioCreacion = Session["usuario"].ToString(); dato.fechaCreacion = Date.DateTimeNow(); //agrega el objeto EmisorReceptorIMEC existeEmisor = conexion.EmisorReceptorIMEC.Find(dato.identificacion); if (existeEmisor == null) { conexion.EmisorReceptorIMEC.Add(dato); } else { conexion.Entry(dato).State = EntityState.Modified; } Plan planE = conexion.Plan.Find(dato.identificacion); if (planE == null) { TipoPlan tipoPlan = conexion.TipoPlan.Find(combPlan.Value.ToString()); Plan plan = new Plan(); plan.usuarioCreacion = Session["usuario"].ToString(); plan.fechaCreacion = Date.DateTimeNow(); plan.cantidadDocEmitido = 0; plan.cantidadDocPlan = tipoPlan.cantidad; plan.plan = tipoPlan.codigo; plan.emisor = dato.identificacion; plan.estado = Estado.ACTIVO.ToString(); plan.fechaInicio = Date.DateTimeNow(); plan.fechaFin = Date.DateTimeNow().AddYears(1); conexion.Plan.Add(plan); } Usuario usuario = conexion.Usuario.Find(dato.identificacion); if (usuario == null) { usuario = new Usuario(); usuario.usuarioCreacion = Session["usuario"].ToString(); usuario.fechaCreacion = Date.DateTimeNow(); usuario.nombre = dato.nombre; usuario.emisor = dato.identificacion; usuario.codigo = dato.identificacion; usuario.contrasena = MD5Util.getMd5Hash("msa" + dato.identificacion + ".01"); usuario.correo = dato.correoElectronico; usuario.rol = Rol.FACTURADOR; conexion.Usuario.Add(usuario); } ConsecutivoDocElectronico consecutivo = conexion.ConsecutivoDocElectronico.Where(x => x.emisor == dato.identificacion && x.tipoDocumento == "01").FirstOrDefault(); if (consecutivo == null) { consecutivo = new ConsecutivoDocElectronico(); consecutivo.emisor = dato.identificacion; consecutivo.sucursal = "001"; consecutivo.caja = "00001"; consecutivo.consecutivo = 1; consecutivo.tipoDocumento = TipoDocumento.FACTURA_ELECTRONICA; consecutivo.digitoVerificador = "00000000"; consecutivo.estado = Estado.ACTIVO.ToString(); consecutivo.usuarioCreacion = Session["usuario"].ToString(); consecutivo.fechaCreacion = Date.DateTimeNow(); conexion.ConsecutivoDocElectronico.Add(consecutivo); } Empresa empresa = conexion.Empresa.Find(dato.identificacion); if (empresa == null) { empresa = new Empresa(); empresa.codigo = dato.identificacion; empresa.descripcion = dato.nombre == null ? dato.nombreComercial : dato.nombre; empresa.estado = Estado.ACTIVO.ToString(); empresa.usuarioCreacion = Session["usuario"].ToString(); empresa.fechaCreacion = Date.DateTimeNow(); empresa.idioma = Empresa.IDIOMA_ESPANOL; empresa.medioPago = "01"; empresa.condicionVenta = "01"; empresa.plazoCredito = 0; empresa.tipoImpresion = "A4"; empresa.moneda = "CRC"; conexion.Empresa.Add(empresa); } string super = Session["usuario"].ToString(); Supervisor supervisor = conexion.Supervisor.Where(x => x.supervisor == super && x.emisor == dato.identificacion).FirstOrDefault(); if (supervisor == null) { supervisor = new Supervisor(); supervisor.supervisor = Session["usuario"].ToString(); supervisor.emisor = dato.identificacion; conexion.Supervisor.Add(supervisor); } conexion.SaveChanges(); //esto es para el manero del devexpress e.Cancel = true; this.ASPxGridView1.CancelEdit(); ((ASPxGridView)sender).JSProperties["cpUpdatedMessage"] = "Los datos se agregaron correctamente, puede continuar."; } } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors); } catch (Exception ex) { throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException); } finally { //refescar los datos this.refreshData(); } }