private void Form1_Load(object sender, EventArgs e)
        {
            String connString = "Database=" + Properties.Settings.Default.sunDatabase + ";Data Source=" + Properties.Settings.Default.sunDatasource + ";Integrated Security=False;User ID='" + Properties.Settings.Default.user + "';Password='******';connect timeout = 10";
            String queryCheck = "USE [" + Properties.Settings.Default.sunDatabase + "] SELECT name FROM sys.tables";
            try
            {
                using (SqlConnection connection = new SqlConnection(connString))
                {
                    connection.Open();

                    SqlCommand cmdCheck = new SqlCommand(queryCheck, connection);
                    SqlDataReader reader = cmdCheck.ExecuteReader();
                    if (reader.HasRows)
                    {
                       // System.Windows.Forms.MessageBox.Show("Conexión Establecida satisfactoriamente", "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        config form = new config();
                        form.ShowDialog();
                      //  System.Windows.Forms.MessageBox.Show("Sin conexión", "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception)
            {
                config form = new config();
                form.ShowDialog();
                //System.Windows.Forms.MessageBox.Show("Sin conexión", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            /*
            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader("settings.txt"))
                {
                    String line = sr.ReadToEnd();
                    Properties.Settings.Default.sunDatasource = line;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }*/
            this.connStringSun = "Database=" + Properties.Settings.Default.databaseFiscal + ";Data Source=" + Properties.Settings.Default.sunDatasource + ";Integrated Security=False;MultipleActiveResultSets=true;User ID='" + Properties.Settings.Default.user + "';Password='******';connect timeout = 60";

               checarSiElSourceLeFaltoDeLigarElDiario();
            checarSiLacuentaEsDeIngresoODeEgreso();
              //  listaDeCandidatos.MouseDoubleClick += listaDeCandidatos_MouseDoubleClick;

            if(tipoDeContabilidadGlobal==1)
            {
                detectLabel.Text = "Gastos";
            }
            else
            {
                if(tipoDeContabilidadGlobal==2)
                {
                    detectLabel.Text = "Ingresos";
                }
                else
                {
                    detectLabel.Text = "Balanza";
                }
            }

            noPermitas = false;
            if(Properties.Settings.Default.predefinidoTodaLaCantidad.Equals("1"))
            {
                todaLaCantidadCheckBox.Checked = true;
            }
            else
            {
                todaLaCantidadCheckBox.Checked = false;
            }
            String decimalesC = cantidadGlobal.Substring(cantidadGlobal.Length - 3, 3);
            cantidadGlobal = cantidadGlobal.Substring(0, cantidadGlobal.Length - 3)+"."+decimalesC;

            labelDiario4.Text = "Cantidad que falta a ligar: $ " + cantidadGlobal;
            cantidadQueFalta = Math.Round(Convert.ToDouble(cantidadGlobal), 2);
            if (cantidadQueFalta==0.0)
            {
                System.Windows.Forms.MessageBox.Show("ERROR: la cantidad no puede ser 0, trata de grabar esa linea y luego volver a dar click al boton de Ligar Facturas", "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                if (System.Windows.Forms.Application.MessageLoop)
                {
                    // WinForms app
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    // Console app
                    System.Environment.Exit(1);
                }
            }

            labelDiario4.Text = "Cantidad que falta a ligar: $ " + cantidadQueFalta;

            lineaLabel.Text = Convert.ToInt32(lineaGlobal).ToString();
            sourceLabel.Text = sourceGlobal;
            cuentaLabel.Text = cuentaGlobal;
            debitCreditLabel.Text = debitCreditGlobal;
            cantidadLabel.Text = Math.Round(Convert.ToDouble(cantidadGlobal), 2).ToString();
            unidadDeNegocioLabel.Text = unidadDeNegociosGlobal;

            listaDeCandidatos.MultiSelect = false;
            /*listaDeCandidatos.AllowDrop = true;
            listaDeCandidatos.MouseDown+=listaDeCandidatos_MouseDown;
            labelDiario4.AllowDrop = true;
            labelDiario4.DragEnter+=labelDiario4_DragEnter;
            labelDiario4.DragDrop+=labelDiario4_DragDrop;*/
            listaUUIDEnlazados = new List<Dictionary<string, object>>();

            contextMenu2 = new System.Windows.Forms.ContextMenu();
            menuItem1 = new System.Windows.Forms.MenuItem();
            menuItem2 = new System.Windows.Forms.MenuItem();
            menuItem3 = new System.Windows.Forms.MenuItem();

            contextMenu2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { menuItem1, menuItem2, menuItem3 });
            menuItem1.Index = 0;
            menuItem1.Text = "Ver PDF";
            menuItem2.Index = 1;
            menuItem2.Text = "Ver XML";
            menuItem1.Click += funcionVerPDF;// new SystemHandler(this.funcionVerPDF);
            menuItem2.Click += funcionVerXML;
            menuItem3.Index = 2;
            menuItem3.Text = "Asociar factura";
            menuItem3.Click += asociarFactura;

            listaDeCandidatos.ContextMenu = contextMenu2;

            contextMenu3 = new System.Windows.Forms.ContextMenu();
            menuItem31 = new System.Windows.Forms.MenuItem();
            menuItem32 = new System.Windows.Forms.MenuItem();
            menuItem33 = new System.Windows.Forms.MenuItem();

            contextMenu3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { menuItem31, menuItem32 ,menuItem33});
            menuItem31.Index = 0;
            menuItem31.Text = "Ver PDF";
            menuItem32.Index = 1;
            menuItem32.Text = "Ver XML";
            menuItem33.Index = 2;
            menuItem33.Text = "Eliminar de las facturas asignadas al asiento contable";

            menuItem31.Click += funcionVerPDF3;
            menuItem32.Click += funcionVerXML3;
            menuItem33.Click += eliminarFacturaDeLaLista;

            facturasAsignadasList.ContextMenu = contextMenu3;

               //!
            if(!lineaGlobal.Equals("ERROR"))
            {
                var source = new AutoCompleteStringCollection();
                var sourceRazonesSociales = new AutoCompleteStringCollection();

                List<String> rfcS = new List<String>();
                List<String> razonesSocialeS = new List<String>();

                String connString1 = "Database=" + Properties.Settings.Default.databaseFiscal + ";Data Source=" + Properties.Settings.Default.sunDatasource + ";Integrated Security=False;User ID='" + Properties.Settings.Default.user + "';Password='******';connect timeout = 10";
                try
                {
                    using (SqlConnection connection = new SqlConnection(connString1))
                    {
                        connection.Open();
                        String queryXML = "";
                        if(tipoDeContabilidadGlobal==1)
                        {
                            queryXML = "SELECT rfc,SUM(total) as total,razonSocial, count(*) as cuantos FROM [SU_FISCAL].[dbo].[facturacion_XML] WHERE STATUS = '1' GROUP BY rfc,razonSocial order by rfc asc";
                        }
                        else
                        {
                            if(tipoDeContabilidadGlobal==2)
                            {
                                 queryXML = "SELECT rfc,SUM(total) as total,razonSocial, count(*) as cuantos FROM [SU_FISCAL].[dbo].[facturacion_XML] WHERE STATUS = '2' GROUP BY rfc,razonSocial order by rfc asc";
                            }
                            else
                            {
                                queryXML = "SELECT rfc,SUM(total) as total,razonSocial, count(*) as cuantos FROM [SU_FISCAL].[dbo].[facturacion_XML] WHERE STATUS in('1', '2') GROUP BY rfc,razonSocial order by rfc asc";
                            }
                        }
                        using (SqlCommand cmdCheck = new SqlCommand(queryXML, connection))
                        {
                            SqlDataReader reader = cmdCheck.ExecuteReader();
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    double total = Convert.ToDouble(Math.Abs(reader.GetDecimal(1)));
                                    String rfc = reader.GetString(0);
                                    String razonSocial = reader.GetString(2);
                                    rfcS.Add(rfc);
                                    razonesSocialeS.Add(razonSocial);
                                }
                            }//if reader
                        }
                    }
                }
                catch (SqlException ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString(), "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                source.AddRange(rfcS.ToArray());

                sourceRazonesSociales.AddRange(razonesSocialeS.ToArray());

                rfcTextBox.AutoCompleteCustomSource = source;
                rfcTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                rfcTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;

                razonSocialText.AutoCompleteCustomSource = sourceRazonesSociales;
                razonSocialText.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                razonSocialText.AutoCompleteSource = AutoCompleteSource.CustomSource;

            //    rfcTextBox.KeyPress += rfcTextBox_KeyPress;

                //presupuesto
                String connString3 = "Database=" + Properties.Settings.Default.sunDatabase + ";Data Source=" + Properties.Settings.Default.sunDatasource + ";Integrated Security=False;User ID='" + Properties.Settings.Default.user + "';Password='******';connect timeout = 10";
                try
                {
                    using (SqlConnection connection1 = new SqlConnection(connString3))
                    {
                        connection1.Open();

                        String queryXML = "SELECT SUM(AMOUNT) as amount FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + unidadDeNegociosGlobal + "_" + Properties.Settings.Default.presupuesto + "_SALFLDG] WHERE ACCNT_CODE = '" + cuentaGlobal + "' AND PERIOD = " + periodoGlobal + "";

                        using (SqlCommand cmdCheck = new SqlCommand(queryXML, connection1))
                        {
                            SqlDataReader reader = cmdCheck.ExecuteReader();
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    if (!reader.IsDBNull(0))
                                    {
                                        presupuestoMensual.Text = "$" + String.Format("{0:n}", Convert.ToDouble(Math.Abs(reader.GetDecimal(0))));
                                    }
                                    else
                                    {
                                        presupuestoMensual.Text = "sin info";
                                    }
                                }
                            }
                            reader.Close();
                        }

                        String queryXML2 = "SELECT SUM(AMOUNT) as amount FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + unidadDeNegociosGlobal + "_" + Properties.Settings.Default.sunLibro + "_SALFLDG] WHERE ACCNT_CODE = '" + cuentaGlobal + "' AND PERIOD = " + periodoGlobal + "";
                        using (SqlCommand cmdCheck2 = new SqlCommand(queryXML2, connection1))
                        {
                            SqlDataReader reader2 = cmdCheck2.ExecuteReader();
                            if (reader2.HasRows)
                            {
                                while (reader2.Read())
                                {
                                    if (!reader2.IsDBNull(0))
                                    {
                                         mensualGastado.Text = "$" + String.Format("{0:n}", Convert.ToDouble(Math.Abs(reader2.GetDecimal(0))));
                                    }
                                    else
                                    {
                                        mensualGastado.Text = "sin info";
                                    }
                                 }
                                reader2.Close();
                            }
                        }

                        String queryXML3 = "SELECT SUM(AMOUNT) as amount FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + unidadDeNegociosGlobal + "_" + Properties.Settings.Default.presupuesto + "_SALFLDG] WHERE ACCNT_CODE = '" + cuentaGlobal + "' AND SUBSTRING( CAST(PERIOD AS NVARCHAR(7)),1,4)  = '" + periodoGlobal.ToString().Substring(0, 4) + "'";
                        using (SqlCommand cmdCheck3 = new SqlCommand(queryXML3, connection1))
                        {
                            SqlDataReader reader3 = cmdCheck3.ExecuteReader();
                            if (reader3.HasRows)
                            {
                                while (reader3.Read())
                                {
                                    if (!reader3.IsDBNull(0))
                                    {
                                        presupuestoAnual.Text = "$" + String.Format("{0:n}", Convert.ToDouble(Math.Abs(reader3.GetDecimal(0))));
                                    }
                                    else
                                    {
                                        presupuestoAnual.Text = "sin info";
                                    }
                                }
                                reader3.Close();
                            }
                        }

                        String queryXML4 = "SELECT SUM(AMOUNT) as amount FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + unidadDeNegociosGlobal + "_" + Properties.Settings.Default.sunLibro + "_SALFLDG] WHERE ACCNT_CODE = '" + cuentaGlobal + "' AND SUBSTRING( CAST(PERIOD AS NVARCHAR(7)),1,4)  = '" + periodoGlobal.ToString().Substring(0, 4) + "'";
                        using (SqlCommand cmdCheck4 = new SqlCommand(queryXML4, connection1))
                        {
                            SqlDataReader reader4 = cmdCheck4.ExecuteReader();
                            if (reader4.HasRows)
                            {
                                while (reader4.Read())
                                {
                                    if (!reader4.IsDBNull(0))
                                    {
                                        anualGastado.Text = "$" + String.Format("{0:n}", Convert.ToDouble(Math.Abs(reader4.GetDecimal(0))));
                                    }
                                    else
                                    {
                                        anualGastado.Text = "sin info";
                                    }
                                }
                                reader4.Close();
                            }
                        }

                    }
                }
                catch (SqlException ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString(), "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

            }
        }
        private void configuraciónToolStripMenuItem_Click(object sender, EventArgs e)
        {
            config form = new config();

            form.Show();
        }