//Cristhian|14/02/2018|FEI2-487 /*NUEVO INICIO*/ /// <summary> /// Verifica si existe un documetno duplicado y si el documento seleccionado esta aceptado por SUNAT. /// Dependiendo de la verificación se habilitara y deshabilitara el botón de Descarga CDR. /// Si no tiene duplicado y esta aceptado por SUNAT se habilita el boton de descarga de CDR. /// Si tiene duplicado(s) y no esta aceptado por SUNAT se dehabilita el botón de descarga de CDR. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void m_Verificar_Duplicidad(object sender, RoutedEventArgs e) { clsBaseConfiguracion conf = new clsBaseConfiguracion(); /*Se intenta realizar el proceso*/ try { /*Se obtinene los datos del item Seleccionado*/ ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem; /*Si no tiene seleccionado no se realiza nada*/ if (item != null) { /*Se obtiene los datos de conexion de la base de datos*/ clsEntityDocument ce = new clsEntityDocument(localDB); /*Se envia los datos a la funcion "cs_Buscar_DocumentoDuplicado" que nos devolvera True or False*/ btncdr.IsEnabled = ce.cs_Buscar_DocumentoDuplicado(item.Id, item.SerieNumero, item.FechaEmision, item.Tipo); } } /*Si existe algun error se registra en el archivo log*/ catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("Buscar Duplicado Reporte Factura: " + ex.ToString()); } }
public frmUsuario(string modo, string id) { InitializeComponent(); /** Antiguo */ entidad_usuario = new clsBaseConfiguracion(); txtUsuario.Text = entidad_usuario.cs_prLoginUsuario; txtClave.Text = entidad_usuario.cs_prLoginPassword; /** Fin-Antiguo */ this.cs_cmModo = modo; switch (cs_cmModo) { case "UPD": user = new clsEntityUsers().cs_pxObtenerUnoPorId(id); txtUsuario.Text = user.Cs_pr_User; txtClave.Text = user.Cs_pr_Password; break; case "INS": user = new clsEntityUsers(); txtUsuario.Text = ""; txtClave.Text = ""; break; case "DLT": user = new clsEntityUsers().cs_pxObtenerUnoPorId(id); txtUsuario.Text = user.Cs_pr_User; txtUsuario.Enabled = false; txtClave.Text = user.Cs_pr_Password; txtClave.Enabled = false; this.btnGuardar.Text = "Eliminar"; break; } }
//Evento para guardar los cambios. private void btnGuardar_Click(object sender, RoutedEventArgs e) { if (existeCambios(entidad_basedatos) > 0) { //Asignar valores para la entidad de base de datos local entidad_basedatos.Cs_pr_DBMS = cboGestorBD.Text; entidad_basedatos.Cs_pr_DBMSDriver = txtDriver.Text; entidad_basedatos.Cs_pr_DBMSServername = txtServidor.Text; entidad_basedatos.Cs_pr_DBMSServerport = txtPuerto.Text; entidad_basedatos.Cs_pr_DBName = txtNombreBD.Text; entidad_basedatos.Cs_pr_DBUser = txtUsuario.Text; entidad_basedatos.Cs_pr_DBPassword = txtContrasenia.Password; entidad_basedatos.cs_pxActualizar(true); cs_pxActualizarEstado(); (this.Tag as MainWindow).EstadoMenu(cs_prConexionEstado, "1"); //Actualizar valores para la configuracion de base de datos. clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); configuracion.cs_prDbms = entidad_basedatos.Cs_pr_DBMS; configuracion.cs_prDbmsdriver = entidad_basedatos.Cs_pr_DBMSDriver; configuracion.cs_prDbmsservidor = entidad_basedatos.Cs_pr_DBMSServername; configuracion.cs_prDbmsservidorpuerto = entidad_basedatos.Cs_pr_DBMSServerport; configuracion.cs_prDbnombre = entidad_basedatos.Cs_pr_DBName; configuracion.cs_prDbusuario = entidad_basedatos.Cs_pr_DBUser; configuracion.cs_prDbclave = entidad_basedatos.Cs_pr_DBPassword; configuracion.cs_pxActualizar(false); } else { System.Windows.Forms.MessageBox.Show("No se han realizado cambios.", "Advertencia - Guardar", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// Genera un Documento de baja. /// </summary> /// <param name="Id">Id del documento.</param> /// <returns>NombreTributo del archivo generado.</returns> public string cs_pxGenerarResumenRA(string Id) { string archivo_nombre_XML = string.Empty; string archivo_nombre_ZIP = string.Empty; string archivo_nombre_directorio = string.Empty; string fila = string.Empty; try { clsEntityVoidedDocuments cabecera = new clsEntityVoidedDocuments(localDB); cabecera.cs_fxObtenerUnoPorId(Id); fila = new clsNegocioCEComunicacionBaja(localDB).cs_pxGenerarXMLAString(Id); #region Genera los nombres de archivo archivo_nombre_XML = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString() + ".xml"; archivo_nombre_ZIP = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString() + ".zip"; archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString(); string comprobante_ruta = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/"; string comprobante_ruta_nombre = comprobante_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML; if (File.Exists(comprobante_ruta_nombre)) { File.Delete(comprobante_ruta_nombre); } if (Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) { var dir = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); } if (!Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) { Directory.CreateDirectory(comprobante_ruta + archivo_nombre_directorio); } if (!File.Exists(comprobante_ruta_nombre)) { File.Create(comprobante_ruta_nombre).Close(); } // StreamWriter sw1 = new StreamWriter(comprobante_ruta_nombre); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; StreamWriter sw1 = new StreamWriter(File.Open(comprobante_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; DirectoryInfo x = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); cs_prComprimirZIP(x); #endregion } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("clsNegocioCE cs_pxGenerarResumenRA" + ex.ToString()); } return(archivo_nombre_ZIP); }
public string cs_pxGenerarGuiaRemision(string Id) { string archivo_nombre_XML = string.Empty, archivo_nombre_ZIP = string.Empty, archivo_nombre_directorio = string.Empty; try { clsEntityDespatch DespatchDocument = new clsEntityDespatch(localDB).cs_fxObtenerUnoPorId(Id); if (DespatchDocument.Cs_pr_EstadoSUNAT != "1") { string fila = string.Empty; fila = new clsNegocioCEGuiaRemision(localDB).cs_pxGenerarXMLAString(Id); #region Genera el nombre de archivo archivo_nombre_XML = declarante.Cs_pr_Ruc + "-" + "09" + "-" + DespatchDocument.Cs_tag_ID.ToString() + ".xml"; archivo_nombre_ZIP = declarante.Cs_pr_Ruc + "-" + "09" + "-" + DespatchDocument.Cs_tag_ID.ToString() + ".zip"; archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + "09" + "-" + DespatchDocument.Cs_tag_ID.ToString(); string documento_ruta = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/", documento_ruta_nombre = documento_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML; if (File.Exists(documento_ruta_nombre)) { File.Delete(documento_ruta_nombre); } if (Directory.Exists(documento_ruta + archivo_nombre_directorio)) { var dir = new DirectoryInfo(documento_ruta + archivo_nombre_directorio); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); } if (!Directory.Exists(documento_ruta + archivo_nombre_directorio)) { Directory.CreateDirectory(documento_ruta + archivo_nombre_directorio); } if (!File.Exists(documento_ruta_nombre)) { File.Create(documento_ruta_nombre).Close(); } // StreamWriter sw1 = new StreamWriter(documento_ruta_nombre); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; StreamWriter sw1 = new StreamWriter(File.Open(documento_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; DirectoryInfo x = new DirectoryInfo(documento_ruta + archivo_nombre_directorio); cs_prComprimirZIP(x); #endregion } return(archivo_nombre_ZIP); } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd(" clsNegocioCE cs_pxGenerarGuiaRemision " + ex.ToString()); return(null); } }
/// <summary> /// Creacion de los reportes en excel y csv /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnExportar_Click(object sender, RoutedEventArgs e) { string RutaReporte = string.Empty; FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog(); // BOTON DE NUEVO FOLDER ACTIVADO folderBrowserDlg.ShowNewFolderButton = true; // MOSTRAR CUADRO DE DIALOGO DialogResult dlgResult = folderBrowserDlg.ShowDialog(); if (dlgResult.Equals(DialogResult.OK)) { RutaReporte = folderBrowserDlg.SelectedPath; } if (lista_reporte.Count > 0) { if (RutaReporte.Trim().Length > 0) { clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); switch (cboDownload.SelectedIndex) { case 0: clsBaseReporte.cs_pxReportePDF_Validar(lista_reporte, RutaReporte + "\\VALIDAR-" + DateTime.Today.Date.ToShortDateString().Replace('/', '-') + "--" + DateTime.Now.ToShortTimeString().Replace(':', '-') + ".pdf"); break; case 1: clsBaseReporte.cs_pxReporteCSV_Validar(lista_reporte, RutaReporte + "\\VALIDAR-" + DateTime.Today.Date.ToShortDateString().Replace('/', '-') + "--" + DateTime.Now.ToShortTimeString().Replace(':', '-') + ".csv"); break; } } else { clsBaseMensaje.cs_pxMsgError("Error al generar reporte", "Seleccione una ruta valida."); } } else { clsBaseMensaje.cs_pxMsgError("Error al generar reporte", "Debe existir datos listados para generar el reporte."); } }
//Evento para descargar reporte. private void btnReporte_Click(object sender, RoutedEventArgs e) { if (lista_reporte.Count > 0) { clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); switch (cboDownload.SelectedIndex) { case 0: clsBaseReporte.cs_pxReportePDF(lista_reporte, configuracion.cs_prRutareportesPDF + "\\FACTURAS-" + DateTime.Today.Date.ToShortDateString().Replace('/', '-') + "--" + DateTime.Now.ToShortTimeString().Replace(':', '-') + ".pdf"); break; case 1: clsBaseReporte.cs_pxReporteCSV(lista_reporte, configuracion.cs_prRutareportesCSV + "\\FACTURAS-" + DateTime.Today.Date.ToShortDateString().Replace('/', '-') + "--" + DateTime.Now.ToShortTimeString().Replace(':', '-') + ".csv"); break; } } else { clsBaseMensaje.cs_pxMsg("Error al generar reporte", "Debe existir datos listados para generar el reporte."); } }
private void btnCrear_Click(object sender, EventArgs e) { entidad_basedatos.Cs_pr_DBMS = cboGestorBasedatos.Text; entidad_basedatos.Cs_pr_DBMSDriver = txtDbmsdriver.Text; entidad_basedatos.Cs_pr_DBMSServername = txtDbmsservidor.Text; entidad_basedatos.Cs_pr_DBMSServerport = txtDbmsservidorpuerto.Text; entidad_basedatos.Cs_pr_DBName = txtDbnombre.Text; entidad_basedatos.Cs_pr_DBUser = txtDbusuario.Text; entidad_basedatos.Cs_pr_DBPassword = txtDbclave.Text; entidad_basedatos.cs_pxActualizar(false); cs_pxActualizarEstado(); clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); configuracion.cs_prDbms = entidad_basedatos.Cs_pr_DBMS; configuracion.cs_prDbmsdriver = entidad_basedatos.Cs_pr_DBMSDriver; configuracion.cs_prDbmsservidor = entidad_basedatos.Cs_pr_DBMSServername; configuracion.cs_prDbmsservidorpuerto = entidad_basedatos.Cs_pr_DBMSServerport; configuracion.cs_prDbnombre = entidad_basedatos.Cs_pr_DBName; configuracion.cs_prDbusuario = entidad_basedatos.Cs_pr_DBUser; configuracion.cs_prDbclave = entidad_basedatos.Cs_pr_DBPassword; configuracion.cs_pxActualizar(false); entidad_basedatos.cs_pxCrearBaseDatos(); }
void App_Startup(object sender, StartupEventArgs e) { if (!isPermited()) { clsBaseMensaje.cs_pxMsgEr("ERR20", ""); isInitialized = false; System.Windows.Application.Current.Shutdown(); } else { //Buscar la ruta de almacen de archivos de FEI. string ruta = new clsRegistry().Read("RUTA"); if (ruta == null) {//En caso no exista mostrar el formulario de seleccion de ruta. frmSelect f = new frmSelect(); if (f.ShowDialog() == DialogResult.OK) { //Si ingresa la ruta mostrar el inicion de sesion. //InicioSesion inicio = new InicioSesion(); //inicio.Show(); presentacion Presentacion_FEI = new presentacion(); Presentacion_FEI.Show(); } } else { //Iniciar configuracion actual y mostrar inicio de sesion. clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); //Mostrar formulario de Inicio de Sesion. //InicioSesion inicio = new InicioSesion(); //inicio.Show(); presentacion Presentacion_FEI = new presentacion(); Presentacion_FEI.Show(); } } }
private void btnGuardar_Click(object sender, EventArgs e) { string ruta = textBox1.Text; if (ruta.Trim() != "" && Directory.Exists(ruta)) { string existe = new clsRegistry().Read("RUTA"); bool registrado = false; if (existe == null) { //noexiste registrado = new clsRegistry().Write("RUTA", ruta); } else { new clsRegistry().DeleteKey("RUTA"); registrado = new clsRegistry().Write("RUTA", ruta); } if (!registrado) { MessageBox.Show("Ocurrio un error al guardar la ruta.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error); //MessageBox.Show("Ocurrio un error al guardar la ruta."); } else { MessageBox.Show("La ruta fue almacenada con exito.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); this.DialogResult = DialogResult.OK; this.Close(); } } else { MessageBox.Show("Seleccione una ruta valida.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } }
/// <summary> /// Genera un Comprobate de pago: factura, boletas y sus NC y ND asociadas. /// </summary> /// <param name="Id">Id del comprobante.</param> /// <returns>NombreTributo del archivo generado.</returns> public string cs_pxGenerarCE(string Id) { string fila = string.Empty; string archivo_nombre_XML = string.Empty, archivo_nombre_ZIP = string.Empty, archivo_nombre_directorio = string.Empty; try { clsEntityDocument cabecera = new clsEntityDocument(localDB); cabecera.cs_fxObtenerUnoPorId(Id); //fila = cs_pxGenerarXMLaString(Id,localDB); switch (cabecera.Cs_tag_InvoiceTypeCode) { case "01": fila = new clsNegocioCEFactura(localDB).cs_pxGenerarXMLAString(Id); break; case "03": fila = new clsNegocioCEBoleta(localDB).cs_pxGenerarXMLAString(Id); break; case "07": fila = new clsNegocioCENotaCredito(localDB).cs_pxGenerarXMLAString(Id); break; case "08": fila = new clsNegocioCENotaDebito(localDB).cs_pxGenerarXMLAString(Id); break; } #region Genera los nombres de archivo archivo_nombre_XML = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID + ".xml"; archivo_nombre_ZIP = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID + ".zip"; archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_InvoiceTypeCode + "-" + cabecera.Cs_tag_ID; string comprobante_ruta = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/"; string comprobante_ruta_nombre = comprobante_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML; if (File.Exists(comprobante_ruta_nombre)) // Sí existe el archivo comprobante_ruta_nombre { File.Delete(comprobante_ruta_nombre); // se elimina } if (Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) // Sí existe el directorio { var dir = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); // Instancia de la clase DirectoryInfo dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; // Asignación de su atributo dir.Delete(true); // Permitir eliminar de forma recursiva } if (!Directory.Exists(comprobante_ruta + archivo_nombre_directorio)) // Sí no existe el directorio { Directory.CreateDirectory(comprobante_ruta + archivo_nombre_directorio); // Lo creamos ;) } if (!File.Exists(comprobante_ruta_nombre)) // Sí el archivo no existe { File.Create(comprobante_ruta_nombre).Close(); // También lo creamos ;) ;) } StreamWriter sw1 = new StreamWriter( File.Open(comprobante_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); // Códifica el archivo generado sw1.WriteLine(fila); sw1.Close(); fila = string.Empty; DirectoryInfo x = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); cs_prComprimirZIP(x); #endregion } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("clsNegocioCE cs_pxGenerarCE" + ex.ToString()); } return(archivo_nombre_ZIP); }
/// <summary> /// Evento Ingresar al sistema. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnIngresar_Click(object sender, RoutedEventArgs e) { //System.Windows.Forms.MessageBox.Show("Todos los comprobantes se agregaron a su respectiva comunicacion de baja","Mensaje",MessageBoxButtons.OK,MessageBoxIcon.Information); try { //txtUsuario.IsKeyboardFocused //btnIngresar.IsEnabled = false; regla_login = false; regla_account = false; //Obtener si usuario esta registrado. userid = new clsEntityUsers().cs_pxLogin(txtUsuario.Text.Trim(), txtPassword.Password.Trim()); if (userid.Length > 0) regla_login = true; //Obtener valor empresa seleccionado. if (cboEmpresa.IsEnabled == false) seleccion_empresa = ""; else { //En caso no exista una empresa seleccionado if (cboEmpresa.SelectedValue != null) { seleccion_empresa = cboEmpresa.SelectedValue.ToString(); //Obtener la configuracion de base de datos para la empresa seleccionada. clsEntityDatabaseLocal bd = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(seleccion_empresa); clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); configuracion.cs_prDbms = bd.Cs_pr_DBMS; configuracion.cs_prDbmsdriver = bd.Cs_pr_DBMSDriver; configuracion.cs_prDbmsservidor = bd.Cs_pr_DBMSServername; configuracion.cs_prDbmsservidorpuerto = bd.Cs_pr_DBMSServerport; configuracion.cs_prDbnombre = bd.Cs_pr_DBName; configuracion.cs_prDbusuario = bd.Cs_pr_DBUser; configuracion.cs_prDbclave = bd.Cs_pr_DBPassword; configuracion.Cs_pr_Declarant_Id = seleccion_empresa; configuracion.cs_pxActualizar(false); } // seleccion_empresa = cboEmpresa.SelectedValue.ToString(); } //Iniciar instancia del perfil Profile = new clsEntityAccount(); Profile_Id = Profile.dgvVerificarCuenta(userid, seleccion_empresa); if (Profile_Id != "") regla_account = true; if (regla_login == true && regla_account == true) { //Si el login es correcto y pertenece al perfil clsEntityDatabaseLocal local = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(seleccion_empresa); clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(seleccion_empresa); clsBaseConexion con = new clsBaseConexion(local); bool estado = con.cs_fxConexionEstadoServidor(); //Si la conexion al servidor de base de datos es correcta Hide(); if (estado == true) { // verifica el estado de la base de datos bool actualizar = new clsEntityDatabaseLocal(declarante).cs_pxSeDebeActualizarBD(); //Determinar si se debe actualizar, versión antigua if (actualizar) { //Mostrar mensaje para pedir confirmacion de actualizacion de base de datos. if (System.Windows.Forms.MessageBox.Show("Es necesario actualizar la estructura de la base de datos.Si escoge continuar se realizara ahora, caso contrario puede hacerlo despues utilizando la opcion verificar estructura.\n ¿Desea continuar?", "Verificar estructura - Base de Datos", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes) { new Loading(declarante).ShowDialog(); } } //Nuevo cambio para actualizar la estructura de la base de datos } // Verificar sí se esta haciendo pruebas //if(DoTest == true) // new pages.FormPruebas().Show(); //else //Cargar la ventana principal // new MainWindow(new clsEntityAccount().cs_fxObtenerUnoPorId(Profile_Id)).Show(); } else { //Mensaje de error en inicio de sesion. clsBaseMensaje.cs_pxMsgEr("ERR12", "Error de inicio de sesión."); } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("btnIngresar " + ex.ToString()); } }
static void Main(string[] args) { /* if (PriorProcess() != null) * { * clsBaseMensaje.cs_pxMsgEr("ERR20", ""); * return; * }*/ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); /* string Code = GetMD5("FEI-Contasis-2016"); * if (args.Length > 0) * { * if (args[0].ToString() == Code) * {*/ try { /* if (args.Length > 0) * { * if (args[0].ToString() == "1") * {*/ // Application.Run(new frmLogin()); string ruta = new clsRegistry().Read("RUTA"); if (ruta == null) { frmSelect f = new frmSelect(); if (f.ShowDialog() == DialogResult.OK) { Application.Run(new frmLogin()); } } else { clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); Application.Run(new frmLogin()); } /* } * else * { * MessageBox.Show("Inicie desde FEI.exe"); * } * * } * else * { * MessageBox.Show("Inicie desde FEI.exe"); * }*/ } catch (Exception) { //throw; } /* } * else * { * MessageBox.Show("Es necesario iniciar la aplicacion desde el lanzador de FEI"); * } * } * else * { * MessageBox.Show("Es necesario iniciar la aplicacion desde el lanzador de FEI"); * }*/ }
private void btnIniciar_Click(object sender, EventArgs e) { bool regla_login = false, regla_account = false; string userid = new clsEntityUsers().cs_pxLogin(this.txtUsuario.Text, this.txtContrasenia.Text); if (userid.Length > 0) { regla_login = true; } string seleccion_empresa; if (cboEmpresa.Enabled == false) { seleccion_empresa = ""; } else { seleccion_empresa = cboEmpresa.SelectedValue.ToString(); clsEntityDatabaseLocal bd = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(seleccion_empresa); clsBaseConfiguracion configuracion = new clsBaseConfiguracion(); configuracion.cs_prDbms = bd.Cs_pr_DBMS; configuracion.cs_prDbmsdriver = bd.Cs_pr_DBMSDriver; configuracion.cs_prDbmsservidor = bd.Cs_pr_DBMSServername; configuracion.cs_prDbmsservidorpuerto = bd.Cs_pr_DBMSServerport; configuracion.cs_prDbnombre = bd.Cs_pr_DBName; configuracion.cs_prDbusuario = bd.Cs_pr_DBUser; configuracion.cs_prDbclave = bd.Cs_pr_DBPassword; configuracion.Cs_pr_Declarant_Id = seleccion_empresa; configuracion.cs_pxActualizar(false); } clsEntityAccount Profile = new clsEntityAccount(); string Profile_Id = Profile.dgvVerificarCuenta(userid, seleccion_empresa); if (Profile_Id != "") { regla_account = true; } if (regla_login == true && regla_account == true) { // this.Close(); Hide(); clsBaseConexion con = new clsBaseConexion(); bool estado = con.cs_fxConexionEstadoServidor(); if (estado == true) { bool actualizar = new clsEntityDatabaseLocal().cs_pxSeDebeActualizarBD(); if (actualizar) { if (MessageBox.Show("Es necesario actualizar la estructura de la base de datos.Si escoge continuar se realizara ahora, caso contrario puede hacerlo despues utilizando la opcion verificar estructura.\n ¿Desea continuar?", "Verificar estructura - Base de Datos", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { new frmLoading().ShowDialog(); } } } new frmSistema(new clsEntityAccount().cs_fxObtenerUnoPorId(Profile_Id)).Show(); } else { clsBaseMensaje.cs_pxMsgEr("ERR12", "Error de inicio de sesión."); } }
private string restaurarUnico(clsEntityDatabaseLocal local, string cadenaConexionServidor, string rutaArchivo) { string retorno = string.Empty; try { clsBaseConfiguracion conf = new clsBaseConfiguracion(); //string[] Partes_Cadena_Conexion = cadenaConexionServidor.Split(';'); //cadenaConexionServidor = Partes_Cadena_Conexion[1] + ";" + Partes_Cadena_Conexion[2] + ";" + Partes_Cadena_Conexion[3] + ";"; //SqlConnection sqlcon = new SqlConnection(cadenaConexionServidor); OdbcConnection sqlcon = new OdbcConnection(cadenaConexionServidor); sqlcon.Open(); string UseMaster = "USE master"; string DatabaseFullPath = local.Cs_pr_DBName; string backUpPath = rutaArchivo; try { //SqlCommand UseMasterCommand = new SqlCommand(UseMaster,sqlcon); OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon); UseMasterCommand.ExecuteNonQuery(); } catch (Exception ex1) { retorno = ex1.Message; } string Alter1 = @"ALTER DATABASE " + DatabaseFullPath + " SET Single_User WITH Rollback Immediate"; try { //SqlCommand Alter1Cmd = new SqlCommand(Alter1,sqlcon); OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon); Alter1Cmd.ExecuteNonQuery(); } catch (Exception ex2) { retorno = ex2.Message; } List <string> tabla_contenidos = new List <string>(); //Cristhian|23/01/2018|FEICONT2-533 /*Se cambia la consulta SQL para traer el nombre de los archivos .mdf y .ldf de la base de datos*/ /*INICIO MODIFICACIóN*/ /*Se declara la sentencia SQL que obtiene el nombre los archivos .mdf y .ldf*/ string Alter10 = "RESTORE FILELISTONLY FROM DISK = '" + backUpPath + "' "; DataTable tabla_datos_archivos = new DataTable(); try { //SqlCommand Alter10Cmd = new SqlCommand(Alter10,sqlcon); OdbcCommand Alter10Cmd = new OdbcCommand(Alter10, sqlcon); /*Se ejecuta el comando DataAdapter y para que los datos se guarden en un data table*/ //SqlDataAdapter TableAdapt = new SqlDataAdapter(Alter10, sqlcon); OdbcDataAdapter TableAdapt = new OdbcDataAdapter(Alter10, sqlcon); /*Se llena de datos el datatable*/ TableAdapt.Fill(tabla_datos_archivos); } catch (Exception ex3) { /*Si no se cumple, se obtiene el mensaje de error para registrarlo*/ retorno = ex3.Message; } string[] UbicacionAnterior = tabla_datos_archivos.Rows[0][0].ToString().Split('\\'); int numeroItems_UA = UbicacionAnterior.Count(); string[] NombreArchivo = UbicacionAnterior[UbicacionAnterior.Count() - 1].Split('.'); try { /*Antes de modificar la cadena de restauracion, se debe verificar el archivo log del FEICONT*/ /*Aqui esta la sentencia SQL para restaurar la base de datos, en el cual tambien movemos el archivo .mdf y ldf hacia nuestra carpeta de las bases de datos*/ string Restore = @"RESTORE DATABASE [" + DatabaseFullPath + "] FROM DISK = N'" + backUpPath + @"' WITH FILE = 1, MOVE N'" + tabla_datos_archivos.Rows[0][0].ToString() + "' TO N'" + conf.cs_prRutainstalacion + "\\BackUp\\" + DatabaseFullPath + ".mdf', MOVE N'" + tabla_datos_archivos.Rows[1][0].ToString() + "' TO N'" + conf.cs_prRutainstalacion + "\\BackUp\\" + DatabaseFullPath + "_log.ldf', NOUNLOAD, REPLACE, STATS = 5"; /*Se ejecuta el comando SQL Server*/ //SqlCommand RestoreCmd = new SqlCommand(Restore, sqlcon); OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon); RestoreCmd.ExecuteNonQuery(); retorno = ""; } catch (Exception restore) { if (NombreArchivo[0] != DatabaseFullPath) { retorno = "La base de datos " + DatabaseFullPath + " no coincide con la base de datos que se quiere restaurar, que es: " + NombreArchivo[0]; } else { retorno = restore.Message; } } /*FIN MODIFICACIóN*/ // the below query change the database back to multiuser string Alter2 = @"ALTER DATABASE " + DatabaseFullPath + " SET Multi_User"; try { //SqlCommand Alter2Cmd = new SqlCommand(Alter2,sqlcon); OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon); Alter2Cmd.ExecuteNonQuery(); } catch (Exception ex4) { retorno = ex4.Message; } sqlcon.Close(); } catch (Exception ex) { retorno = ex.Message; clsBaseLog.cs_pxRegistarAdd("restback" + ex.ToString()); //System.Windows.Forms.MessageBox.Show("Se ha producido un error al procesar la restauración de backup.\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(retorno); }
private string procesarBackup(string cadenaConexionServidor, string dbName, string rutaArchivo) { string retorno = string.Empty; try { clsBaseConfiguracion conf = new clsBaseConfiguracion(); OdbcConnection sqlcon = new OdbcConnection(cadenaConexionServidor); sqlcon.Open(); string UseMaster = "USE master"; string DatabaseFullPath = dbName; string backUpPath = rutaArchivo; try { OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon); UseMasterCommand.ExecuteNonQuery(); } catch { retorno = "2"; } // The below query will rollback any transaction which is running on that database and brings SQL Server database in a single user mode. string Alter1 = @"ALTER DATABASE " + DatabaseFullPath + " SET Single_User WITH Rollback Immediate"; try { OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon); Alter1Cmd.ExecuteNonQuery(); } catch { retorno = "2"; } //Cristhian|23/01/2018|FEICONT2-533 /*Se cambia la consulta SQL para traer el nombre de los archivos .mdf y .ldf de la base de datos*/ /*INICIO MODIFICACIóN*/ /*Se declara la sentencia SQL que obtiene el nombre los archivos .mdf y .ldf*/ string Alter10 = "RESTORE FILELISTONLY FROM DISK = '" + backUpPath + "' "; DataTable tabla_datos_archivos = new DataTable(); try { OdbcCommand Alter10Cmd = new OdbcCommand(Alter10, sqlcon); /*Se ejecuta el comando DataAdapter y para que los datos se guarden en un data table*/ OdbcDataAdapter TableAdapt = new OdbcDataAdapter(Alter10, sqlcon); /*Se llena de datos el datatable*/ TableAdapt.Fill(tabla_datos_archivos); } catch { /*Si no se cumple, se obtiene el mensaje de error para registrarlo*/ retorno = "2"; } try { /*Antes de modificar la cadena de restauracion, se debe verificar el archivo log del FEICONT*/ /*Aqui esta la sentencia SQL para restaurar la base de datos, en el cual tambien movemos el archivo .mdf y ldf hacia nuestra carpeta de las bases de datos*/ string Restore = @"RESTORE DATABASE [" + DatabaseFullPath + "] FROM DISK = N'" + backUpPath + @"' WITH FILE = 1, MOVE N'" + tabla_datos_archivos.Rows[0][0].ToString() + "' TO N'" + conf.cs_prRutainstalacion + "\\" + DatabaseFullPath + ".mdf', MOVE N'" + tabla_datos_archivos.Rows[1][0].ToString() + "' TO N'" + conf.cs_prRutainstalacion + "\\" + DatabaseFullPath + "_log.ldf', NOUNLOAD, REPLACE, STATS = 5"; /*Se ejecuta el comando SQL Server*/ OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon); RestoreCmd.ExecuteNonQuery(); retorno = "1"; } catch { retorno = "2"; } /*FIN MODIFICACIóN*/ // the below query change the database back to multiuser string Alter2 = @"ALTER DATABASE " + DatabaseFullPath + " SET Multi_User"; try { OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon); Alter2Cmd.ExecuteNonQuery(); } catch { retorno = "2"; } sqlcon.Close(); //retorno = "1"; } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("restback " + ex.ToString()); retorno = "2"; } return(retorno); }
private void btnDescargaCDR_Click(object sender, RoutedEventArgs e) { btncdr.IsEnabled = false; clsBaseConfiguracion conf = new clsBaseConfiguracion(); //Obtener el usuario seleccionado. ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem; //Si existe el item seleccionado. if (item != null) { /* if (item.EstadoSunatCodigo == "0" || item.EstadoSunatCodigo == "1" || item.EstadoSunatCodigo == "3") * {*/ clsEntityDeclarant declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(localDB.Cs_pr_Declarant_Id); string nombreCarpeta = declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".zip-dc"; string[] dirs = Directory.GetDirectories(conf.cs_prRutadocumentosrecepcion, "*" + nombreCarpeta); if (dirs.Length > 0) { string rutaOpen = string.Empty; foreach (string dir in dirs) { rutaOpen = dir; } //existe el cdr Process.Start("explorer.exe", rutaOpen); } else { try { //descargar el cdr string[] partes = item.SerieNumero.Split('-'); string serie = partes[0]; int numero = Convert.ToInt32(partes[1]); byte[] comprobante_electronico_bytes = null; SecurityBindingElement binding = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); binding.IncludeTimestamp = false; ServicioCDR.billServiceClient bsc = new ServicioCDR.billServiceClient(new CustomBinding(binding, new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement()), new EndpointAddress("https://www.sunat.gob.pe:443/ol-it-wsconscpegem/billConsultService")); bsc.ClientCredentials.UserName.UserName = declarante.Cs_pr_Ruc + declarante.Cs_pr_Usuariosol; bsc.ClientCredentials.UserName.Password = declarante.Cs_pr_Clavesol; ServicioCDR.statusResponse sr = new ServicioCDR.statusResponse(); bsc.Open(); sr = bsc.getStatusCdr(declarante.Cs_pr_Ruc, item.Tipo, serie, numero); string code = sr.statusCode; if (sr.statusCode == "0004") { comprobante_electronico_bytes = sr.content; } bsc.Close(); if (comprobante_electronico_bytes != null) { XmlDocument documentoXML = new XmlDocument(); string comprobante_electronico = declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".zip"; string FechaHora = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"); string CDR = conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico; FileStream fs = new FileStream(CDR, FileMode.Create); fs.Write(comprobante_electronico_bytes, 0, comprobante_electronico_bytes.Length); fs.Close(); //string FechaHora = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"); //Verificar el contenido del archivo ZipFile.ExtractToDirectory(conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico, conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc"); documentoXML.Load(conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc\\" + "R-" + declarante.Cs_pr_Ruc + "-" + item.Tipo + "-" + item.SerieNumero + ".xml"); clsEntityDocument ce = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(item.Id); ce.Cs_pr_EstadoSCC = "0"; if (documentoXML.OuterXml.Contains("ha sido aceptad")) { ce.Cs_pr_EstadoSUNAT = "0"; ce.Cs_pr_CDR = documentoXML.OuterXml; } else { ce.Cs_pr_EstadoSUNAT = "1"; ce.Cs_pr_CDR = documentoXML.OuterXml; } string cadena_xml = @documentoXML.OuterXml; cadena_xml = cadena_xml.Replace("ext:", ""); cadena_xml = cadena_xml.Replace("cbc:", ""); cadena_xml = cadena_xml.Replace("cac:", ""); cadena_xml = cadena_xml.Replace("ds:", ""); cadena_xml = cadena_xml.Replace("ar:", ""); cadena_xml = cadena_xml.Replace("\\\"", "\""); if (cadena_xml.Trim().Length > 0) { cadena_xml = cadena_xml.Replace("<ApplicationResponse xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2\" xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\" xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\">", "<ApplicationResponse>"); XmlDocument d = new XmlDocument(); d.LoadXml(cadena_xml); ce.Cs_pr_ComentarioSUNAT = d.SelectSingleNode("/ApplicationResponse/DocumentResponse/Response/Description").InnerText; } ce.cs_pxActualizar(false, false); System.Windows.Forms.MessageBox.Show("El CDR correspondiente se ha descargado correctamente.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); cargarGrilla(); Process.Start("explorer.exe", conf.cs_prRutadocumentosrecepcion + "\\" + FechaHora + " " + comprobante_electronico + "-dc"); } else { System.Windows.Forms.MessageBox.Show("No se ha podido descargar el CDR correspondiente de la Sunat. Intente nuevamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("descrgar cdr" + ex.ToString()); System.Windows.Forms.MessageBox.Show("No se ha podido descargar el CDR correspondiente. Revise el archivo de errores para mayor información.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /* } * else * { * System.Windows.Forms.MessageBox.Show("Solo se puede descargar el CDR de comprobantes que hayan sido enviados a Sunat", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); * }*/ } else { System.Windows.Forms.MessageBox.Show("Seleccione un comprobante", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } btncdr.IsEnabled = true; }