Пример #1
0
        private static void AlCambiar(object source, FileSystemEventArgs e)
        {
            WatcherChangeTypes TipoDeCambio = e.ChangeType;

            if (e.Name.Substring(0, 3) == "MMS")
            {
                Console.WriteLine("El archivo {0} tuvo un cambio de: {1}", e.FullPath, TipoDeCambio.ToString());
                try
                {
                    System.Threading.Thread.Sleep(1000);
                    List <Registry> newRegistries = NewCleaner.NewCleaner.cleanCSV(e.FullPath);
                    List <Prueba>   newPruebas    = newRegistries.Select(r => Utils.toPrueba(r)).ToList();
                    CopyDBEntities  ctx           = new CopyDBEntities();

                    Console.WriteLine("* Starting writing...");
                    Console.WriteLine(newPruebas.Count);

                    ctx.Pruebas.AddRange(newPruebas);
                    ctx.SaveChanges();
                    Console.WriteLine("* Ending writing...");
                    Console.WriteLine("* Writing ended...");
                    //DataTable Table = Cleaner.cleanCSV(e.FullPath);

                    //foreach (DataRow row in Table.Rows)
                    //{
                    //    try
                    //    {
                    //        var loginInfo = databaseManager.PruebaProcedure(row[0].ToString(), row[1].ToString(), row[2].ToString(),
                    //                                                        row[3].ToString(), row[4].ToString(), row[5].ToString(),
                    //                                                        row[6].ToString(), row[7].ToString(), row[8].ToString(),
                    //                                                        row[9].ToString(), row[10].ToString(), row[11].ToString(),
                    //                                                        row[12].ToString(), row[13].ToString(), row[14].ToString(),
                    //                                                        row[15].ToString(), row[16].ToString(), row[17].ToString(),
                    //                                                        row[18].ToString(), row[19].ToString(), row[20].ToString(),
                    //                                                        row[21].ToString() == "" ? 0 : Convert.ToInt64(row[21]));
                    //        //Console.WriteLine("Error de Conexión con la Base de Datos");
                    //    }
                    //    catch (System.IO.IOException x)
                    //    {
                    //        Console.WriteLine("Error de Conexión con la Base de Datos");
                    //    }
                    //}

                    //var csv = File.ReadAllText(e.FullPath);
                    //var csv2 = csv.Split('\n');
                    //int cont = csv2.Length;

                    //for (int i = 0; i < cont; i++)
                    //{
                    //    if (i != 0)
                    //    {
                    //        String[] temp = csv2[i].Split(';');
                    //        if (temp.Length == 16)
                    //        {
                    //            try
                    //            {
                    //                var loginInfo = databaseManager.PruebaProcedure(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8], temp[9], temp[10], temp[11], temp[12], temp[13], temp[14], temp[15]);
                    //                Console.WriteLine("Error de Conexión con la Base de Datos");
                    //            }
                    //            catch (System.IO.IOException x)
                    //            {
                    //                Console.WriteLine("Error de Conexión con la Base de Datos");
                    //            }


                    //        }

                    //    }
                    //}
                    Console.WriteLine("Guardado exitoso");
                    Cleaner.PullData();
                    if (File.Exists(e.FullPath))
                    {
                        File.Delete(e.FullPath);
                    }
                }
                catch (System.IO.IOException x)
                {
                    Console.WriteLine(x.Message);
                }
            }
            else
            {
                Console.WriteLine("El documento guardado es incorrecto, y se procedió a borrarlo");
                if (File.Exists(e.FullPath))
                {
                    File.Delete(e.FullPath);
                }
            }
        }
Пример #2
0
        public static DataTable cleanCSV(string path)
        {
            // Get Entity as List

            CopyDBEntities ctx = new CopyDBEntities();

            List <Prueba> PruebasList = ctx.Pruebas.ToList();

            // Create DataTable from new CSV

            DataTable Table = IOUtils.GetDataTabletFromCSVFile(path);

            // Starting cleaning Process - Delete Sustr Entries

            DataTable woSustrTable = Table.AsEnumerable().Where(x => x[(int)Col.Cargadora].ToString() != "Sustr").CopyToDataTable();

            // Continue cleaning Process - Add Columns

            addColumns(woSustrTable);

            // Copy Entity to DataTable

            DataTable PruebaDataTable = woSustrTable.Clone();

            foreach (Prueba p in PruebasList)
            {
                PruebaDataTable.Rows.Add(Utils.toDataRow(PruebaDataTable, p));
            }

            IOUtils.WriteToCsvFile(PruebaDataTable, @"C:\Users\lesch\Desktop\SQLtoDT.csv");

            // Delete last entry per Cargadora
            // CRITIC: Validate it belongs to a Imaginary Row i.e. Hour field is 7:00:00 or 19:00:00

            IEnumerable <Prueba> lastEntryPerCarg = PruebasList
                                                    .GroupBy(l => l.Cargadora)
                                                    .Select(g => g.OrderByDescending(c => Utils.toDateTime(c.Fecha.ToString()))
                                                            .ThenByDescending(c => Utils.toHourTime(c.Hora.ToString()))
                                                            .FirstOrDefault()
                                                            ).Select(r => r);

            foreach (Prueba row in lastEntryPerCarg)
            {
                Console.WriteLine("Deleting following imaginary rows...");
                Console.WriteLine(row.Fecha);
                Console.WriteLine(row.Hora);
                ctx.Pruebas.Remove(row);
                ctx.SaveChanges();
            }

            // Get info like last useful row per Carg or last sequence information per carg
            // CRITIC: This is going to be queried from PruebaDataTable

            Dictionary <string, Tuple <string, string> > usefulRows = PruebaDataTable
                                                                      .AsEnumerable()
                                                                      .GroupBy(l => l[(int)Col.Cargadora])
                                                                      .Select(g => g.OrderByDescending(c => Utils.toDateTime(c[(int)Col.Fecha].ToString()))
                                                                              .ThenByDescending(c => Utils.toHourTime(c[(int)Col.Hora].ToString()))
                                                                              .Skip(1).FirstOrDefault()
                                                                              ).ToDictionary(g => g[(int)Col.Cargadora].ToString(), g => Tuple.Create(g[(int)Col.Fecha].ToString().Trim(), g[(int)Col.Hora].ToString().Trim()));

            foreach (var row in usefulRows.Keys)
            {
                Console.WriteLine("Useful...");
                Console.WriteLine(row);
                Console.WriteLine(usefulRows[row]);
            }

            // Add Imaginary Rows
            // This process should consider the data useful row per Carg from the Previous Stage

            addImaginaryTurnTimeRows(ref woSustrTable, usefulRows);

            // Order Table so calculations such as cicle make sense

            DataTable augmentedTable = woSustrTable.AsEnumerable()
                                       .OrderBy(t => t[(int)Col.Cargadora])
                                       .ThenBy(t => DateTime.ParseExact(t[(int)Col.Fecha].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture))
                                       .ThenBy(t => Utils.toHourTime(t[(int)Col.Hora].ToString()))
                                       .CopyToDataTable();


            Dictionary <Tuple <string, string>, Tuple <string, long> >
            secuenceLastValues = PruebaDataTable
                                 .AsEnumerable()
                                 .Where(l => Convert.ToInt64(l[(int)Col.SecuenciaID].ToString().Trim()) != 0)
                                 .GroupBy(l => l[(int)Col.Cargadora])
                                 .Select(g => g.OrderBy(c => c[(int)Col.SecuenciaID])
                                         //.ThenBy(c => c[(int)Col.Producto])
                                         .ThenByDescending(c => Utils.toHourTime(c[(int)Col.Hora].ToString()))
                                         .FirstOrDefault()
                                         ).ToDictionary(g => Tuple.Create(g[(int)Col.Cargadora].ToString().Trim(),
                                                                          g[(int)Col.Producto].ToString().Trim()),
                                                        g => Tuple.Create(g[(int)Col.Funcion].ToString().Trim(),
                                                                          Convert.ToInt64(g[(int)Col.SecuenciaID].ToString().Trim())));

            //PruebaDataTable
            //            .AsEnumerable()
            //            .Where(l => Convert.ToInt64(l[(int)Col.SecuenciaID].ToString().Trim()) != 0)
            //            .ToList()
            //            .ForEach(x => { Console.WriteLine(x); });



            foreach (var key in secuenceLastValues.Keys)
            {
                Console.WriteLine(key);
                Console.WriteLine(secuenceLastValues[key]);
            }

            long lastSequence = PruebaDataTable
                                .AsEnumerable()
                                .OrderByDescending(l => l[(int)Col.SecuenciaID].ToString().Trim())
                                .Select(l => Convert.ToInt64(l[(int)Col.SecuenciaID].ToString()))
                                .FirstOrDefault();

            Console.WriteLine("Last Sequence");
            Console.WriteLine(lastSequence);

            // This can be optimized with for each and linq

            for (int i = 0; i < augmentedTable.Rows.Count; i++)
            {
                DataRow row = augmentedTable.Rows[i];

                if (i == 0 && usefulRows.ContainsKey(row[(int)Col.Cargadora].ToString()))
                {
                    DataRow useful = augmentedTable.NewRow();
                    useful[(int)Col.Fecha]     = usefulRows[row[(int)Col.Cargadora].ToString()].Item1.ToString().Trim();
                    useful[(int)Col.Hora]      = usefulRows[row[(int)Col.Cargadora].ToString()].Item2.ToString().Trim();
                    useful[(int)Col.Cargadora] = row[(int)Col.Cargadora];
                    row[(int)Col.Ciclo]        = calculateCicleTime(useful, row);
                }

                if (i > 0)
                {
                    DataRow prevRow = augmentedTable.Rows[i - 1];
                    if (row[(int)Col.Cargadora].ToString() != prevRow[(int)Col.Cargadora].ToString() && usefulRows.ContainsKey(row[(int)Col.Cargadora].ToString()))
                    {
                        DataRow useful = augmentedTable.NewRow();
                        useful[(int)Col.Fecha]     = usefulRows[row[(int)Col.Cargadora].ToString()].Item1.ToString().Trim();
                        useful[(int)Col.Hora]      = usefulRows[row[(int)Col.Cargadora].ToString()].Item2.ToString().Trim();
                        useful[(int)Col.Cargadora] = row[(int)Col.Cargadora];
                        row[(int)Col.Ciclo]        = calculateCicleTime(useful, row);
                    }
                    else
                    {
                        row[(int)Col.Ciclo] = calculateCicleTime(prevRow, row);
                    }
                    // Get first per carg and update with corresponding useful row
                }

                row[(int)Col.Rendimiento] = calculatePerformance(row);

                row[(int)Col.Fecha_Mina] = shiftDates(row);

                row[(int)Col.Turno] = calculateShift(row);

                row[(int)Col.Mascara] = calculateMask(row);

                if (row[(int)Col.Funcion].ToString().Trim() == "Agregar" || row[(int)Col.Funcion].ToString().Trim() == "Borrar total")
                {
                    string cargadora = row[(int)Col.Cargadora].ToString().Trim();
                    string producto  = row[(int)Col.Producto].ToString().Trim();
                    Tuple <string, string> rowKey = Tuple.Create(cargadora, producto);

                    if (secuenceLastValues.ContainsKey(rowKey))
                    {
                        if (secuenceLastValues[rowKey].Item1 == "Borrar total")
                        {
                            lastSequence++;
                            row[(int)Col.SecuenciaID]  = lastSequence.ToString();
                            secuenceLastValues[rowKey] = Tuple.Create(secuenceLastValues[rowKey].Item1, lastSequence);
                        }
                        else
                        {
                            row[(int)Col.SecuenciaID] = secuenceLastValues[rowKey].Item2.ToString();
                        }
                    }
                    else
                    {
                        lastSequence++;
                        row[(int)Col.SecuenciaID]  = lastSequence.ToString();
                        secuenceLastValues[rowKey] = Tuple.Create(row[(int)Col.Funcion].ToString().Trim(), lastSequence);
                    }
                }
            }

            //var cargsLookUp = augmentedTable.AsEnumerable().ToLookup(x => x[(int)Col.Cargadora]);
            //IEnumerable<string> cargs = cargsLookUp.Select(g => g.Key.ToString()).AsEnumerable();

            //foreach (string s in cargs)
            //{
            //    cargsLookUp[s].ToList();
            //}

            //Dictionary<string, Dictionary<string, Prueba>> cargadoraProductoRow = new Dictionary<string, Dictionary<string, Prueba>>();


            //cargadoraProductoRow["5"].Add("Desmonte", new Prueba());

            // Little correction
            //DataColumn indexColumn = new DataColumn("Index");
            //indexColumn.AutoIncrement = true;
            //augmentedTable.Columns.Add(indexColumn);


            // Calculate Borrar Total Transformation - This should consider

            for (int i = 0; i < augmentedTable.Rows.Count; i++)
            {
                DataRow row = augmentedTable.Rows[i];
                row[(int)Col.Index] = i.ToString(); // Index algorithm may be wrong

                if ((row[(int)Col.Hora].ToString() == "7:00:00" || row[(int)Col.Hora].ToString() == "19:00:00") && i < augmentedTable.Rows.Count - 1)
                {
                    DataRow nextRow = augmentedTable.Rows[i + 1];
                    nextRow[(int)Col.Mascara] = "Tiempo No Disponible";
                }
            }


            //Cargadora
            // Dictionary<Tuple<string, string>, Tuple<string, string>> cardAndProdToFuncAndSec =
            // This also should return a sum of the last sequences, but I'm not there yet

            //cargadora + producto => funcion + secuencia



            //augmentedTable.AsEnumerable().ToList().Each((row, index) =>
            //{
            //    // Update Dictionary

            //    if (row[(int)Col.Funcion].ToString().Trim() != "Agregar" || row[(int)Col.Funcion].ToString().Trim()  != "Borrar total")
            //    {

            //    }


            //});

            var queryJustValidColumns = augmentedTable.Select().Where(x => (x[(int)Col.Secuencia].ToString() == "1") ||
                                                                      x[(int)Col.Funcion].ToString().Contains("Borrar"));

            if (queryJustValidColumns.Count() != 0)
            {
                DataTable justValidColumns = queryJustValidColumns.CopyToDataTable();

                List <Tuple <Int32, Int32> > indexCollection = new List <Tuple <Int32, Int32> >();

                for (int i = 0; i < justValidColumns.Rows.Count - 1; i++)
                {
                    DataRow row     = justValidColumns.Rows[i];
                    DataRow nextRow = justValidColumns.Rows[i + 1];

                    if (row[(int)Col.Cargadora].ToString() != nextRow[(int)Col.Cargadora].ToString())
                    {
                        continue;
                    }

                    if (row[(int)Col.Funcion].ToString() == "Agregar" && nextRow[(int)Col.Funcion].ToString().Contains("Borrar"))
                    {
                        indexCollection.Add(new Tuple <Int32, Int32>(Convert.ToInt32(row[(int)Col.Index].ToString()), Convert.ToInt32(nextRow[(int)Col.Index].ToString())));
                    }
                }

                foreach (var t in indexCollection)
                {
                    double sumaRealPeso  = 0;
                    double sumaRealCiclo = 0;

                    for (int i = t.Item1; i < t.Item2; i++)
                    {
                        DataRow row = augmentedTable.Rows[i];

                        if (row[(int)Col.Funcion].ToString() == "Agregar" && row[(int)Col.Mascara].ToString() == "Tiempo Efectivo")
                        {
                            sumaRealPeso += double.Parse(row[(int)Col.Peso].ToString(), CultureInfo.GetCultureInfo("es-MX"));
                        }
                        if (row[(int)Col.Secuencia].ToString() != "1")
                        {
                            sumaRealCiclo += double.Parse(row[(int)Col.Ciclo].ToString());
                        }
                    }
                    DataRow borrartotal = augmentedTable.Rows[t.Item2];
                    sumaRealCiclo += double.Parse(borrartotal[(int)Col.Ciclo].ToString());

                    borrartotal[(int)Col.Ciclo] = sumaRealCiclo.ToString();
                    borrartotal[(int)Col.Peso]  = sumaRealPeso.ToString();
                }
            }

            //WriteToCsvFile(justValidColumns, "C:\\Users\\lesch\\Desktop\\test2.CSV");

            return(augmentedTable);
        }