Ejemplo n.º 1
0
        /// <summary>
        /// este metodo si inicializa al cada vez que se renderiza la pagina
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Request.IsAuthenticated)
                {
                    Response.Redirect("~/Pages/Login.aspx");
                }
                if (!IsCallback && !IsPostBack)
                {
                    using (var conexion = new DataModelFE())
                    {
                        /* EMISOR */
                        string             emisorUsuario = Session["usuario"].ToString();
                        EmisorReceptorIMEC emisor        = conexion.EmisorReceptorIMEC.Where(x => x.identificacion == emisorUsuario).FirstOrDefault();
                        this.loadEmisor(emisor);
                    }

                    this.loadComboBox();
                }
                this.refreshData();
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
Ejemplo n.º 2
0
        /// <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();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// carga datos del emisor
        /// </summary>
        /// <param name="emisor"></param>
        private void loadEmisor(EmisorReceptorIMEC emisor)
        {
            this.cmbEmisorTipo.Value           = emisor.identificacionTipo;
            this.txtEmisorIdentificacion.Text  = emisor.identificacion;
            this.txtEmisorNombre.Text          = emisor.nombre;
            this.txtEmisorNombreComercial.Text = emisor.nombreComercial;

            this.cmbEmisorTelefonoCod.Value = emisor.telefonoCodigoPais;
            this.cmbEmisorFaxCod.Value      = emisor.faxCodigoPais;
            this.txtEmisorTelefono.Value    = emisor.telefono;
            this.txtEmisorFax.Value         = emisor.fax;
            this.txtEmisorCorreo.Text       = emisor.correoElectronico;

            this.cmbEmisorProvincia.Value = emisor.provincia;

            this.cmbEmisorProvincia_ValueChanged(null, null);
            this.cmbEmisorCanton.Value = emisor.canton;

            this.cmbEmisorCanton_ValueChanged(null, null);
            this.cmbEmisorDistrito.Value = emisor.distrito;

            this.cmbEmisorDistrito_ValueChanged(null, null);
            this.cmbEmisorBarrio.Value    = emisor.barrio;
            this.txtEmisorOtraSenas.Value = emisor.otraSena;

            this.txtUsernameOAuth2.Text          = emisor.usernameOAuth2;
            this.txtPasswordOAuth2.Text          = emisor.passwordOAuth2;
            this.txtClaveLlaveCriptografica.Text = emisor.claveLlaveCriptografica.ToString();
        }
Ejemplo n.º 4
0
        protected void btnCargarDatos_Click(object sender, EventArgs e)
        {
            try
            {
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();
                string xml = Session["xmlFileValidar"].ToString();

                //string receptorIdentificacion1 = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xml);
                //txtNumCedReceptor.Text = receptorIdentificacion.Substring(2);

                if (XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xml).Substring(2) == Session["emisor"].ToString())
                {
                    txtClave.Text = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xml), "Clave", xml);
                    //Emisor
                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xml);
                    txtNumCedEmisor.Text = emisorIdentificacion.Substring(2);
                    txtFechaEmisor.Text  = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xml), "FechaEmision", xml);

                    EmisorReceptorIMEC emisor = (EmisorReceptorIMEC)Session["elEmisor"];
                    this.txtNumConsecutivoReceptor.Text = "0010000107" + emisor.consecutivo.ToString().PadLeft(10, '0');

                    //Factura
                    double totalImpuesto = Convert.ToDouble(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml));
                    txtMontoTotalImpuesto.Text = totalImpuesto.ToString("N2");
                    double totalFactura = Convert.ToDouble(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml));
                    txtTotalFactura.Text = totalFactura.ToString("N2");

                    //Receptor
                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xml);
                    if (!string.IsNullOrWhiteSpace(receptorIdentificacion))
                    {
                        Session["receptor.tipoIdentificacion"] = receptorIdentificacion.Substring(0, 2);
                        txtNumCedReceptor.Text = receptorIdentificacion.Substring(2);
                    }
                    else
                    {
                        Session["receptor.tipoIdentificacion"] = "99";
                        txtNumCedReceptor.Text = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xml);
                    }
                    Session["receptor.CorreoElectronico"] = XMLUtils.buscarValorEtiquetaXML("Receptor", "CorreoElectronico", xml);
                    Session["receptor.Nombre"]            = XMLUtils.buscarValorEtiquetaXML("Receptor", "Nombre", xml);

                    this.alertMessages.Attributes["class"] = "alert alert-success";
                    this.alertMessages.InnerText           = "Los datos fueron cargados correctamente!!!";
                }
                else
                {
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                    this.alertMessages.InnerText           = "El receptor del XML seleccionado no corresponde con la identificación del usuario!!!";
                    xmlUploadControl1 = null;
                    return;
                }
            }
            catch (Exception ex)
            {
                this.alertMessages.Attributes["class"] = "alert alert-danger";
                this.alertMessages.InnerText           = Utilidades.validarExepcionSQL(ex);
            }
        }
        protected async void btnEnvioManual_Click(object sender, EventArgs e)
        {
            try
            {
                if (TipoDocumento.PENDIENTE.ToString().Equals(Session["indEstado"].ToString()) ||
                    TipoDocumento.ENVIADO.ToString().Equals(Session["indEstado"].ToString()))
                {
                    Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();

                    using (var conexion = new DataModelFE())
                    {
                        string               clave     = Session["clave"].ToString();
                        WSRecepcionPOST      dato      = conexion.WSRecepcionPOST.Find(clave);
                        string               xml       = dato.comprobanteXml;
                        DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                        documento.verificaDatosParaXML();

                        EmisorReceptorIMEC elEmisor     = ((EmisorReceptorIMEC)Session["elEmisor"]);
                        string             responsePost = await Services.enviarDocumentoElectronico(false, documento, elEmisor, dato.tipoDocumento, Session["usuario"].ToString());

                        string correoElectronico = XMLUtils.buscarValorEtiquetaXML("Receptor", "CorreoElectronico", xml);

                        if (responsePost.Equals("Success"))
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-info";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} enviada.", dato.numeroConsecutivo);

                            if (!string.IsNullOrWhiteSpace(correoElectronico))
                            {
                                Utilidades.sendMail(Session["emisor"].ToString(), correoElectronico,
                                                    string.Format("{0} - {1}", dato.numeroConsecutivo, dato.receptor.nombre),
                                                    Utilidades.mensageGenerico(), "Documento Electrónico", xml, dato.numeroConsecutivo, dato.clave, null);
                            }
                        }
                        else if (responsePost.Equals("Error"))
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-danger";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} con errores.", dato.numeroConsecutivo);
                        }
                        else
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-warning";
                            this.alertMessages.InnerText           = String.Format("Documento #{0} pendiente de envío", dato.numeroConsecutivo);
                        }
                    }
                }
                else
                {
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                    this.alertMessages.InnerText           = String.Format("Documento eléctronico no se encuentra PENDIENTE");
                }
            }
            catch (Exception ex)
            {
                this.alertMessages.InnerText = Utilidades.validarExepcionSQL(ex);
            }
        }
Ejemplo n.º 6
0
 private async Task <OAuth2.OAuth2Token> getToken()
 {
     OAuth2.OAuth2Config config = null;
     using (var conexionAuth = new DataModelFE())
     {
         EmisorReceptorIMEC elEmisor = conexionAuth.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN);
         string             ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
         config          = conexionAuth.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
         config.username = elEmisor.usernameOAuth2;
         config.password = elEmisor.passwordOAuth2;
         await OAuth2.OAuth2Config.getTokenWeb(config);
     }
     return(config.token);
 }
Ejemplo n.º 7
0
        protected async void btnEnviar_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 xmlFile = Session["xmlFile"].ToString();
                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);

                    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);
                    trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                    trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;

                    trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    using (var conexion2 = new DataModelFE())
                    {
                        WSRecepcionPOST tramaObjeto = JsonConvert.DeserializeObject <WSRecepcionPOST>(jsonTrama);
                        conexion2.WSRecepcionPOST.Add(tramaObjeto);
                        conexion2.SaveChanges();
                    }

                    string responsePost = await Services.postRecepcion(config.token, jsonTrama);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
Ejemplo n.º 8
0
        public async Task <HttpResponseMessage> recepcionmesajehacienda()
        {
            string responsePost = "";

            try
            {
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();
                string xml = await Request.Content.ReadAsStringAsync();

                DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                documento.verificaDatosParaXML();

                EmisorReceptorIMEC elEmisor = null;
                using (var conexion = new DataModelFE())
                {
                    long id = long.Parse(documento.emisor.identificacion.numero);
                    elEmisor = conexion.EmisorReceptorIMEC.Find(id.ToString());
                    if (elEmisor == null)
                    {
                        //return "Emisor no registrado!!!";
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emisor no registrado!!!"));
                        //return Ok("Emisor no registrado!!!");
                    }
                }
                responsePost = await ServicesHacienda.enviarDocumentoElectronico(false, documento, elEmisor, documento.tipoDocumento, Usuario.USUARIO_AUTOMATICO);
            }
            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(Request.CreateErrorResponse(HttpStatusCode.NotFound, fullErrorMessage));
                //return Ok(fullErrorMessage);
            }
            catch (Exception ex)
            {
                //return ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message));
                //return Ok(ex.Message);
            }
            //return responsePost;
            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, responsePost));
            //return Ok(responsePost);
        }
Ejemplo n.º 9
0
 protected void ASPxGridViewClientes_SelectionChanged(object sender, EventArgs e)
 {
     if ((sender as ASPxGridView).GetSelectedFieldValues("identificacion").Count > 0)
     {
         string identificacion = (sender as ASPxGridView).GetSelectedFieldValues("identificacion")[0].ToString();
         using (var conexion = new DataModelFE())
         {
             EmisorReceptorIMEC emisor = conexion.EmisorReceptorIMEC.Find(identificacion);
             //Session["usuario"] = emisor.identificacion;
             //Session["elUsuario"] = conexion.Usuario.Find(emisor.identificacion);
             Session["emisor"]   = emisor.identificacion;
             Session["elEmisor"] = emisor;
             Response.Redirect("~/");
         }
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xmlFile">XML sin firmar</param>
        /// <param name="responsePost">respuesta del webs ervices</param>
        /// <param name="receptorTipoIdentificacion">tipoo identificacion del receptor</param>
        public static async Task <string> enviarMensajeReceptor(string xmlFile, EmisorReceptorIMEC emisor, string receptorTipoIdentificacion)
        {
            String responsePost = "";

            try
            {
                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.emisor.tipoIdentificacion   = emisor.identificacionTipo;
                    trama.emisor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("MensajeReceptor", "NumeroCedulaEmisor", xmlFile);

                    trama.receptor.tipoIdentificacion   = receptorTipoIdentificacion;
                    trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("MensajeReceptor", "NumeroCedulaReceptor", xmlFile);

                    xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString());

                    trama.consecutivoReceptor = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "NumeroConsecutivoReceptor", xmlFile);
                    trama.comprobanteXml      = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    responsePost = await Services.postRecepcion(config.token, jsonTrama);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            return(responsePost);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// verifica que existan los datos de la conexionn con hacienda
        /// </summary>
        /// <param name="dato"></param>
        /// <returns></returns>
        public static bool verificaDatosHacienda(EmisorReceptorIMEC dato)
        {
            bool valido = true;

            if (dato.llaveCriptografica == null)
            {
                valido = false;
            }
            if (string.IsNullOrWhiteSpace(dato.claveLlaveCriptografica))
            {
                valido = false;
            }
            if (string.IsNullOrWhiteSpace(dato.usernameOAuth2))
            {
                valido = false;
            }
            if (string.IsNullOrWhiteSpace(dato.passwordOAuth2))
            {
                valido = false;
            }
            return(valido);
        }
Ejemplo n.º 12
0
        /// <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"] != null ? e.NewValues["identificacionTipo"].ToString().ToUpper() : null;
                    dato.identificacion     = e.NewValues["identificacion"] != null ? e.NewValues["identificacion"].ToString().ToUpper() : null;

                    dato.nombre = e.NewValues["nombre"] != null ? e.NewValues["nombre"].ToString().ToUpper() : null;

                    dato.nombreComercial = e.NewValues["nombreComercial"] != null ? e.NewValues["nombreComercial"].ToString().ToUpper() : null;

                    dato.usuarioCreacion = Session["usuario"].ToString();
                    dato.fechaCreacion   = Date.DateTimeNow();

                    //agrega el objeto
                    conexion.EmisorReceptorIMEC.Add(dato);
                    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();
            }
        }
Ejemplo n.º 13
0
        protected void btnFirmar_Click(object sender, EventArgs e)
        {
            try
            {
                string xmlFile = Session["xmlFile"].ToString();

                EmisorReceptorIMEC dato = null;
                using (var conexion = new DataModelFE())
                {
                    string usuario = Session["usuario"].ToString();
                    dato = conexion.EmisorReceptorIMEC.Where(x => x.identificacion == usuario).FirstOrDefault();
                }

                string xmlFileSigned = FirmaXML.getXMLFirmadoWeb(xmlFile, dato.llaveCriptografica, dato.claveLlaveCriptografica.ToString());
                Session["xmlFile"] = xmlFileSigned;

                this.loadHTML();
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
Ejemplo n.º 14
0
        protected async void btnProbarUsuario_Click(object sender, EventArgs e)
        {
            using (var conexion = new DataModelFE())
            {
                string ambiente            = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                EmisorReceptorIMEC  emisor = (EmisorReceptorIMEC)Session["elEmisor"];
                config.username = emisor.usernameOAuth2;
                config.password = emisor.passwordOAuth2;

                await OAuth2.OAuth2Config.getTokenWeb(config);

                if (config.token.access_token != null)
                {
                    this.alertMessages.InnerText           = "Usuario configurado con éxito";
                    this.alertMessages.Attributes["class"] = "alert alert-info";
                }
                else
                {
                    this.alertMessages.InnerText           = "Usuario presenta errores, verificar configuración";
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                }
            }
        }
Ejemplo n.º 15
0
        /// <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);
        }
Ejemplo n.º 16
0
        /// <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);
        }
Ejemplo n.º 17
0
        public async Task <HttpResponseMessage> recepcionmesajehacienda()
        {
            string responsePost = "";

            try
            {
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();
                string xml = await Request.Content.ReadAsStringAsync();

                DocumentoElectronico documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xml);
                documento.verificaDatosParaXML();

                EmisorReceptorIMEC elEmisor = null;
                using (var conexion = new DataModelFE())
                {
                    long idE = long.Parse(documento.emisor.identificacion.numero);
                    elEmisor = conexion.EmisorReceptorIMEC.Find(idE.ToString());
                    if (elEmisor == null)
                    {
                        //return "Emisor no registrado!!!";
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emisor no registrado!!!"));
                        //return Ok("Emisor no registrado!!!");
                    }
                    else// si el xml es de un emisor valido, verifica si existe el receptor y si no lo crea
                    {
                        string tipo       = "";
                        string idReceptor = "";
                        if (!string.IsNullOrWhiteSpace(documento.receptor.identificacionExtranjero))
                        {
                            tipo       = "99";
                            idReceptor = documento.receptor.identificacionExtranjero;
                        }
                        else
                        {
                            //elimina ceros a la izquierda
                            long idR = long.Parse(documento.receptor.identificacion.numero);
                            tipo       = documento.receptor.identificacion.tipo;
                            idReceptor = idR.ToString();
                        }
                        EmisorReceptorIMEC elReceptor = conexion.EmisorReceptorIMEC.Find(idReceptor);
                        if (elReceptor == null)
                        {
                            // crea un cliente para que se muestre el emisor
                            elReceptor = new EmisorReceptorIMEC();
                            elReceptor.identificacion     = idReceptor;
                            elReceptor.identificacionTipo = tipo;
                            elReceptor.correoElectronico  = documento.receptor.correoElectronico;
                            if (documento.receptor.telefono != null)
                            {
                                elReceptor.telefonoCodigoPais = documento.receptor.telefono.codigoPais;
                                elReceptor.telefono           = documento.receptor.telefono.numTelefono;
                            }
                            elReceptor.nombre          = documento.receptor.nombre;
                            elReceptor.nombreComercial = documento.receptor.nombreComercial;
                            conexion.EmisorReceptorIMEC.Add(elReceptor);
                            conexion.SaveChanges();
                        }
                    }
                }
                responsePost = await ServicesHacienda.enviarDocumentoElectronico(false, documento, elEmisor, documento.tipoDocumento, Usuario.USUARIO_AUTOMATICO);
            }
            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(Request.CreateErrorResponse(HttpStatusCode.NotFound, fullErrorMessage));
                //return Ok(fullErrorMessage);
            }
            catch (Exception ex)
            {
                //return ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message));
                //return Ok(ex.Message);
            }
            //return responsePost;
            return(Request.CreateErrorResponse(HttpStatusCode.NotFound, responsePost));
            //return Ok(responsePost);
        }
Ejemplo n.º 18
0
        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);
            }
        }
        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();
            }
        }
Ejemplo n.º 20
0
        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();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// desabilita los campos que no son editables
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ASPxGridView1_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
        {
            if (e.Column.FieldName == "identificacion")
            {
                ASPxPageControl tabs           = (ASPxPageControl)ASPxGridView1.FindEditFormTemplateControl("pageControl");
                ASPxFormLayout  form           = (ASPxFormLayout)tabs.FindControl("formLayoutUbicacion");
                ASPxComboBox    comboProvincia = (ASPxComboBox)form.FindControl("cmbProvincia");

                if (comboProvincia.Items.Count == 0)
                {
                    this.cargarProvincias();
                }

                EmisorReceptorIMEC dato = null;
                using (var conexion = new DataModelFE())
                {
                    if (e.Editor.Value != null)
                    {
                        dato = conexion.EmisorReceptorIMEC.Find(e.Editor.Value.ToString());
                        if (dato != null)
                        {
                            comboProvincia.Value = dato.provincia;
                        }
                    }
                }
            }

            if (this.ASPxGridView1.IsNewRowEditing)
            {
                if (e.Column.FieldName == "identificacion")
                {
                    this.cargarProvincias();
                }

                if (e.Column.FieldName == "estado")
                {
                    e.Editor.Value = "ACTIVO";
                }
            }
            else
            {/******************  CUANDO ES UNA MODIFICACION   *******************/
                if (this.ASPxGridView1.IsEditing && e.Column.FieldName == "identificacion" && !String.IsNullOrEmpty(e.Editor.Value.ToString()) && Session["entro"].ToString() == "NO")
                {
                    Session["entro"] = "SI";
                    EmisorReceptorIMEC dato = null;
                    using (var conexion = new DataModelFE())
                    {
                        dato = conexion.EmisorReceptorIMEC.Find(e.Editor.Value.ToString());
                    }

                    ASPxPageControl tabs = (ASPxPageControl)ASPxGridView1.FindEditFormTemplateControl("pageControl");
                    ASPxFormLayout  form = (ASPxFormLayout)tabs.FindControl("formLayoutUbicacion");

                    this.cargarProvincias();

                    /* PROVINCIA */
                    ASPxComboBox comboProvincia = (ASPxComboBox)form.FindControl("cmbProvincia");
                    comboProvincia.Value = dato.provincia;

                    /* CANTON */
                    ASPxComboBox comboCanton = (ASPxComboBox)form.FindControl("cmbCanton");
                    comboCanton.Items.Clear();

                    /* DISTRITO */
                    ASPxComboBox comboDistrito = (ASPxComboBox)form.FindControl("cmbDistrito");
                    comboDistrito.Items.Clear();

                    /* BARRIO */
                    ASPxComboBox comboBarrio = (ASPxComboBox)form.FindControl("cmbBarrio");
                    comboBarrio.Items.Clear();

                    /* OTRA SEÑAS */
                    ASPxMemo otraSena = (ASPxMemo)form.FindControl("txtOtraSenas");
                    otraSena.Text = dato.otraSena;


                    using (var conexion = new DataModelFE())
                    {
                        foreach (var item in conexion.Ubicacion.
                                 Where(x => x.codProvincia == dato.provincia).
                                 Select(x => new { x.codCanton, x.nombreCanton }).Distinct())
                        {
                            comboCanton.Items.Add(item.nombreCanton, item.codCanton);
                        }
                        comboCanton.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
                        comboCanton.Value = dato.canton;


                        foreach (var item in conexion.Ubicacion.
                                 Where(x => x.codProvincia == dato.provincia).
                                 Where(x => x.codCanton == dato.canton).
                                 Select(x => new { x.codDistrito, x.nombreDistrito }).Distinct())
                        {
                            comboDistrito.Items.Add(item.nombreDistrito, item.codDistrito);
                        }
                        comboDistrito.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
                        comboDistrito.Value = dato.distrito;


                        foreach (var item in conexion.Ubicacion.
                                 Where(x => x.codProvincia == dato.provincia).
                                 Where(x => x.codCanton == dato.canton).
                                 Where(x => x.codDistrito == dato.distrito).
                                 Select(x => new { x.codBarrio, x.nombreBarrio }).Distinct())
                        {
                            comboBarrio.Items.Add(item.nombreBarrio, item.codBarrio);
                        }
                        comboBarrio.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
                        comboBarrio.Value = dato.barrio;
                    }
                }
            }
        }
Ejemplo n.º 22
0
        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();
            }
        }
Ejemplo n.º 23
0
        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";
            }
        }
Ejemplo n.º 24
0
        /// <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;
        }
Ejemplo n.º 25
0
        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());
        }
Ejemplo n.º 26
0
        /// <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);
        }
Ejemplo n.º 27
0
        /// <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();
            }
        }