private void SeleccionProvincia(object sender, SelectionChangedEventArgs e)
 {
     try
     {
         UbicacionesType provincia = (UbicacionesType)cb_Provincia.SelectedItem;
         cb_canton.ItemsSource = new UbicacionesData().GetCantones(provincia.Id);
     }
     catch (Exception ex)
     {
         this.LogError(ex);
         MessageBox.Show("Ocurrio al seleccionar la provincia", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        private void Guardar(object sender, RoutedEventArgs e)
        {
            try
            {
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    bool ClienteNuevo = false;
                    if (ClienteActual == null)
                    {
                        ClienteActual = new Cliente();
                        ClienteNuevo  = true;
                        ClienteActual.Id_Contribuyente = RecursosSistema.Contribuyente.Id_Contribuyente;
                    }
                    else
                    {
                        db.Cliente.Attach(ClienteActual);
                    }

                    ClienteActual.Nombre            = txt_Nombre.Text;
                    ClienteActual.CorreoElectronico = txt_Correo.Text;
                    if (string.IsNullOrEmpty(ClienteActual.Nombre))
                    {
                        MessageBox.Show("Favor ingresar el nombre del cliente", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }

                    if (string.IsNullOrEmpty(ClienteActual.CorreoElectronico))
                    {
                        MessageBox.Show("Favor ingresar el correo del cliente", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }

                    ClienteActual.NombreComercial       = txt_comercial.Text;
                    ClienteActual.Identificacion_Numero = txt_Identificacion.Text;

                    if (!string.IsNullOrEmpty(ClienteActual.Identificacion_Numero))
                    {
                        for (int i = 0; i < ClienteActual.Identificacion_Numero.Length; i++)
                        {
                            if (!char.IsDigit(ClienteActual.Identificacion_Numero[i]))
                            {
                                MessageBox.Show("El numero de identificacion solo puede contener nuemeros", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                                return;
                            }
                        }
                    }

                    if (cb_Cedula.SelectedItem != null && !string.IsNullOrEmpty((cb_Cedula.SelectedItem as ComboBoxItem).Tag as string))
                    {
                        ClienteActual.Identificacion_Tipo = (cb_Cedula.SelectedItem as ComboBoxItem).Tag.ToString();
                    }
                    else
                    {
                        ClienteActual.Identificacion_Tipo = null;
                    }

                    #region Telefono
                    if (string.IsNullOrEmpty(txt_TelefonoRegion.Text))
                    {
                        ClienteActual.Telefono_Codigo = null;
                    }
                    else
                    {
                        if (!int.TryParse(txt_TelefonoRegion.Text, out int Region))
                        {
                            MessageBox.Show("Favor llenar el campo de region (solamente numeros) ", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.Telefono_Codigo = Region;
                    }

                    if (string.IsNullOrEmpty(txt_TelefonoNumero.Text))
                    {
                        ClienteActual.Telefono_Numero = null;
                    }
                    else
                    {
                        if (!int.TryParse(txt_TelefonoNumero.Text, out int telefono))
                        {
                            MessageBox.Show("Favor llenar el campo de telefono (solamente numeros)", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.Telefono_Numero = telefono;
                    }
                    #endregion

                    #region Ubicacion
                    UbicacionesType provincia = cb_Provincia.SelectedItem as UbicacionesType;
                    if (provincia != null)
                    {
                        ClienteActual.Provincia = provincia.Id;
                        UbicacionesType canton = cb_canton.SelectedItem as UbicacionesType;
                        if (canton == null)
                        {
                            MessageBox.Show("Favor seleccionar una Canton", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.Canton = canton.Id;


                        UbicacionesType Distrito = cb_distrito.SelectedItem as UbicacionesType;
                        if (Distrito == null)
                        {
                            MessageBox.Show("Favor seleccionar una Distrito", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.Distrito = Distrito.Id;


                        UbicacionesType Barrio = cb_barrio.SelectedItem as UbicacionesType;
                        if (Distrito == null)
                        {
                            MessageBox.Show("Favor seleccionar una Barrio", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.Barrio = Barrio.Id;


                        if (string.IsNullOrEmpty(txt_otrasSenas.Text))
                        {
                            MessageBox.Show("Favor llenar el campo de otras senas", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                        ClienteActual.OtrasSenas = txt_otrasSenas.Text;
                    }
                    #endregion

                    if (!string.IsNullOrEmpty(ClienteActual.Identificacion_Numero) && ClienteNuevo)
                    {
                        if (db.Cliente.Any(q => q.Identificacion_Numero == ClienteActual.Identificacion_Numero))
                        {
                            MessageBox.Show("Ya existe un cliente con ese numero de identificacion", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                    }
                    else if (ClienteNuevo)
                    {
                        if (db.Cliente.Any(q => q.Nombre == ClienteActual.Nombre))
                        {
                            MessageBox.Show("Ya existe un cliente con ese nombre registrado", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                            return;
                        }
                    }

                    if (ClienteNuevo)
                    {
                        db.Cliente.Add(ClienteActual);
                    }

                    db.SaveChanges();
                    Volver(sender, e);
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Error al guardar datos del cliente", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Guardar(object sender, RoutedEventArgs e)
        {
            try
            {
                bool ExisteContribuyente = true;
                using (db_FacturaDigital db = new db_FacturaDigital())
                {
                    DataModel.EF.Contribuyente Contribuyente = db.Contribuyente.FirstOrDefault();
                    if (Contribuyente == null)
                    {
                        ExisteContribuyente = false;
                        Contribuyente       = new DataModel.EF.Contribuyente();
                    }

                    #region DatosGenerales
                    if (string.IsNullOrEmpty(txt_Identificacion.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de identificacion", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Identificacion_Numero = txt_Identificacion.Text;
                    Contribuyente.Identificacion_Tipo   = (cb_Cedula.SelectedItem as ComboBoxItem).Tag.ToString();


                    if (string.IsNullOrEmpty(txt_Nombre.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de nombre", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Nombre = txt_Nombre.Text;



                    if (string.IsNullOrEmpty(txt_comercial.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de nombre comercial", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.NombreComercial = txt_comercial.Text;

                    if (string.IsNullOrEmpty(txt_Correo.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de correo", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.CorreoElectronico = txt_Correo.Text;
                    int Region;
                    if (!int.TryParse(txt_TelefonoRegion.Text, out Region))
                    {
                        MessageBox.Show("Favor llenar el campo de region (solamente numeros) ", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Telefono_Codigo = Region;

                    int telefono;
                    if (!int.TryParse(txt_TelefonoNumero.Text, out telefono))
                    {
                        MessageBox.Show("Favor llenar el campo de telefono (solamente numeros)", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Telefono_Numero = telefono;
                    #endregion

                    #region Ubicacion
                    UbicacionesType provincia = cb_Provincia.SelectedItem as UbicacionesType;
                    if (provincia == null)
                    {
                        MessageBox.Show("Favor seleccionar una provincia", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Provincia = provincia.Id;


                    UbicacionesType canton = cb_canton.SelectedItem as UbicacionesType;
                    if (canton == null)
                    {
                        MessageBox.Show("Favor seleccionar una Canton", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Canton = canton.Id;


                    UbicacionesType Distrito = cb_distrito.SelectedItem as UbicacionesType;
                    if (Distrito == null)
                    {
                        MessageBox.Show("Favor seleccionar una Distrito", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Distrito = Distrito.Id;


                    UbicacionesType Barrio = cb_barrio.SelectedItem as UbicacionesType;
                    if (Distrito == null)
                    {
                        MessageBox.Show("Favor seleccionar una Barrio", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Barrio = Barrio.Id;


                    if (string.IsNullOrEmpty(txt_otrasSenas.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de otras senas", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.OtrasSenas = txt_otrasSenas.Text;
                    #endregion

                    #region Datos Hacienda
                    if (string.IsNullOrEmpty(txt_UsuarioHacienda.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de usuario de hacienda ", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.UsuarioHacienda = txt_UsuarioHacienda.Text;


                    if (string.IsNullOrEmpty(txt_contrasena.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de contrasena de hacienda", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.ContrasenaHacienda = txt_contrasena.Text;
                    #endregion

                    #region Certificado
                    if (string.IsNullOrEmpty(CertificadoUrl) && (Contribuyente.Certificado == null || Contribuyente.Certificado.Length == 0))
                    {
                        MessageBox.Show("Favor seleccionar un certificado", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }

                    if (!string.IsNullOrEmpty(CertificadoUrl))
                    {
                        Contribuyente.Certificado = File.ReadAllBytes(CertificadoUrl);
                    }

                    if (string.IsNullOrEmpty(txt_contrasenaCertificado.Text))
                    {
                        MessageBox.Show("Favor llenar el campo de contrasena de certificado", "Validacion", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }
                    Contribuyente.Contrasena_Certificado = txt_contrasenaCertificado.Text;


                    try
                    {
                        X509Certificate2 x509 = new X509Certificate2(Contribuyente.Certificado, Contribuyente.Contrasena_Certificado, X509KeyStorageFlags.Exportable);
                        x509.Verify();
                        string Values       = x509.Subject.Split(',').First(q => q.ToUpper().Contains("SERIALNUMBER"));
                        string SerialNumber = Values.Split('=')[1];
                        string OnlyNumber   = new string(SerialNumber.Where(c => char.IsDigit(c)).ToArray());
                        if (!OnlyNumber.Contains(Contribuyente.Identificacion_Numero) && !Contribuyente.Identificacion_Numero.Contains(OnlyNumber))
                        {
                            if (MessageBox.Show("El numero de identificacion registrado en el certificado no concuerda con el ingresado por el usuario en el campo [Identificacion]. Aun asi desea continuar?", "Validacion", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                            {
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.LogError(ex);
                        MessageBox.Show("No se pudo abrir el ceritificado. Esto se puede deber a que la contrasena indicada no es valida o que el contenido del certificado es invalido", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                        return;
                    }


                    #endregion

                    if (!ExisteContribuyente)
                    {
                        db.Contribuyente.Add(Contribuyente);
                    }

                    db.SaveChanges();

                    Contribuyente_Consecutivos conse = db.Contribuyente_Consecutivos.FirstOrDefault(q => q.Id_Contribuyente == Contribuyente.Id_Contribuyente);

                    if (conse == null)
                    {
                        conse = new Contribuyente_Consecutivos()
                        {
                            Consecutivo_Facturas            = 1,
                            Consecutivo_NotasCredito        = 1,
                            Consecutivo_Tiquete_Electrónico = 1,
                            Consecutivo_Confirmacion        = 1,
                            Id_Contribuyente = Contribuyente.Id_Contribuyente
                        };
                        db.Contribuyente_Consecutivos.Add(conse);
                        db.SaveChanges();
                    }

                    MessageBox.Show("Perfil actualizado correctamente", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
                    try
                    {
                        RecursosSistema.Contribuyente = Contribuyente;
                        RecursosSistema.OnStartMain_Load();
                    }catch (Exception ex)
                    {
                        this.LogError(ex);
                        MessageBox.Show("Reinicie el sistema para continuar");
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex);
                MessageBox.Show("Ocurrio al guardar el perfil del contribuyente", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }