Advertisement
robhunter

MainWindow.xaml.cs

Mar 11th, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 37.53 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Data.SqlClient;
  15. using System.Xml;
  16. using System.Data;
  17. using System.IO;
  18. using System.Runtime.InteropServices;
  19. using Microsoft.Office.Interop.Excel;
  20. namespace Seguros_Sociales
  21. {
  22.     /// <summary>
  23.     /// Lógica de interacción para MainWindow.xaml
  24.     /// </summary>
  25.  
  26.     public partial class MainWindow : Window
  27.     {
  28.  
  29.         public static SqlConnection ConexBD; // Conexión a la BBDD
  30.         string lastDate; // Almacena la última fecha, para acceso rápido con F7
  31.         int CurrentId; // Almacena el ID actual de la BBDD
  32.         bool isEdit = false; // Determina si estamos en modo edición (o consulta) o en modo insertar.
  33.         static string currentSession = System.Environment.MachineName.ToString(); // Almacena la sesión actual (nombre del equipo)
  34.  
  35.         public MainWindow()
  36.         {
  37.             InitializeComponent();
  38.         }
  39.  
  40.         private void Window_Loaded(object sender, RoutedEventArgs e)
  41.         {
  42.             try
  43.             {
  44.                 XmlDocument xmlconex = new XmlDocument();
  45.                 xmlconex.Load(Directory.GetCurrentDirectory() + "\\Conexiones.xml");
  46.  
  47.                 ConexBD = new SqlConnection(xmlconex.GetElementsByTagName("ConnectionString").Item(0).InnerText);
  48.                 ConexBD.Open();
  49.             }
  50.             catch (Exception ex)
  51.             {
  52.                 Logger.log(ex);
  53.                 MessageBox.Show("Ha ocurrido un error, no se puede iniciar la aplicación");
  54.                 this.Close();
  55.             }
  56.             lblSesion.Content = "Sesión iniciada como " + currentSession;
  57.         }
  58.         private void Window_Unloaded(object sender, RoutedEventArgs e)
  59.         {
  60.             // Cerramos la conexión al cerrar la ventana.
  61.             ConexBD.Close();
  62.         }
  63.  
  64.         /// <summary>
  65.         /// Click en "Datos Nuevos" que borrará el contenido anterior para comenzar un nuevo lote
  66.         /// </summary>
  67.         /// <param name="sender"></param>
  68.         /// <param name="e"></param>
  69.         private void DatosNuevos_Click(object sender, RoutedEventArgs e)
  70.         {
  71.             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);
  72.             if (newDataPopUp.ToString() == "Yes")
  73.             {
  74.                 try
  75.                 {
  76.                     SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
  77.                     if (!sel.EOF)
  78.                     {
  79.                         sel.MoveLast();
  80.                         CurrentId = (int)sel.Campo("id");
  81.                         SqlCommand cmd = new SqlCommand("DELETE FROM Usuario WHERE sesion='" + currentSession + "'", ConexBD);
  82.                         cmd.ExecuteNonQuery();
  83.                         cmd.Dispose();
  84.                     }
  85.                     foreach (TextBox tb in FindChilds<TextBox>(this))
  86.                     {
  87.                         tb.IsEnabled = true;
  88.                         tb.Text = null;
  89.                     }
  90.                     this.txtTotal.Focus();
  91.                     this.btnSiguiente.IsEnabled = false;
  92.                     this.btnAnterior.IsEnabled = false;
  93.                 }
  94.                 catch (Exception ex)
  95.                 {
  96.                     Logger.log(ex);
  97.                 }
  98.             }
  99.         }
  100.  
  101.         /// <summary>
  102.         /// Al pulsar ENTER | ADD en el último campo (txtFecha) se insertarán los datos
  103.         /// </summary>
  104.         /// <param name="sender"></param>
  105.         /// <param name="e"></param>
  106.         private void txtFecha_KeyDown(object sender, KeyEventArgs e)
  107.         {
  108.             TextBox tb = sender as TextBox;
  109.             if (e.Key == Key.F7)
  110.                 tb.Text = lastDate;
  111.             if (e.Key == Key.Subtract & tb.AcceptsReturn == false)
  112.                 MoveToPrevUIElement(e);
  113.             if (((e.Key == Key.Enter || e.Key == Key.Add) & tb.AcceptsReturn == false))
  114.             {
  115.                 lastDate = tb.Text;
  116.                 try { this.txtTotal.Text = (Convert.ToInt32(this.txtTotal.Text) - Convert.ToInt32(this.txtImporte.Text + this.txtImporteDec.Text)).ToString(); }
  117.                 catch { this.txtTotal.Text = this.txtTotal.Text; }
  118.                 try
  119.                 {
  120.                     SelectBD sel;
  121.                     if (isEdit == true)
  122.                         sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id='" + CurrentId + "'", "Seguros");
  123.                     else
  124.                     {
  125.                         sel = new SelectBD(ConexBD, "SELECT * FROM Seguros", "Seguros");
  126.                         sel.NuevoRegistro("Seguros");
  127.                     }
  128.  
  129.                     sel.SetCampo("banco", this.txtBanco.Text);
  130.                     sel.SetCampo("sucursal", this.txtSucursal.Text);
  131.                     sel.SetCampo("provincia", this.txtProvincia.Text);
  132.                     sel.SetCampo("emisora", this.txtEmisora.Text);
  133.                     sel.SetCampo("referencia", this.txtReferencia.Text);
  134.                     sel.SetCampo("identificacion", this.txtIdentificacion.Text);
  135.                     sel.SetCampo("importe", this.txtImporte.Text);
  136.                     sel.SetCampo("importe_dec", this.txtImporteDec.Text);
  137.                     sel.SetCampo("fecha", this.txtFecha.Text);
  138.                     sel.SetCampo("fcreacion", DateTime.Today.ToString("ddMMyy"));
  139.                     sel.SetCampo("sesion", currentSession);
  140.  
  141.                     if (isEdit == true)
  142.                         sel.AcceptChanges("Seguros");
  143.                     else
  144.                         sel.InsertaRegistro("Seguros");
  145.  
  146.                     sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
  147.  
  148.                     sel.MoveLast();
  149.                     CurrentId = (int)sel.Campo("id") + 1;
  150.                 }
  151.                 catch (Exception ex)
  152.                 {
  153.                     Logger.log(ex);
  154.                 }
  155.  
  156.                 this.btnAnterior.IsEnabled = true;
  157.                 this.btnPrimero.IsEnabled = true;
  158.                 foreach (TextBox box in FindChilds<TextBox>(this))
  159.                 {
  160.                     if (box.IsEnabled == true & box.Name != "txtTotal")
  161.                         box.Text = null;
  162.                 }
  163.  
  164.                 MoveToNextUIElement(e);
  165.             }
  166.         }
  167.  
  168.  
  169.         /// <summary>
  170.         /// Click en Archivo->Consulta Lote
  171.         /// </summary>
  172.         /// <param name="sender"></param>
  173.         /// <param name="e"></param>
  174.         private void ConsultaDatos_Click(object sender, RoutedEventArgs e)
  175.         {
  176.  
  177.             LoadListOne(false);
  178.         }
  179.  
  180.         /// <summary>
  181.         /// Genera los ficheros de salida
  182.         /// </summary>
  183.         /// <param name="sender"></param>
  184.         /// <param name="e"></param>
  185.         private void GenerarFichero_Click(object sender, RoutedEventArgs e)
  186.         {
  187.             LoadListOne(true);
  188.             string NombreBanco = new SelectBD(ConexBD, "SELECT * FROM Bancos WHERE referencia='" + this.txtBanco.Text + "'").Campo("nombre").ToString();
  189.             CreateExcelDoc Excel = new CreateExcelDoc();
  190.             CreateExcelDoc Excel2 = new CreateExcelDoc();
  191.             Excel.createDoc(false);
  192.             Excel2.createDoc(false);
  193.             string valEmisora = "02827003";
  194.             string codigoCabecera;
  195.             if (DateTime.Today.Day > 7)
  196.                 codigoCabecera = "AE570200";
  197.             else
  198.                 codigoCabecera = "AE570100";
  199.             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);
  200.             Excel.createHeaders(2, 8, (" Cobro Por Ventanilla S. S. CONTROL DE DOCUMENTOS").ToUpper(), "A2", "H2", 8);
  201.             Excel.createHeaders(3, 1, "N.ORDEN", "A3", "A3", 1);
  202.             Excel.createHeaders(3, 2, "NUMERO REFERENCIA", "B3", "C3", 2);
  203.             Excel.createHeaders(3, 4, "IMPORTE", "D3", "E3", 2);
  204.             Excel.createHeaders(3, 6, "SUC", "F3", "F3", 1);
  205.             Excel.createHeaders(3, 7, "EMISORA", "G3", "H3", 2);
  206.  
  207.             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);
  208.             Excel2.createHeaders(2, 6, (" Cobro Por Ventanilla S. S. REMESAS PRESENTADAS POR SUCURSALES").ToUpper(), "A2", "F2", 6);
  209.             Excel2.createHeaders(3, 1, "PROV", "A3", "A3", 1);
  210.             Excel2.createHeaders(3, 2, "SUC", "B3", "B3", 1);
  211.             Excel2.createHeaders(3, 3, "REFERENCIA", "C3", "D3", 2);
  212.             Excel2.createHeaders(3, 5, "IMPORTE", "E3", "F3", 2);
  213.  
  214.             SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros");
  215.  
  216.             // Convertimos el DataTable de la query en un IENumerable, para poder tratarla como objeto
  217.             // y poder organizar de mejor forma los resultados...
  218.             var Query = sel.DataTable.AsEnumerable().Select(row =>
  219.             {
  220.                 return new
  221.                 {
  222.                     banco = row["banco"].ToString(),
  223.                     emisora = row["emisora"].ToString(),
  224.                     sucursal = row["sucursal"].ToString(),
  225.                     fecha = row["fecha"].ToString(),
  226.                     identificacion = row["identificacion"].ToString(),
  227.                     importe = row["importe"].ToString(),
  228.                     importe_dec = row["importe_dec"].ToString(),
  229.                     provincia = row["provincia"].ToString(),
  230.                     referencia = row["referencia"].ToString(),
  231.                 };
  232.             });
  233.  
  234.             // Agrupamos por emisora
  235.             var OutputQuery = Query.GroupBy(l => l.emisora);
  236.             List<int> TotalRegistros = new List<int>();
  237.             List<int> TotalSumas = new List<int>();
  238.             int i = 1;
  239.             int lastRow;
  240.             #region Escritura en fichero
  241.             using (StreamWriter sw = new StreamWriter(codigoCabecera.Remove(6, 2)))
  242.             {
  243.                 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));
  244.                 sw.WriteLine(("0170      " + valEmisora + "    " + this.txtBanco.Text + "          10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy")).PadRight(100));
  245.                 foreach (var grupo in OutputQuery)
  246.                 {
  247.                     sw.WriteLine(("0270      " + valEmisora + grupo.Key + " " + this.txtBanco.Text + "          10" + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy")).PadRight(100));
  248.                     List<int> Suma = new List<int>();
  249.                     foreach (var data in grupo)
  250.                     {
  251.                         Excel.addData(3 + i, 1, i.ToString(), "A" + (3 + i), "A" + (3 + i), "#0", 1);
  252.                         Excel.addData(3 + i, 2, data.referencia, "B" + (3 + i), "C" + (3 + i), "0000000000000", 2);
  253.                         Excel.addData(3 + i, 4, Convert.ToInt32(data.importe).ToString() + "." + data.importe_dec, "D" + (3 + i), "E" + (3 + i), "###,###.00##", 2);
  254.                         Excel.addData(3 + i, 6, data.sucursal, "F" + (3 + i), "F" + (3 + i), "0000", 1);
  255.                         Excel.addData(3 + i, 7, data.emisora, "G" + (3 + i), "H" + (3 + i), "000", 2);
  256.                         Excel2.addData(3 + i, 1, data.provincia, "A" + (3 + i), "A" + (3 + i), "#0", 1);
  257.                         Excel2.addData(3 + i, 2, data.sucursal, "B" + (3 + i), "B" + (3 + i), "0000", 1);
  258.                         Excel2.addData(3 + i, 3, data.referencia, "C" + (3 + i), "D" + (3 + i), "0000000000000", 2);
  259.                         Excel2.addData(3 + i, 5, Convert.ToInt32(data.importe).ToString() + "." + data.importe_dec, "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2);
  260.                         sw.WriteLine(("6070      " + valEmisora + data.emisora + "1" + data.banco + data.sucursal + data.fecha + data.importe + data.importe_dec + data.identificacion + "                      " + data.referencia).PadRight(100));
  261.                         Suma.Add(Convert.ToInt32(data.importe + data.importe_dec));
  262.                         i++;
  263.                     }
  264.                     sw.WriteLine(("8070      " + valEmisora + grupo.Key + " " + (grupo.Count() + 2).ToString().PadLeft(6, '0') + "        " + Suma.Sum().ToString().PadLeft(12, '0')).PadRight(100));
  265.                     TotalRegistros.Add((grupo.Count() + 2));
  266.                     TotalSumas.Add(Suma.Sum());
  267.                 }
  268.                 sw.WriteLine(("9070      " + valEmisora + "    " + (TotalRegistros.Sum() + 2).ToString().PadLeft(6, '0') + "        " + TotalSumas.Sum().ToString().PadLeft(12, '0')).PadRight(100));
  269.                 this.txtTotal.Text = TotalSumas.Sum().ToString();
  270.                 lastRow = i + 2;
  271.             }
  272.             #endregion
  273.  
  274.             Excel.createHeaders(3 + i, 3, "TOTAL", "C" + (3 + i), "C" + (3 + i), 1);
  275.             Excel.addData(3 + i, 4, ((decimal)TotalSumas.Sum() / 100).ToString("###,###.##"), "D" + (3 + i), "E" + (3 + i), "", 2);
  276.  
  277.             foreach (var suc in Query.GroupBy(l => l.sucursal))
  278.             {
  279.                 Excel2.createHeaders(3 + i, 1, "TOT. SUCURSAL " + suc.Key.PadLeft(4, '0'), "A" + (3 + i), "B" + (3 + i), 2);
  280.                 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);
  281.                 i++;
  282.             }
  283.  
  284.             foreach (var prov in Query.GroupBy(l => l.provincia))
  285.             {
  286.                 Excel2.createHeaders(3 + i, 1, "TOT. PROVINCIA " + prov.Key, "A" + (3 + i), "B" + (3 + i), 2);
  287.                 Excel2.addData(3 + i, 4, "=CONTAR.SI(A4:A" + lastRow + ";" + prov.Key + ")", "D" + (3 + i), "D" + (3 + i), "", 1, true);
  288.                 Excel2.addData(3 + i, 5, "=SUMAR.SI(A4:A" + lastRow + ";" + prov.Key + ";E4:F" + lastRow + ")", "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2, true);
  289.                 i++;
  290.             }
  291.  
  292.             Excel2.createHeaders(3 + i, 1, "TOT. GENERAL", "A" + (3 + i), "B" + (3 + i), 2);
  293.             Excel2.addData(3 + i, 4, (lastRow - 3).ToString(), "D" + (3 + i), "D" + (3 + i), "", 1);
  294.             Excel2.addData(3 + i, 5, "=SUMA(E4:F" + (lastRow) + ")", "E" + (3 + i), "F" + (3 + i), "###,###.00##", 2, true);
  295.  
  296.             foreach (TextBox tb in FindChilds<TextBox>(this))
  297.             {
  298.                 tb.IsEnabled = false;
  299.                 tb.Text = null;
  300.             }
  301.             Excel.saveFile("Listado General");
  302.             Excel2.saveFile("Listado por provincias");
  303.         }
  304.  
  305.         /// <summary>
  306.         /// Rutina para comprobar si se han insertado todos los datos
  307.         /// al restar a 0 el total se determina que no hay más que insertar
  308.         /// si da negativo indica revisión por parte del usuario
  309.         /// </summary>
  310.         /// <param name="sender"></param>
  311.         /// <param name="e"></param>
  312.         private void txtTotal_TextChanged(object sender, TextChangedEventArgs e)
  313.         {
  314.             if (!(sender as TextBox).IsFocused & Convert.ToInt32((sender as TextBox).Text) == 0)
  315.             {
  316.                 foreach (TextBox tb in FindChilds<TextBox>(this))
  317.                 {
  318.                     tb.IsEnabled = false;
  319.                     tb.Text = null;
  320.                 }
  321.                 MessageBox.Show("Se han insertado todos los registros, verificar la tabla y proceder a generar el fichero.");
  322.             }
  323.             else if (!(sender as TextBox).IsFocused & Convert.ToInt32((sender as TextBox).Text) < 0)
  324.                 MessageBox.Show("Ha ocurrido un problema, la resta del total da negativo. Revisar el listado y comparar los importes.");
  325.         }
  326.  
  327.         /// <summary>
  328.         /// Mueve al resultado siguiente
  329.         /// </summary>
  330.         /// <param name="sender"></param>
  331.         /// <param name="e"></param>
  332.         protected void btnSiguiente_Click(object sender, RoutedEventArgs e)
  333.         {
  334.             this.btnAnterior.IsEnabled = true;
  335.             this.btnPrimero.IsEnabled = true;
  336.             SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id > " + CurrentId + " AND sesion='" + currentSession + "' ORDER BY id");
  337.  
  338.             if (!sel.EOF)
  339.                 fillFields(sel);
  340.             else
  341.             {
  342.                 isEdit = false;
  343.                 CurrentId++;
  344.                 foreach (TextBox box in FindChilds<TextBox>(this))
  345.                 {
  346.                     box.IsEnabled = true;
  347.                     if (box.IsEnabled == true & box.Name != "txtTotal")
  348.                         box.Text = null;
  349.                 }
  350.             }
  351.         }
  352.  
  353.         /// <summary>
  354.         /// Mueve al resultado anterior
  355.         /// </summary>
  356.         /// <param name="sender"></param>
  357.         /// <param name="e"></param>
  358.         private void btnAnterior_Click(object sender, RoutedEventArgs e)
  359.         {
  360.             this.btnSiguiente.IsEnabled = true;
  361.             this.btnUltimo.IsEnabled = true;
  362.             SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE id < " + CurrentId + " AND sesion='" + currentSession + "' ORDER BY id DESC");
  363.  
  364.             if (!sel.EOF)
  365.                 fillFields(sel);
  366.         }
  367.  
  368.         /// <summary>
  369.         /// Click en botón "Primero" que devuelve los resultados de la primera inserción
  370.         /// </summary>
  371.         /// <param name="sender"></param>
  372.         /// <param name="e"></param>
  373.         private void btnPrimero_Click(object sender, RoutedEventArgs e)
  374.         {
  375.             this.btnPrimero.IsEnabled = false;
  376.             this.btnSiguiente.IsEnabled = true;
  377.             this.btnUltimo.IsEnabled = true;
  378.             SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
  379.             sel.MoveFirst();
  380.             if (!sel.EOF)
  381.                 fillFields(sel);
  382.         }
  383.  
  384.         /// <summary>
  385.         /// Click en botón "Último" que devuelve los resultados de la última inserción
  386.         /// </summary>
  387.         /// <param name="sender"></param>
  388.         /// <param name="e"></param>
  389.         private void btnUltimo_Click(object sender, RoutedEventArgs e)
  390.         {
  391.             this.btnUltimo.IsEnabled = false;
  392.             this.btnPrimero.IsEnabled = true;
  393.             this.btnAnterior.IsEnabled = true;
  394.             SelectBD sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
  395.             sel.MoveLast();
  396.             if (!sel.EOF)
  397.                 fillFields(sel);
  398.         }
  399.  
  400.         /// <summary>
  401.         /// Genera el listado inicial al pulsar sobre consulta.
  402.         /// En el caso de que generar = true, lo que hace es
  403.         /// rellenar los campos antes de generar los ficheros, para obtener los datos.
  404.         /// </summary>
  405.         /// <param name="generar">True o False si se carga la función para generar un fichero o no</param>
  406.         private void LoadListOne(bool generar)
  407.         {
  408.             SelectBD sel;
  409.             if (generar == false)
  410.             {
  411.                 sel = new SelectBD(ConexBD, "SELECT * FROM Seguros WHERE sesion='" + currentSession + "' ORDER BY id");
  412.                 this.btnSiguiente.IsEnabled = true;
  413.                 this.btnUltimo.IsEnabled = true;
  414.             }
  415.             else
  416.             {
  417.                 sel = new SelectBD(ConexBD, "SELECT * FROM Seguros ORDER BY id");
  418.                 sel.MoveLast();
  419.                 this.btnSiguiente.IsEnabled = true;
  420.                 this.btnUltimo.IsEnabled = false;
  421.             }
  422.  
  423.             if (!sel.EOF)
  424.                 fillFields(sel);
  425.         }
  426.  
  427.         /// <summary>
  428.         /// Click en el botón Archivo -> Salir
  429.         /// </summary>
  430.         /// <param name="sender"></param>
  431.         /// <param name="e"></param>
  432.         private void Exit_Click(object sender, RoutedEventArgs e)
  433.         {
  434.             MessageBoxResult exitPopUp = MessageBox.Show("¿Realmente desea salir?", "Salir", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
  435.             if (exitPopUp.ToString() == "Yes")
  436.                 this.Close();
  437.         }
  438.  
  439.  
  440.         #region Funciones genéricas
  441.         /// <summary>
  442.         /// Rellena los campos con los resultados de la query
  443.         /// </summary>
  444.         /// <param name="sel">Query</param>
  445.         public void fillFields(SelectBD sel)
  446.         {
  447.             isEdit = true;
  448.             CurrentId = (int)sel.Campo("id");
  449.             this.txtBanco.Text = sel.CampoString("banco");
  450.             this.txtEmisora.Text = sel.CampoString("emisora");
  451.             this.txtFecha.Text = sel.CampoString("fecha");
  452.             this.txtIdentificacion.Text = sel.CampoString("identificacion");
  453.             this.txtImporte.Text = sel.CampoString("importe");
  454.             this.txtImporteDec.Text = sel.CampoString("importe_dec");
  455.             this.txtProvincia.Text = sel.CampoString("provincia");
  456.             this.txtReferencia.Text = sel.CampoString("referencia");
  457.             this.txtSucursal.Text = sel.CampoString("sucursal");
  458.             foreach (TextBox box in FindChilds<TextBox>(this))
  459.             {
  460.                 if (box.IsEnabled == false)
  461.                     box.IsEnabled = true;
  462.             }
  463.         }
  464.  
  465.         /// <summary>
  466.         /// Pérdida de foco, rellena con ceros a la izquierda los elementos que no cumplan el MaxLength
  467.         /// </summary>
  468.         /// <param name="sender"></param>
  469.         /// <param name="e"></param>
  470.         void TextBox_LostFocusFill(object sender, RoutedEventArgs e)
  471.         {
  472.             TextBox tb = sender as TextBox;
  473.             if (tb.Text.Count() < tb.MaxLength)
  474.                 tb.Text = tb.Text.PadLeft(tb.MaxLength, '0');
  475.         }
  476.  
  477.         /// <summary>
  478.         /// Presión de tecla
  479.         /// </summary>
  480.         /// <param name="sender"></param>
  481.         /// <param name="e"></param>
  482.         void TextBox_KeyDown(object sender, KeyEventArgs e)
  483.         {
  484.             TextBox tb = sender as TextBox;
  485.             if ((e.Key == Key.Enter || e.Key == Key.Add) & tb.AcceptsReturn == false)
  486.             {
  487.                 if (tb.Name == "txtBanco")
  488.                 {
  489.                     if (tb.Text == "1485")
  490.                     {
  491.                         this.txtSucursal.IsEnabled = false;
  492.                         this.txtSucursal.Text = "0001";
  493.                         this.txtProvincia.IsEnabled = false;
  494.                         this.txtProvincia.Text = "28";
  495.                     }
  496.                     tb.IsEnabled = false;
  497.                     MoveToNextUIElement(e);
  498.                 }
  499.                 else
  500.                 {
  501.                     MoveToNextUIElement(e);
  502.                 }
  503.             }
  504.             if (e.Key == Key.Subtract & tb.AcceptsReturn == false)
  505.                 MoveToPrevUIElement(e);
  506.         }
  507.  
  508.         /// <summary>
  509.         /// Foco en control, selecciona todo el texto cuando se haga foco en él, para editar rápido.
  510.         /// </summary>
  511.         /// <param name="sender"></param>
  512.         /// <param name="e"></param>
  513.         private void TextBox_Focus(object sender, RoutedEventArgs e)
  514.         {
  515.             if (!string.IsNullOrEmpty((sender as TextBox).Text))
  516.                 (sender as TextBox).SelectAll();
  517.         }
  518.  
  519.         /// <summary>
  520.         /// Previsión de input, para prohibir carácteres no númericos
  521.         /// </summary>
  522.         /// <param name="sender"></param>
  523.         /// <param name="e"></param>
  524.         private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
  525.         {
  526.             CheckEsNumerico(e);
  527.         }
  528.  
  529.         #region Movimiento entre UIElements
  530.  
  531.         /// <summary>
  532.         /// Mueve al siguiente elemento con TabStop
  533.         /// usa las teclas ADD y ENTER
  534.         /// </summary>
  535.         /// <param name="e"></param>
  536.         void MoveToNextUIElement(KeyEventArgs e)
  537.         {
  538.             // Creamos un FocusNavigationDirection y lo configuramos a un campo que contiene la dirección seleccionada.
  539.             FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;
  540.  
  541.             // MoveFocus hace un TraversalRequest como argumento
  542.             TraversalRequest request = new TraversalRequest(focusDirection);
  543.  
  544.             // Obtenemos el elemento con foco del teclado
  545.             UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
  546.  
  547.             // Cambiamos el foco
  548.             if (elementWithFocus != null)
  549.             {
  550.                 if (elementWithFocus.MoveFocus(request))
  551.                     e.Handled = true;
  552.             }
  553.         }
  554.  
  555.         /// <summary>
  556.         /// Mueve al anterior elemento con TabStop
  557.         /// usa la tecla SUBSTRACT
  558.         /// </summary>
  559.         /// <param name="e"></param>
  560.         void MoveToPrevUIElement(KeyEventArgs e)
  561.         {
  562.             // Creamos un FocusNavigationDirection y lo configuramos a un campo que contiene la dirección seleccionada.
  563.             FocusNavigationDirection focusDirection = FocusNavigationDirection.Previous;
  564.  
  565.             // MoveFocus hace un TraversalRequest como argumento
  566.             TraversalRequest request = new TraversalRequest(focusDirection);
  567.  
  568.             // Obtenemos el elemento con foco del teclado
  569.             UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
  570.  
  571.             // Cambiamos el foco
  572.             if (elementWithFocus != null)
  573.             {
  574.                 if (elementWithFocus.MoveFocus(request))
  575.                     e.Handled = true;
  576.             }
  577.         }
  578.         #endregion
  579.  
  580.         /// <summary>
  581.         /// Verifica que los caracteres sean numéricos, si no, no permite escribir
  582.         /// </summary>
  583.         /// <param name="e"></param>
  584.         private void CheckEsNumerico(TextCompositionEventArgs e)
  585.         {
  586.             int result;
  587.             if (!(int.TryParse(e.Text, out result)))
  588.                 e.Handled = true;
  589.         }
  590.  
  591.         /// <summary>
  592.         /// Devuelve todos los elementos de un tipo en el formulario para su manipulación
  593.         /// </summary>
  594.         /// <typeparam name="T">Tipo de elemento</typeparam>
  595.         /// <param name="depObj">Padre de los controles</param>
  596.         /// <returns>Devuelve un listado de los elementos</returns>
  597.         public static IEnumerable<T> FindChilds<T>(DependencyObject depObj) where T : DependencyObject
  598.         {
  599.             if (depObj != null)
  600.             {
  601.                 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
  602.                 {
  603.                     DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
  604.                     if (child != null && child is T)
  605.                         yield return (T)child;
  606.  
  607.                     foreach (T childOfChild in FindChilds<T>(child))
  608.                         yield return childOfChild;
  609.                 }
  610.             }
  611.         }
  612.         #endregion
  613.     }
  614.  
  615.     public class SelectBD
  616.     {
  617.         DataSet m_Dataset;
  618.         SqlDataAdapter m_DataAdapter;
  619.         DataRow m_dr;
  620.         private int m_indice;
  621.         private int m_PageSize;
  622.  
  623.         public SelectBD()
  624.         {
  625.             m_Dataset = null;
  626.             m_dr = null;
  627.             m_indice = 0;
  628.             m_PageSize = 0;
  629.         }
  630.  
  631.         public SelectBD(SqlConnection conex, string SQL)
  632.             : this()
  633.         {
  634.             Open(conex, SQL);
  635.         }
  636.  
  637.         public SelectBD(SqlConnection conex, string SQL, string tabla)
  638.             : this()
  639.         {
  640.             Open(conex, SQL, tabla);
  641.         }
  642.  
  643.         ~SelectBD()
  644.         {
  645.             if (m_Dataset != null)
  646.                 m_Dataset.Clear();
  647.             m_Dataset = null;
  648.         }
  649.  
  650.         public int PageSize
  651.         {
  652.             get
  653.             {
  654.                 return m_PageSize;
  655.             }
  656.             set
  657.             {
  658.                 m_PageSize = value;
  659.             }
  660.         }
  661.  
  662.         public bool Open(SqlConnection conex, string SQL)
  663.         {
  664.             return this.Open(conex, SQL, "");
  665.         }
  666.  
  667.         public bool Open(SqlConnection conex, string SQL, string tabla)
  668.         {
  669.             m_Dataset = new DataSet();
  670.             m_DataAdapter = new SqlDataAdapter(SQL, conex);
  671.             SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(m_DataAdapter);
  672.             if (tabla != "") // si llega el nombre de una tabla
  673.                 m_DataAdapter.Fill(m_Dataset, tabla);
  674.             else
  675.                 m_DataAdapter.Fill(m_Dataset);
  676.  
  677.             if (m_Dataset == null)
  678.                 return false;
  679.  
  680.             if (m_Dataset.Tables.Count == 0)
  681.                 m_indice = 0;
  682.             m_indice = 1;
  683.             return true;
  684.         }
  685.  
  686.         public object Campo(string indice)
  687.         {
  688.             return m_Dataset.Tables[0].Rows[m_indice - 1][indice];
  689.         }
  690.  
  691.         public string CampoString(string indice)
  692.         {
  693.             return Campo(indice).Equals(DBNull.Value) ? "" : Campo(indice).ToString();
  694.         }
  695.  
  696.         public DataRow GetCurrentDataRow()
  697.         {
  698.             return m_Dataset.Tables[0].Rows[m_indice - 1];
  699.         }
  700.  
  701.         public object Campo(int indice)
  702.         {
  703.             return m_Dataset.Tables[0].Rows[m_indice - 1][indice];
  704.         }
  705.  
  706.         public string CampoString(int indice)
  707.         {
  708.             return Campo(indice).Equals(DBNull.Value) ? "" : Campo(indice).ToString();
  709.         }
  710.  
  711.         public void NuevoRegistro(string tabla)
  712.         {
  713.             m_dr = m_Dataset.Tables[tabla].NewRow();
  714.         }
  715.  
  716.         public void InsertaRegistro(string tabla)
  717.         {
  718.             m_Dataset.Tables[tabla].Rows.Add(m_dr);
  719.             m_DataAdapter.Update(m_Dataset, tabla);
  720.             m_Dataset.AcceptChanges();
  721.             m_dr = null;
  722.         }
  723.  
  724.         public void SetCampo(string indice, object valor)
  725.         {
  726.             if (m_dr != null)
  727.                 m_dr[indice] = valor;
  728.             else
  729.                 m_Dataset.Tables[0].Rows[m_indice - 1][indice] = valor;
  730.         }
  731.  
  732.         public void SetCampo(int indice, object valor)
  733.         {
  734.             if (m_dr != null)
  735.                 m_dr[indice] = valor;
  736.             else
  737.                 m_Dataset.Tables[0].Rows[m_indice][indice] = valor;
  738.         }
  739.  
  740.         public void SetCampo(int indice, byte[] valor)
  741.         {
  742.             if (m_dr != null)
  743.                 m_dr[indice] = valor;
  744.             else
  745.                 m_Dataset.Tables[0].Rows[m_indice][indice] = valor;
  746.         }
  747.  
  748.         public void AcceptChanges()
  749.         {
  750.             m_DataAdapter.Update(m_Dataset);
  751.         }
  752.  
  753.         public void AcceptChanges(string tabla)
  754.         {
  755.             m_DataAdapter.Update(m_Dataset, tabla);
  756.         }
  757.  
  758.         public void MoveFirst()
  759.         {
  760.             m_indice = 1;
  761.         }
  762.  
  763.         public void MoveLast()
  764.         {
  765.             m_indice = m_Dataset.Tables[0].Rows.Count;
  766.         }
  767.  
  768.         public void MoveNext()
  769.         {
  770.             if (!EOF)
  771.                 m_indice = m_indice + 1;
  772.         }
  773.  
  774.         public bool EOF
  775.         {
  776.             get
  777.             {
  778.                 if (m_Dataset.Tables[0].Rows.Count <= 0)
  779.                     return true;
  780.                 if (m_indice > m_Dataset.Tables[0].Rows.Count)
  781.                     return true;
  782.                 return false;
  783.             }
  784.         }
  785.  
  786.         public int Count
  787.         {
  788.             get
  789.             {
  790.                 return m_Dataset.Tables[0].Rows.Count;
  791.             }
  792.         }
  793.  
  794.         public int PageCount
  795.         {
  796.             get
  797.             {
  798.                 if (m_PageSize > 0)
  799.                     return (Count / m_PageSize) + (Count % m_PageSize > 0 ? 1 : 0);
  800.                 return Count;
  801.             }
  802.         }
  803.  
  804.         public int AbsolutePage
  805.         {
  806.             get
  807.             {
  808.                 if (m_PageSize > 0)
  809.                     return (m_indice / m_PageSize) + 1;
  810.                 return 1;
  811.             }
  812.             set
  813.             {
  814.                 if (value <= 0)
  815.                     m_indice = 0;
  816.                 else if (value > Count)
  817.                     m_indice = (int)Count;
  818.                 else
  819.                 {
  820.                     if (m_PageSize > 0)
  821.                         m_indice = (m_PageSize * (value - 1)) + 1;
  822.                     else
  823.                         m_indice = 1;
  824.                 }
  825.             }
  826.         }
  827.  
  828.         public SqlDataAdapter DataAdapter
  829.         {
  830.             get
  831.             {
  832.                 return m_DataAdapter;
  833.             }
  834.         }
  835.  
  836.         public DataSet DataSet
  837.         {
  838.             get
  839.             {
  840.                 return m_Dataset;
  841.             }
  842.         }
  843.  
  844.         public DataTable DataTable
  845.         {
  846.             get
  847.             {
  848.                 return m_Dataset.Tables[0];
  849.             }
  850.         }
  851.  
  852.     }
  853.  
  854.     /// <summary>
  855.     /// Crea un documento excel, y lo rellena con los datos que le asignemos
  856.     /// </summary>
  857.     class CreateExcelDoc
  858.     {
  859.         Microsoft.Office.Interop.Excel.Application app;
  860.         Microsoft.Office.Interop.Excel.Workbook workbook;
  861.         Microsoft.Office.Interop.Excel.Worksheet worksheet;
  862.         Microsoft.Office.Interop.Excel.Range workSheet_range;
  863.         /// <summary>
  864.         /// Crea un nuevo documento excel
  865.         /// </summary>
  866.         /// <param name="visible">Determina si el documento será visible o no</param>
  867.         public void createDoc(bool visible)
  868.         {
  869.             try
  870.             {
  871.                 app = new Microsoft.Office.Interop.Excel.Application();
  872.                 app.Visible = visible;
  873.                 workbook = app.Workbooks.Add(1);
  874.                 worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
  875.             }
  876.             catch (Exception ex)
  877.             {
  878.                 Logger.log(ex);
  879.             }
  880.         }
  881.  
  882.         /// <summary>
  883.         /// Añade cabeceras a nuestra tabla excel
  884.         /// </summary>
  885.         /// <param name="row">Línea en la que empezará a pintar el valor</param>
  886.         /// <param name="col">Columna e la que empezará a pintar el valor</param>
  887.         /// <param name="data">Texto de la cabecera</param>
  888.         /// <param name="cell1">Celda donde empieza el valor</param>
  889.         /// <param name="cell2">Celda donde termina el valor</param>
  890.         /// <param name="mergeColumns">Combinar y centrar.</param>
  891.         public void createHeaders(int row, int col, string data, string cell1,
  892.             string cell2, int mergeColumns)
  893.         {
  894.             worksheet.Cells[row, col] = data;
  895.             workSheet_range = worksheet.get_Range(cell1, cell2);
  896.             workSheet_range.Merge(mergeColumns);
  897.             workSheet_range.Borders.ColorIndex = 20;
  898.             workSheet_range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlBorderWeight.xlHairline;
  899.             workSheet_range.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
  900.         }
  901.  
  902.         /// <summary>
  903.         /// Añade datos a nuestra tabla excel
  904.         /// </summary>
  905.         /// <param name="row">Línea en la que empezará a pintar el valor</param>
  906.         /// <param name="col">Columna e la que empezará a pintar el valor</param>
  907.         /// <param name="data">String con el valor, puede ser una formula si formula = true</param>
  908.         /// <param name="cell1">Celda donde empieza el valor</param>
  909.         /// <param name="cell2">Celda donde termina el valor</param>
  910.         /// <param name="format">Formato numérico para el valor</param>
  911.         /// <param name="mergeColumns">Combinar y centrar.</param>
  912.         /// <param name="formula">Por defecto false, si es true data será una formula</param>
  913.         public void addData(int row, int col, string data,
  914.             string cell1, string cell2, string format, int mergeColumns, bool formula = false)
  915.         {
  916.             if (formula == true)
  917.                 worksheet.Cells[row, col].FormulaLocal = data;
  918.             else
  919.                 worksheet.Cells[row, col] = data;
  920.             workSheet_range = worksheet.get_Range(cell1, cell2);
  921.             workSheet_range.NumberFormat = format;
  922.             workSheet_range.Merge(mergeColumns);
  923.             workSheet_range.Borders.ColorIndex = 0;
  924.  
  925.         }
  926.  
  927.         /// <summary>
  928.         /// Guardamos el archivo (con prompt de sobreescribir) y matamos procesos
  929.         /// </summary>
  930.         /// <param name="filename">Archivo de salida</param>
  931.         public void saveFile(string filename)
  932.         {
  933.             try
  934.             {
  935.                 workbook.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
  936.                 app.Quit();
  937.                 Marshal.ReleaseComObject(workSheet_range);
  938.                 Marshal.ReleaseComObject(worksheet);
  939.                 Marshal.ReleaseComObject(workbook);
  940.                 Marshal.ReleaseComObject(app);
  941.                 GC.Collect();
  942.                 GC.WaitForPendingFinalizers();
  943.             }
  944.             catch (Exception ex)
  945.             {
  946.  
  947.                 Logger.log(ex);
  948.             }
  949.         }
  950.     }
  951. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement