Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Data.SqlClient;
- using System.Xml;
- using System.Data;
- using System.IO;
- using System.Runtime.InteropServices;
- using Microsoft.Office.Interop.Excel;
- namespace Seguros_Sociales
- {
- /// <summary>
- /// Lógica de interacción para MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- public static SqlConnection ConexBD; // Conexión a la BBDD
- string lastDate; // Almacena la última fecha, para acceso rápido con F7
- int CurrentId; // Almacena el ID actual de la BBDD
- bool isEdit = false; // Determina si estamos en modo edición (o consulta) o en modo insertar.
- static string currentSession = System.Environment.MachineName.ToString(); // Almacena la sesión actual (nombre del equipo)
- public MainWindow()
- {
- InitializeComponent();
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- try
- {
- XmlDocument xmlconex = new XmlDocument();
- xmlconex.Load(Directory.GetCurrentDirectory() + "\\Conexiones.xml");
- ConexBD = new SqlConnection(xmlconex.GetElementsByTagName("ConnectionString").Item(0).InnerText);
- ConexBD.Open();
- }
- catch (Exception ex)
- {
- Logger.log(ex);
- MessageBox.Show("Ha ocurrido un error, no se puede iniciar la aplicación");
- this.Close();
- }
- lblSesion.Content = "Sesión iniciada como " + currentSession;
- }
- private void Window_Unloaded(object sender, RoutedEventArgs e)
- {
- // Cerramos la conexión al cerrar la ventana.
- ConexBD.Close();
- }
- /// <summary>
- /// Click en "Datos Nuevos" que borrará el contenido anterior para comenzar un nuevo lote
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void DatosNuevos_Click(object sender, RoutedEventArgs e)
- {
- MessageBoxResult newDataPopUp = MessageBox.Show("Al insertar datos nuevos se borrarán los anteriores ¿Realmente desea continuar?", "Insertar nuevos datos", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
- if (newDataPopUp.ToString() == "Yes")
- {
- try
- {
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
- if (!sel.EOF)
- {
- sel.MoveLast();
- CurrentId = (int)sel.Campo("id");
- SqlCommand cmd = new SqlCommand("DELETE FROM Usuario WHERE sesion='" + currentSession + "'", ConexBD);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- }
- foreach (TextBox tb in FindChilds<TextBox>(this))
- {
- tb.IsEnabled = true;
- tb.Text = null;
- }
- this.txtTotal.Focus();
- this.btnSiguiente.IsEnabled = false;
- this.btnAnterior.IsEnabled = false;
- }
- catch (Exception ex)
- {
- Logger.log(ex);
- }
- }
- }
- /// <summary>
- /// Al pulsar ENTER | ADD en el último campo (txtFecha) se insertarán los datos
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void txtFecha_KeyDown(object sender, KeyEventArgs e)
- {
- TextBox tb = sender as TextBox;
- if (e.Key == Key.F7)
- tb.Text = lastDate;
- if (e.Key == Key.Subtract & tb.AcceptsReturn == false)
- MoveToPrevUIElement(e);
- if (((e.Key == Key.Enter || e.Key == Key.Add) & tb.AcceptsReturn == false))
- {
- lastDate = tb.Text;
- try { this.txtTotal.Text = (Convert.ToInt32(this.txtTotal.Text) - Convert.ToInt32(this.txtImporte.Text + this.txtImporteDec.Text)).ToString(); }
- catch { this.txtTotal.Text = this.txtTotal.Text; }
- try
- {
- SelectBD sel;
- if (isEdit == true)
- sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id='" + CurrentId + "'", "Seguros");
- else
- {
- sel = new SelectBD(ConexBD, "SELECT * FROM Seguros", "Seguros");
- sel.NuevoRegistro("Seguros");
- }
- sel.SetCampo("banco", this.txtBanco.Text);
- sel.SetCampo("sucursal", this.txtSucursal.Text);
- sel.SetCampo("provincia", this.txtProvincia.Text);
- sel.SetCampo("emisora", this.txtEmisora.Text);
- sel.SetCampo("referencia", this.txtReferencia.Text);
- sel.SetCampo("identificacion", this.txtIdentificacion.Text);
- sel.SetCampo("importe", this.txtImporte.Text);
- sel.SetCampo("importe_dec", this.txtImporteDec.Text);
- sel.SetCampo("fecha", this.txtFecha.Text);
- sel.SetCampo("fcreacion", DateTime.Today.ToString("ddMMyy"));
- sel.SetCampo("sesion", currentSession);
- if (isEdit == true)
- sel.AcceptChanges("Seguros");
- else
- sel.InsertaRegistro("Seguros");
- sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
- sel.MoveLast();
- CurrentId = (int)sel.Campo("id") + 1;
- }
- catch (Exception ex)
- {
- Logger.log(ex);
- }
- this.btnAnterior.IsEnabled = true;
- this.btnPrimero.IsEnabled = true;
- foreach (TextBox box in FindChilds<TextBox>(this))
- {
- if (box.IsEnabled == true & box.Name != "txtTotal")
- box.Text = null;
- }
- MoveToNextUIElement(e);
- }
- }
- /// <summary>
- /// Click en Archivo->Consulta Lote
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void ConsultaDatos_Click(object sender, RoutedEventArgs e)
- {
- LoadListOne(false);
- }
- /// <summary>
- /// Genera los ficheros de salida
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void GenerarFichero_Click(object sender, RoutedEventArgs e)
- {
- LoadListOne(true);
- string NombreBanco = new SelectBD(ConexBD, "SELECT * FROM Bancos WHERE referencia='" + this.txtBanco.Text + "'").Campo("nombre").ToString();
- CreateExcelDoc Excel = new CreateExcelDoc();
- CreateExcelDoc Excel2 = new CreateExcelDoc();
- Excel.createDoc(false);
- Excel2.createDoc(false);
- string valEmisora = "02827003";
- string codigoCabecera;
- if (DateTime.Today.Day > 7)
- codigoCabecera = "AE570200";
- else
- codigoCabecera = "AE570100";
- Excel.createHeaders(1, 8, (this.txtBanco.Text + " " + NombreBanco + " " + "RECAUDACIÓN: " + DateTime.Today.AddMonths(-1).ToString("Y") + " FECHA: " + DateTime.Today.ToString("dd-MM-yy")).ToUpper(), "A1", "H1", 8);
- Excel.createHeaders(2, 8, (" Cobro Por Ventanilla S. S. CONTROL DE DOCUMENTOS").ToUpper(), "A2", "H2", 8);
- Excel.createHeaders(3, 1, "N.ORDEN", "A3", "A3", 1);
- Excel.createHeaders(3, 2, "NUMERO REFERENCIA", "B3", "C3", 2);
- Excel.createHeaders(3, 4, "IMPORTE", "D3", "E3", 2);
- Excel.createHeaders(3, 6, "SUC", "F3", "F3", 1);
- Excel.createHeaders(3, 7, "EMISORA", "G3", "H3", 2);
- Excel2.createHeaders(1, 6, (this.txtBanco.Text + " " + NombreBanco + " " + "RECAUDACIÓN: " + DateTime.Today.AddMonths(-1).ToString("Y") + " FECHA: " + DateTime.Today.ToString("dd-MM-yy")).ToUpper(), "A1", "F1", 6);
- Excel2.createHeaders(2, 6, (" Cobro Por Ventanilla S. S. REMESAS PRESENTADAS POR SUCURSALES").ToUpper(), "A2", "F2", 6);
- Excel2.createHeaders(3, 1, "PROV", "A3", "A3", 1);
- Excel2.createHeaders(3, 2, "SUC", "B3", "B3", 1);
- Excel2.createHeaders(3, 3, "REFERENCIA", "C3", "D3", 2);
- Excel2.createHeaders(3, 5, "IMPORTE", "E3", "F3", 2);
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros");
- // Convertimos el DataTable de la query en un IENumerable, para poder tratarla como objeto
- // y poder organizar de mejor forma los resultados...
- var Query = sel.DataTable.AsEnumerable().Select(row =>
- {
- return new
- {
- banco = row["banco"].ToString(),
- emisora = row["emisora"].ToString(),
- sucursal = row["sucursal"].ToString(),
- fecha = row["fecha"].ToString(),
- identificacion = row["identificacion"].ToString(),
- importe = row["importe"].ToString(),
- importe_dec = row["importe_dec"].ToString(),
- provincia = row["provincia"].ToString(),
- referencia = row["referencia"].ToString(),
- };
- });
- // Agrupamos por emisora
- var OutputQuery = Query.GroupBy(l => l.emisora);
- List<int> TotalRegistros = new List<int>();
- List<int> TotalSumas = new List<int>();
- int i = 1;
- int lastRow;
- #region Escritura en fichero
- using (StreamWriter sw = new StreamWriter(codigoCabecera.Remove(6, 2)))
- {
- sw.WriteLine(("775701 " + DateTime.Now.ToString("yy") + DateTime.Now.Month.ToString("d2") + DateTime.Now.AddDays(1).Day.ToString("d2") + DateTime.Now.Hour.ToString("d2") + DateTime.Now.Minute.ToString("d2") + "008910 00" + txtBanco.Text + codigoCabecera + txtBanco.Text + "").PadRight(100));
- sw.WriteLine(("0170 " + valEmisora + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy")).PadRight(100));
- foreach (var grupo in OutputQuery)
- {
- sw.WriteLine(("0270 " + valEmisora + grupo.Key + " " + this.txtBanco.Text + " 10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy")).PadRight(100));
- List<int> Suma = new List<int>();
- foreach (var data in grupo)
- {
- Excel.addData(3 + i, 1, i.ToString(), "A" + (3 + i), "A" + (3 + i), "#0", 1);
- Excel.addData(3 + i, 2, data.referencia, "B" + (3 + i), "C" + (3 + i), "0000000000000", 2);
- Excel.addData(3 + i, 4, Convert.ToInt32(data.importe).ToString() + "." + data.importe_dec, "D" + (3 + i), "E" + (3 + i), "###,###.00##", 2);
- Excel.addData(3 + i, 6, data.sucursal, "F" + (3 + i), "F" + (3 + i), "0000", 1);
- Excel.addData(3 + i, 7, data.emisora, "G" + (3 + i), "H" + (3 + i), "000", 2);
- Excel2.addData(3 + i, 1, data.provincia, "A" + (3 + i), "A" + (3 + i), "#0", 1);
- Excel2.addData(3 + i, 2, data.sucursal, "B" + (3 + i), "B" + (3 + i), "0000", 1);
- Excel2.addData(3 + i, 3, data.referencia, "C" + (3 + i), "D" + (3 + i), "0000000000000", 2);
- Excel2.addData(3 + i, 5, Convert.ToInt32(data.importe).ToString() + "." + data.importe_dec, "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2);
- sw.WriteLine(("6070 " + valEmisora + data.emisora + "1" + data.banco + data.sucursal + data.fecha + data.importe + data.importe_dec + data.identificacion + " " + data.referencia).PadRight(100));
- Suma.Add(Convert.ToInt32(data.importe + data.importe_dec));
- i++;
- }
- sw.WriteLine(("8070 " + valEmisora + grupo.Key + " " + (grupo.Count() + 2).ToString().PadLeft(6, '0') + " " + Suma.Sum().ToString().PadLeft(12, '0')).PadRight(100));
- TotalRegistros.Add((grupo.Count() + 2));
- TotalSumas.Add(Suma.Sum());
- }
- sw.WriteLine(("9070 " + valEmisora + " " + (TotalRegistros.Sum() + 2).ToString().PadLeft(6, '0') + " " + TotalSumas.Sum().ToString().PadLeft(12, '0')).PadRight(100));
- this.txtTotal.Text = TotalSumas.Sum().ToString();
- lastRow = i + 2;
- }
- #endregion
- Excel.createHeaders(3 + i, 3, "TOTAL", "C" + (3 + i), "C" + (3 + i), 1);
- Excel.addData(3 + i, 4, ((decimal)TotalSumas.Sum() / 100).ToString("###,###.##"), "D" + (3 + i), "E" + (3 + i), "", 2);
- foreach (var suc in Query.GroupBy(l => l.sucursal))
- {
- Excel2.createHeaders(3 + i, 1, "TOT. SUCURSAL " + suc.Key.PadLeft(4, '0'), "A" + (3 + i), "B" + (3 + i), 2);
- Excel2.addData(3 + i, 5, "=SUMAR.SI(B4:B" + lastRow + ";" + suc.Key.PadLeft(4, '0') + ";E4:F" + lastRow + ")", "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2, true);
- i++;
- }
- foreach (var prov in Query.GroupBy(l => l.provincia))
- {
- Excel2.createHeaders(3 + i, 1, "TOT. PROVINCIA " + prov.Key, "A" + (3 + i), "B" + (3 + i), 2);
- Excel2.addData(3 + i, 4, "=CONTAR.SI(A4:A" + lastRow + ";" + prov.Key + ")", "D" + (3 + i), "D" + (3 + i), "", 1, true);
- Excel2.addData(3 + i, 5, "=SUMAR.SI(A4:A" + lastRow + ";" + prov.Key + ";E4:F" + lastRow + ")", "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2, true);
- i++;
- }
- Excel2.createHeaders(3 + i, 1, "TOT. GENERAL", "A" + (3 + i), "B" + (3 + i), 2);
- Excel2.addData(3 + i, 4, (lastRow - 3).ToString(), "D" + (3 + i), "D" + (3 + i), "", 1);
- Excel2.addData(3 + i, 5, "=SUMA(E4:F" + (lastRow) + ")", "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2, true);
- foreach (TextBox tb in FindChilds<TextBox>(this))
- {
- tb.IsEnabled = false;
- tb.Text = null;
- }
- Excel.saveFile("Listado General");
- Excel2.saveFile("Listado por provincias");
- }
- /// <summary>
- /// Rutina para comprobar si se han insertado todos los datos
- /// al restar a 0 el total se determina que no hay más que insertar
- /// si da negativo indica revisión por parte del usuario
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void txtTotal_TextChanged(object sender, TextChangedEventArgs e)
- {
- if (!(sender as TextBox).IsFocused & Convert.ToInt32((sender as TextBox).Text) == 0)
- {
- foreach (TextBox tb in FindChilds<TextBox>(this))
- {
- tb.IsEnabled = false;
- tb.Text = null;
- }
- MessageBox.Show("Se han insertado todos los registros, verificar la tabla y proceder a generar el fichero.");
- }
- else if (!(sender as TextBox).IsFocused & Convert.ToInt32((sender as TextBox).Text) < 0)
- MessageBox.Show("Ha ocurrido un problema, la resta del total da negativo. Revisar el listado y comparar los importes.");
- }
- /// <summary>
- /// Mueve al resultado siguiente
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnSiguiente_Click(object sender, RoutedEventArgs e)
- {
- this.btnAnterior.IsEnabled = true;
- this.btnPrimero.IsEnabled = true;
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id > " + CurrentId + " AND sesion='" + currentSession + "' ORDER BY id");
- if (!sel.EOF)
- fillFields(sel);
- else
- {
- isEdit = false;
- CurrentId++;
- foreach (TextBox box in FindChilds<TextBox>(this))
- {
- box.IsEnabled = true;
- if (box.IsEnabled == true & box.Name != "txtTotal")
- box.Text = null;
- }
- }
- }
- /// <summary>
- /// Mueve al resultado anterior
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnAnterior_Click(object sender, RoutedEventArgs e)
- {
- this.btnSiguiente.IsEnabled = true;
- this.btnUltimo.IsEnabled = true;
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id < " + CurrentId + " AND sesion='" + currentSession + "' ORDER BY id DESC");
- if (!sel.EOF)
- fillFields(sel);
- }
- /// <summary>
- /// Click en botón "Primero" que devuelve los resultados de la primera inserción
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnPrimero_Click(object sender, RoutedEventArgs e)
- {
- this.btnPrimero.IsEnabled = false;
- this.btnSiguiente.IsEnabled = true;
- this.btnUltimo.IsEnabled = true;
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
- sel.MoveFirst();
- if (!sel.EOF)
- fillFields(sel);
- }
- /// <summary>
- /// Click en botón "Último" que devuelve los resultados de la última inserción
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnUltimo_Click(object sender, RoutedEventArgs e)
- {
- this.btnUltimo.IsEnabled = false;
- this.btnPrimero.IsEnabled = true;
- this.btnAnterior.IsEnabled = true;
- SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
- sel.MoveLast();
- if (!sel.EOF)
- fillFields(sel);
- }
- /// <summary>
- /// Genera el listado inicial al pulsar sobre consulta.
- /// En el caso de que generar = true, lo que hace es
- /// rellenar los campos antes de generar los ficheros, para obtener los datos.
- /// </summary>
- /// <param name="generar">True o False si se carga la función para generar un fichero o no</param>
- private void LoadListOne(bool generar)
- {
- SelectBD sel;
- if (generar == false)
- {
- sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
- this.btnSiguiente.IsEnabled = true;
- this.btnUltimo.IsEnabled = true;
- }
- else
- {
- sel = new SelectBD(ConexBD, "SELECT * FROM Seguros ORDER BY id");
- sel.MoveLast();
- this.btnSiguiente.IsEnabled = true;
- this.btnUltimo.IsEnabled = false;
- }
- if (!sel.EOF)
- fillFields(sel);
- }
- /// <summary>
- /// Click en el botón Archivo -> Salir
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Exit_Click(object sender, RoutedEventArgs e)
- {
- MessageBoxResult exitPopUp = MessageBox.Show("¿Realmente desea salir?", "Salir", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
- if (exitPopUp.ToString() == "Yes")
- this.Close();
- }
- #region Funciones genéricas
- /// <summary>
- /// Rellena los campos con los resultados de la query
- /// </summary>
- /// <param name="sel">Query</param>
- public void fillFields(SelectBD sel)
- {
- isEdit = true;
- CurrentId = (int)sel.Campo("id");
- this.txtBanco.Text = sel.CampoString("banco");
- this.txtEmisora.Text = sel.CampoString("emisora");
- this.txtFecha.Text = sel.CampoString("fecha");
- this.txtIdentificacion.Text = sel.CampoString("identificacion");
- this.txtImporte.Text = sel.CampoString("importe");
- this.txtImporteDec.Text = sel.CampoString("importe_dec");
- this.txtProvincia.Text = sel.CampoString("provincia");
- this.txtReferencia.Text = sel.CampoString("referencia");
- this.txtSucursal.Text = sel.CampoString("sucursal");
- foreach (TextBox box in FindChilds<TextBox>(this))
- {
- if (box.IsEnabled == false)
- box.IsEnabled = true;
- }
- }
- /// <summary>
- /// Pérdida de foco, rellena con ceros a la izquierda los elementos que no cumplan el MaxLength
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void TextBox_LostFocusFill(object sender, RoutedEventArgs e)
- {
- TextBox tb = sender as TextBox;
- if (tb.Text.Count() < tb.MaxLength)
- tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
- }
- /// <summary>
- /// Presión de tecla
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void TextBox_KeyDown(object sender, KeyEventArgs e)
- {
- TextBox tb = sender as TextBox;
- if ((e.Key == Key.Enter || e.Key == Key.Add) & tb.AcceptsReturn == false)
- {
- if (tb.Name == "txtBanco")
- {
- if (tb.Text == "1485")
- {
- this.txtSucursal.IsEnabled = false;
- this.txtSucursal.Text = "0001";
- this.txtProvincia.IsEnabled = false;
- this.txtProvincia.Text = "28";
- }
- tb.IsEnabled = false;
- MoveToNextUIElement(e);
- }
- else
- {
- MoveToNextUIElement(e);
- }
- }
- if (e.Key == Key.Subtract & tb.AcceptsReturn == false)
- MoveToPrevUIElement(e);
- }
- /// <summary>
- /// Foco en control, selecciona todo el texto cuando se haga foco en él, para editar rápido.
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TextBox_Focus(object sender, RoutedEventArgs e)
- {
- if (!string.IsNullOrEmpty((sender as TextBox).Text))
- (sender as TextBox).SelectAll();
- }
- /// <summary>
- /// Previsión de input, para prohibir carácteres no númericos
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
- {
- CheckEsNumerico(e);
- }
- #region Movimiento entre UIElements
- /// <summary>
- /// Mueve al siguiente elemento con TabStop
- /// usa las teclas ADD y ENTER
- /// </summary>
- /// <param name="e"></param>
- void MoveToNextUIElement(KeyEventArgs e)
- {
- // Creamos un FocusNavigationDirection y lo configuramos a un campo que contiene la dirección seleccionada.
- FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;
- // MoveFocus hace un TraversalRequest como argumento
- TraversalRequest request = new TraversalRequest(focusDirection);
- // Obtenemos el elemento con foco del teclado
- UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
- // Cambiamos el foco
- if (elementWithFocus != null)
- {
- if (elementWithFocus.MoveFocus(request))
- e.Handled = true;
- }
- }
- /// <summary>
- /// Mueve al anterior elemento con TabStop
- /// usa la tecla SUBSTRACT
- /// </summary>
- /// <param name="e"></param>
- void MoveToPrevUIElement(KeyEventArgs e)
- {
- // Creamos un FocusNavigationDirection y lo configuramos a un campo que contiene la dirección seleccionada.
- FocusNavigationDirection focusDirection = FocusNavigationDirection.Previous;
- // MoveFocus hace un TraversalRequest como argumento
- TraversalRequest request = new TraversalRequest(focusDirection);
- // Obtenemos el elemento con foco del teclado
- UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
- // Cambiamos el foco
- if (elementWithFocus != null)
- {
- if (elementWithFocus.MoveFocus(request))
- e.Handled = true;
- }
- }
- #endregion
- /// <summary>
- /// Verifica que los caracteres sean numéricos, si no, no permite escribir
- /// </summary>
- /// <param name="e"></param>
- private void CheckEsNumerico(TextCompositionEventArgs e)
- {
- int result;
- if (!(int.TryParse(e.Text, out result)))
- e.Handled = true;
- }
- /// <summary>
- /// Devuelve todos los elementos de un tipo en el formulario para su manipulación
- /// </summary>
- /// <typeparam name="T">Tipo de elemento</typeparam>
- /// <param name="depObj">Padre de los controles</param>
- /// <returns>Devuelve un listado de los elementos</returns>
- public static IEnumerable<T> FindChilds<T>(DependencyObject depObj) where T : DependencyObject
- {
- if (depObj != null)
- {
- for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
- {
- DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
- if (child != null && child is T)
- yield return (T)child;
- foreach (T childOfChild in FindChilds<T>(child))
- yield return childOfChild;
- }
- }
- }
- #endregion
- }
- public class SelectBD
- {
- DataSet m_Dataset;
- SqlDataAdapter m_DataAdapter;
- DataRow m_dr;
- private int m_indice;
- private int m_PageSize;
- public SelectBD()
- {
- m_Dataset = null;
- m_dr = null;
- m_indice = 0;
- m_PageSize = 0;
- }
- public SelectBD(SqlConnection conex, string SQL)
- : this()
- {
- Open(conex, SQL);
- }
- public SelectBD(SqlConnection conex, string SQL, string tabla)
- : this()
- {
- Open(conex, SQL, tabla);
- }
- ~SelectBD()
- {
- if (m_Dataset != null)
- m_Dataset.Clear();
- m_Dataset = null;
- }
- public int PageSize
- {
- get
- {
- return m_PageSize;
- }
- set
- {
- m_PageSize = value;
- }
- }
- public bool Open(SqlConnection conex, string SQL)
- {
- return this.Open(conex, SQL, "");
- }
- public bool Open(SqlConnection conex, string SQL, string tabla)
- {
- m_Dataset = new DataSet();
- m_DataAdapter = new SqlDataAdapter(SQL, conex);
- SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(m_DataAdapter);
- if (tabla != "") // si llega el nombre de una tabla
- m_DataAdapter.Fill(m_Dataset, tabla);
- else
- m_DataAdapter.Fill(m_Dataset);
- if (m_Dataset == null)
- return false;
- if (m_Dataset.Tables.Count == 0)
- m_indice = 0;
- m_indice = 1;
- return true;
- }
- public object Campo(string indice)
- {
- return m_Dataset.Tables[0].Rows[m_indice - 1][indice];
- }
- public string CampoString(string indice)
- {
- return Campo(indice).Equals(DBNull.Value) ? "" : Campo(indice).ToString();
- }
- public DataRow GetCurrentDataRow()
- {
- return m_Dataset.Tables[0].Rows[m_indice - 1];
- }
- public object Campo(int indice)
- {
- return m_Dataset.Tables[0].Rows[m_indice - 1][indice];
- }
- public string CampoString(int indice)
- {
- return Campo(indice).Equals(DBNull.Value) ? "" : Campo(indice).ToString();
- }
- public void NuevoRegistro(string tabla)
- {
- m_dr = m_Dataset.Tables[tabla].NewRow();
- }
- public void InsertaRegistro(string tabla)
- {
- m_Dataset.Tables[tabla].Rows.Add(m_dr);
- m_DataAdapter.Update(m_Dataset, tabla);
- m_Dataset.AcceptChanges();
- m_dr = null;
- }
- public void SetCampo(string indice, object valor)
- {
- if (m_dr != null)
- m_dr[indice] = valor;
- else
- m_Dataset.Tables[0].Rows[m_indice - 1][indice] = valor;
- }
- public void SetCampo(int indice, object valor)
- {
- if (m_dr != null)
- m_dr[indice] = valor;
- else
- m_Dataset.Tables[0].Rows[m_indice][indice] = valor;
- }
- public void SetCampo(int indice, byte[] valor)
- {
- if (m_dr != null)
- m_dr[indice] = valor;
- else
- m_Dataset.Tables[0].Rows[m_indice][indice] = valor;
- }
- public void AcceptChanges()
- {
- m_DataAdapter.Update(m_Dataset);
- }
- public void AcceptChanges(string tabla)
- {
- m_DataAdapter.Update(m_Dataset, tabla);
- }
- public void MoveFirst()
- {
- m_indice = 1;
- }
- public void MoveLast()
- {
- m_indice = m_Dataset.Tables[0].Rows.Count;
- }
- public void MoveNext()
- {
- if (!EOF)
- m_indice = m_indice + 1;
- }
- public bool EOF
- {
- get
- {
- if (m_Dataset.Tables[0].Rows.Count <= 0)
- return true;
- if (m_indice > m_Dataset.Tables[0].Rows.Count)
- return true;
- return false;
- }
- }
- public int Count
- {
- get
- {
- return m_Dataset.Tables[0].Rows.Count;
- }
- }
- public int PageCount
- {
- get
- {
- if (m_PageSize > 0)
- return (Count / m_PageSize) + (Count % m_PageSize > 0 ? 1 : 0);
- return Count;
- }
- }
- public int AbsolutePage
- {
- get
- {
- if (m_PageSize > 0)
- return (m_indice / m_PageSize) + 1;
- return 1;
- }
- set
- {
- if (value <= 0)
- m_indice = 0;
- else if (value > Count)
- m_indice = (int)Count;
- else
- {
- if (m_PageSize > 0)
- m_indice = (m_PageSize * (value - 1)) + 1;
- else
- m_indice = 1;
- }
- }
- }
- public SqlDataAdapter DataAdapter
- {
- get
- {
- return m_DataAdapter;
- }
- }
- public DataSet DataSet
- {
- get
- {
- return m_Dataset;
- }
- }
- public DataTable DataTable
- {
- get
- {
- return m_Dataset.Tables[0];
- }
- }
- }
- /// <summary>
- /// Crea un documento excel, y lo rellena con los datos que le asignemos
- /// </summary>
- class CreateExcelDoc
- {
- Microsoft.Office.Interop.Excel.Application app;
- Microsoft.Office.Interop.Excel.Workbook workbook;
- Microsoft.Office.Interop.Excel.Worksheet worksheet;
- Microsoft.Office.Interop.Excel.Range workSheet_range;
- /// <summary>
- /// Crea un nuevo documento excel
- /// </summary>
- /// <param name="visible">Determina si el documento será visible o no</param>
- public void createDoc(bool visible)
- {
- try
- {
- app = new Microsoft.Office.Interop.Excel.Application();
- app.Visible = visible;
- workbook = app.Workbooks.Add(1);
- worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
- }
- catch (Exception ex)
- {
- Logger.log(ex);
- }
- }
- /// <summary>
- /// Añade cabeceras a nuestra tabla excel
- /// </summary>
- /// <param name="row">Línea en la que empezará a pintar el valor</param>
- /// <param name="col">Columna e la que empezará a pintar el valor</param>
- /// <param name="data">Texto de la cabecera</param>
- /// <param name="cell1">Celda donde empieza el valor</param>
- /// <param name="cell2">Celda donde termina el valor</param>
- /// <param name="mergeColumns">Combinar y centrar.</param>
- public void createHeaders(int row, int col, string data, string cell1,
- string cell2, int mergeColumns)
- {
- worksheet.Cells[row, col] = data;
- workSheet_range = worksheet.get_Range(cell1, cell2);
- workSheet_range.Merge(mergeColumns);
- workSheet_range.Borders.ColorIndex = 20;
- workSheet_range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlBorderWeight.xlHairline;
- workSheet_range.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
- }
- /// <summary>
- /// Añade datos a nuestra tabla excel
- /// </summary>
- /// <param name="row">Línea en la que empezará a pintar el valor</param>
- /// <param name="col">Columna e la que empezará a pintar el valor</param>
- /// <param name="data">String con el valor, puede ser una formula si formula = true</param>
- /// <param name="cell1">Celda donde empieza el valor</param>
- /// <param name="cell2">Celda donde termina el valor</param>
- /// <param name="format">Formato numérico para el valor</param>
- /// <param name="mergeColumns">Combinar y centrar.</param>
- /// <param name="formula">Por defecto false, si es true data será una formula</param>
- public void addData(int row, int col, string data,
- string cell1, string cell2, string format, int mergeColumns, bool formula = false)
- {
- if (formula == true)
- worksheet.Cells[row, col].FormulaLocal = data;
- else
- worksheet.Cells[row, col] = data;
- workSheet_range = worksheet.get_Range(cell1, cell2);
- workSheet_range.NumberFormat = format;
- workSheet_range.Merge(mergeColumns);
- workSheet_range.Borders.ColorIndex = 0;
- }
- /// <summary>
- /// Guardamos el archivo (con prompt de sobreescribir) y matamos procesos
- /// </summary>
- /// <param name="filename">Archivo de salida</param>
- public void saveFile(string filename)
- {
- try
- {
- workbook.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
- app.Quit();
- Marshal.ReleaseComObject(workSheet_range);
- Marshal.ReleaseComObject(worksheet);
- Marshal.ReleaseComObject(workbook);
- Marshal.ReleaseComObject(app);
- GC.Collect();
- GC.WaitForPendingFinalizers();
- }
- catch (Exception ex)
- {
- Logger.log(ex);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement