Exemplo n.º 1
0
        public ActionResult Upload(HttpPostedFileBase upload, HttpPostedFileBase upload2, DateTime Date)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                HttpCookie cookie = new HttpCookie("My localhost cookie");

                //найдем старые данные за этот месяц и заменим их не щадя
                List <Musor> dbMusor = new List <Musor>();
                try { dbMusor = db.Musors.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList(); }
                catch { }
                pro100 = dbMusor.Count;
                foreach (Musor S in dbMusor)
                {
                    try
                    {
                        db.Musors.Remove(S);
                        db.SaveChanges();
                        procount++;
                        progress = Convert.ToInt16(procount / pro100 * 100);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                        ProgressHub.SendMessage("Удаляем старые данные...", progress);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                Excel.Application ApExcel = new Excel.Application();
                Excel.Workbooks   WB      = null;
                WB = ApExcel.Workbooks;
                Excel.Workbook WbExcel = ApExcel.Workbooks.Add(System.Reflection.Missing.Value);


                for (int h = 1; h <= 31; h++)
                {
                    ApExcel.Worksheets.Add(Type.Missing);//Добавляем лист
                    Excel.Worksheet WS = WbExcel.Sheets[1];
                    WS.Name = h.ToString() + ".01.2019";
                    Excel.Range range;              //рэндж
                    ApExcel.Visible        = false; //невидимо
                    ApExcel.ScreenUpdating = false; //и не обновляемо

                    //call this method inside your working action
                    ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                    // получаем имя файла
                    string fileName  = Path.GetFileName(upload.FileName);
                    string fileName2 = Path.GetFileName(upload2.FileName);
                    // сохраняем файл в папку Files в проекте
                    if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Files/"));
                    }
                    upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                    upload2.SaveAs(Server.MapPath("~/Files/" + fileName2));

                    //обрабатываем файл после загрузки
                    //Загружаем файл ТБО
                    string[] Names2 = new string[] { "Государственный регистрационный знак", "Итого принято ТКО за смену, кг", "Итого принято ТКО за смену, куб.м." };
                    string   Error2 = "";
                    List <List <string> > excel2 = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName2), Names2, out Error2, h.ToString());
                    //Загружаем файл наших выездов
                    string[] Names = new string[] { "Дата", "Автомобиль", "Улица", "Номер дома", "Объем ТКО за смену, м3" };
                    string   Error = "";
                    List <List <string> > excel  = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, h.ToString());
                    List <Musor>          Result = new List <Musor>();
                    if (excel.Count < 1 || excel2.Count < 1)
                    {
                        //если нифига не загрузилось то
                        ViewBag.Error = Error + Error2;
                        ViewBag.Names = Names;
                        return(View("NotUpload"));
                    }
                    else
                    {
                        pro100 = excel.Count;

                        List <Musor>  Mus   = new List <Musor>();
                        List <string> NeMus = new List <string>();



                        //для каждой строки в экселе "Дата", "Автомобиль", "Улица", "Номер дома", "Объем ТКО за смену, м3"
                        Musor  Old  = new Musor();
                        string Name = "";
                        foreach (List <string> L in excel)
                        {
                            try
                            {
                                if (L[1] != null && L[1] != "" && L[1] != "0")
                                {
                                    Musor MusorKA = new Musor();

                                    MusorKA.Date   = Convert.ToDateTime(L[0]);
                                    MusorKA.Name   = L[1].ToUpper().Replace(" ", "").Replace("154", "").Replace("54", "").Replace("ГАЗ", "").Replace("САЗ", "").Replace("МАЗ", "").Replace("ВАЗ", "").Replace("ЗИЛ", "").Replace("МТЗ", "").Replace("-", "");
                                    MusorKA.AvtoID = 0;
                                    try
                                    {
                                        MusorKA.AvtoID = db.Avtomobils.Where(x => MusorKA.Name.Equals(x.Number)).Select(x => x.Id).First();
                                    }
                                    catch
                                    {
                                    }

                                    MusorKA.KgOut   = 0;
                                    MusorKA.Mesta   = (L[2] + L[3]).Replace(" ", "");
                                    MusorKA.ObiemIn = Convert.ToDecimal(L[4]);
                                    Mus.Add(MusorKA);
                                    Old = MusorKA;
                                }
                                else
                                {
                                    if (L[2] != "0" && L[2] != null && L[2] != "")
                                    {
                                        Musor MusorKA = new Musor();

                                        MusorKA.Date    = Old.Date;
                                        MusorKA.Name    = Old.Name;
                                        MusorKA.AvtoID  = Old.AvtoID;
                                        MusorKA.KgOut   = 0;
                                        MusorKA.Mesta   = (L[2] + L[3]).Replace(" ", "");
                                        MusorKA.ObiemIn = Convert.ToDecimal(L[4]);
                                        Mus.Add(MusorKA);
                                    }
                                    else
                                    {
                                        NeMus.Add(L[0] + ";" + L[1] + ";" + L[2] + ";" + L[3] + ";" + L[4] + ";");
                                        continue;
                                    }
                                }
                                // db.Musors.Add(MusorKA);
                                // db.SaveChanges();
                            }
                            catch
                            {
                                if (L[0] != "" && L[0] != null)
                                {
                                    Name = L[0].ToUpper().Replace(" ", "").Replace("154", "").Replace("54", "").Replace("ГАЗ", "").Replace("САЗ", "").Replace("МАЗ", "").Replace("ВАЗ", "").Replace("ЗИЛ", "").Replace("МАРШРУТ", "").Replace("МТЗ", "").Replace("-", "");
                                    if (Name.Contains("№"))
                                    {
                                        for (int i = 0; i < 10; i++)
                                        {
                                            Name = Name.Replace("№" + i.ToString(), "");
                                        }
                                    }
                                    Old.AvtoID = 0;
                                    try
                                    {
                                        Old.AvtoID = db.Avtomobils.Where(x => Name.Equals(x.Number)).Select(x => x.Id).First();
                                        Old.Name   = Name;
                                    }
                                    catch
                                    {
                                        NeMus.Add(L[0] + ";" + L[1] + ";" + L[2] + ";" + L[3] + ";" + L[4] + ";");
                                        continue;
                                    }
                                }
                                else
                                {
                                    NeMus.Add(L[0] + ";" + L[1] + ";" + L[2] + ";" + L[3] + ";" + L[4] + ";");
                                    continue;
                                }
                            }
                            procount++;
                            progress = Convert.ToInt16(50 + procount / pro100 * 50);
                            ProgressHub.SendMessage("Обрабатываем файл УЭВ...", progress);
                            if (procount > pro100)
                            {
                                procount = Convert.ToInt32(pro100);
                            }
                        }
                        List <string> Nam = Mus.Select(x => x.Name).Distinct().ToList();

                        foreach (string N in Nam)
                        {
                            if (N != "")
                            {
                                List <Musor> summa = Mus.Where(x => x.Name.Equals(N)).ToList();
                                string       Mest  = "";
                                decimal      sum   = 0;
                                for (int i = 0; i < summa.Count; i++)
                                {
                                    Mest += summa[i].Mesta + "\r\n";
                                    sum  += summa[i].ObiemIn;
                                }
                                Musor M = new Musor();
                                M.Date     = summa[0].Date;
                                M.AvtoID   = summa[0].AvtoID;
                                M.Mesta    = Mest;
                                M.Name     = N;
                                M.ObiemIn  = sum;
                                M.ObiemOut = 0;
                                M.KgOut    = 0;
                                //Теперь ищем объёмы с полигона "Государственный регистрационный знак", "Итого принято ТКО за смену, кг", "Итого принято ТКО за смену, куб.м."
                                foreach (List <string> P in excel2)
                                {
                                    if (P[0].ToUpper().Replace(" ", "").Contains(N))
                                    {
                                        M.ObiemOut = Convert.ToDecimal(P[2]);
                                        M.KgOut    = Convert.ToDecimal(P[1]);
                                        break;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }

                                //Ищем водителя и пробег в ездках
                                Ezdka E = new Ezdka();
                                try
                                {
                                    E = db.Ezdkas.Where(x => x.Date.Year == M.Date.Year && x.Date.Month == M.Date.Month && x.Date.Day == M.Date.Day && x.AvtoId == M.AvtoID).First();
                                }
                                catch
                                {
                                }
                                if (E.Voditel == null)
                                {
                                    E.Voditel = "";
                                }
                                if (E.Probeg == null)
                                {
                                    E.Probeg = 0;
                                }
                                M.Driver = E.Voditel;
                                M.Probeg = E.Probeg;

                                Result.Add(M);
                            }
                        }
                    }

                    //Выводим отчет

                    int stroka = 1;
                    WS.Cells[stroka, 1] = "Приложение №3 ";
                    range = WS.get_Range("A" + stroka.ToString(), "P" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    stroka++;
                    WS.Cells[stroka, 1] = "к договору на оказание услуг по транспортированию твердых коммунальных отходов №______от " + Result[0].Date.ToString("dd/MM/yyyy");
                    range = WS.get_Range("A" + stroka.ToString(), "P" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    stroka++;
                    WS.Cells[stroka, 1] = "Выезд на маршрут";
                    range = WS.get_Range("A" + stroka.ToString(), "C" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 4] = "Загрузка ТКО";
                    range = WS.get_Range("D" + stroka.ToString(), "G" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true, 13, 70);
                    WS.Cells[stroka, 8] = "Транспортирование ТКО";
                    range = WS.get_Range("H" + stroka.ToString(), "J" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 11] = "Выгрузка ТКО";
                    range = WS.get_Range("K" + stroka.ToString(), "N" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 15] = "Примечание";
                    range = WS.get_Range("O" + stroka.ToString(), "O" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    stroka++;
                    WS.Cells[stroka, 1] = "Дата";
                    range = WS.get_Range("A" + stroka.ToString(), "A" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true, 13, 20);
                    WS.Cells[stroka, 2] = "Номер рейса";
                    range = WS.get_Range("B" + stroka.ToString(), "B" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 3] = "ФИО водителя";
                    range = WS.get_Range("C" + stroka.ToString(), "C" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 4] = "Место накопления(адрес загрузки мусоровоза)";
                    range = WS.get_Range("D" + stroka.ToString(), "D" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true, 13, 60);
                    WS.Cells[stroka, 5] = "Объем / тип контейнера";
                    range = WS.get_Range("E" + stroka.ToString(), "E" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 6] = "Время загрузки";
                    range = WS.get_Range("F" + stroka.ToString(), "F" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 7] = "Объем загрузки";
                    WS.Cells[stroka, 8] = "Показания одометра, км";
                    range = WS.get_Range("H" + stroka.ToString(), "I" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 10] = "Показания одометра Плечо доставки, км";
                    WS.Cells[stroka, 11] = "Место(адрес) выгрузки";
                    range = WS.get_Range("K" + stroka.ToString(), "K" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 12] = "Дата / время выгрузки";
                    range = WS.get_Range("L" + stroka.ToString(), "L" + (stroka + 1).ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    WS.Cells[stroka, 13] = "Объем и / или масса выгрузки";
                    range = WS.get_Range("O" + stroka.ToString(), "P" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true);
                    stroka++;
                    WS.Cells[stroka, 1] = "Время";
                    range = WS.get_Range("A" + stroka.ToString(), "A" + stroka.ToString());
                    Opr.RangeMerge(ApExcel, range, true, true, 13, 20);
                    WS.Cells[stroka, 7]  = "Объем, м³";
                    WS.Cells[stroka, 8]  = "Начало маршрута";
                    WS.Cells[stroka, 9]  = "Конец маршрута";
                    WS.Cells[stroka, 10] = "(от последнего места загрузки до места выгрузки)";
                    WS.Cells[stroka, 13] = "Объем, м³";
                    WS.Cells[stroka, 14] = "Масса, кг";
                    range                     = WS.get_Range("A1", "O15");
                    range.Font.Size           = 13;
                    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    range.VerticalAlignment   = Excel.XlHAlign.xlHAlignCenter;
                    range.WrapText            = true;
                    range.Font.Bold           = true;
                    range.ColumnWidth         = 15;
                    range                     = WS.get_Range("A1", "A1");
                    range.ColumnWidth         = 20;
                    range                     = WS.get_Range("B1", "B1");
                    range.ColumnWidth         = 6;
                    range                     = WS.get_Range("C1", "C1");
                    range.ColumnWidth         = 20;
                    range                     = WS.get_Range("D1", "D1");
                    range.ColumnWidth         = 60;
                    range                     = WS.get_Range("E1", "E1");
                    range.ColumnWidth         = 10;
                    range                     = WS.get_Range("G1", "G1");
                    range.ColumnWidth         = 10;
                    range                     = WS.get_Range("J1", "J1");
                    range.ColumnWidth         = 10;
                    range                     = WS.get_Range("M1", "O1");
                    range.ColumnWidth         = 10;
                    stroka++;
                    for (int i = 0; i < Result.Count(); i++)
                    {
                        WS.Cells[stroka, 1]  = Result[i].Date;
                        WS.Cells[stroka, 2]  = (i + 1).ToString();
                        WS.Cells[stroka, 3]  = Result[i].Driver;
                        WS.Cells[stroka, 4]  = Result[i].Mesta;
                        WS.Cells[stroka, 5]  = "0,75/M";
                        WS.Cells[stroka, 7]  = Result[i].ObiemIn;
                        WS.Cells[stroka, 10] = Result[i].Probeg;
                        WS.Cells[stroka, 11] = "Полигон ТБО";
                        WS.Cells[stroka, 13] = Result[i].ObiemOut;
                        WS.Cells[stroka, 14] = Result[i].KgOut;
                        WS.Cells[stroka, 15] = Result[i].Name;
                        range                     = WS.get_Range("A" + stroka, "A" + stroka);
                        range.RowHeight           = 50;
                        range.Font.Size           = 12;
                        range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                        range.VerticalAlignment   = Excel.XlHAlign.xlHAlignCenter;
                        range.WrapText            = true;
                        range.Borders.LineStyle   = Excel.XlLineStyle.xlContinuous;

                        stroka++;
                    }
                }


                string patch    = Server.MapPath("~/Content/OtchetECO.xlsx"); //@"C:\inetpub\Otchets\ASP" + "X" + Year.Remove(0, 2) + "X" + Month + ".xlsx";//Server.MapPath("~\\ASP" +"X"+ Year.Remove(0,2) +"X"+ Month + ".xlsx");
                string filename = "OtchetECO.xlsx";
                string path2    = Url.Content("~/Content/OtchetECO.xlsx");

                // RedirectToAction("DownloadPS", new {path,filename});
                string dat         = path2; //+ filename;
                string contentType = "application/vnd.ms-excel";
                //



                // Сохранение файла Excel.
                try
                {
                    Opr.EstLiFile(patch);
                    WbExcel.SaveCopyAs(patch);//сохраняем в папку
                }
                catch
                {
                }
                //WbExcel.PrintOutEx(1, 1, 1, true, null, null, null, null, null);//печать сразу после сохранения
                ApExcel.Visible        = false; //невидимо
                ApExcel.ScreenUpdating = false; //и не обновляемо
                                                // Закрытие книги.
                WbExcel.Close(false, "", Type.Missing);
                // Закрытие приложения Excel.


                ApExcel.Quit();


                Marshal.FinalReleaseComObject(WbExcel);
                Marshal.FinalReleaseComObject(WB);



                GC.Collect();
                Marshal.FinalReleaseComObject(ApExcel);
                GC.WaitForPendingFinalizers();



                ViewBag.date = Date;
                ViewBag.file = filename;
                ViewBag.dat  = dat;
                // return File(path2, contentType, filename);
                //  return Json(dat);
                return(View("UploadComplete"));
            }

            return(RedirectToAction("Upload"));
        }
Exemplo n.º 2
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date, bool JQ = false)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                //найдем старые данные за этот месяц и заменим их не щадя
                List <OBSD> dbOBSD = db.OBSDs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();
                pro100 = dbOBSD.Count;

                try
                {
                    db.OBSDs.RemoveRange(dbOBSD);
                    db.SaveChanges();
                    procount++;
                    progress = Convert.ToInt16(procount / pro100 * 100);
                    if (procount > pro100)
                    {
                        procount = Convert.ToInt32(pro100);
                    }
                    ProgressHub.SendMessage("Удаляем старые данные ОБСД...", progress);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }



                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));

                //обрабатываем файл после загрузки
                string   Vkladka            = "Общая";
                string[] Names              = new string[] { "адрес", "лицевой", "услуга", "начислениефактическое", "фио", "сальдоисходящее", "квартира" };
                string   Error              = "";
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, Vkladka);
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Names = Names;
                    ViewBag.Error = Error;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    if (!JQ)
                    {
                        return(View("NotUpload"));
                    }
                    else
                    {
                        return(Json(Error));
                    }
                }
                else
                {
                    List <Adres> Adresa = db.Adres.ToList();// грузим все адреса из БД
                    foreach (Adres A in Adresa)
                    {
                        A.Adress = A.Adress.Replace(" ", "");
                    }
                    List <TableService> Services = db.TableServices.ToList();
                    foreach (TableService S in Services)//Преобразуем в беспробельных
                    {
                        S.Type = S.Type.Replace(" ", "");
                    }

                    if (!JQ)
                    {
                        ZapuskPoiska(excel, Date, Adresa, Services);
                    }
                    else
                    {
                        FastPoisk(excel, Date, Adresa, Services);
                    }


                    ViewBag.date = Date;
                    ViewBag.file = fileName;

                    if (!JQ)
                    {
                        return(View("UploadComplete"));
                    }
                    else
                    {
                        return(Json("Ошибок загрузки нет!"));
                    }
                }
            }
            if (!JQ)
            {
                return(RedirectToAction("NotUpload"));
            }
            else
            {
                return(Json("Файл не выбран или неверный формат файла."));
            }
        }
Exemplo n.º 3
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date, bool JQ = false)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                //найдем старые данные за этот месяц и заменим их не щадя
                List <IPU> dbIPU = db.IPUs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();
                pro100 = dbIPU.Count;
                try
                {
                    procount++;
                    progress = Convert.ToInt16(procount / pro100 * 100);
                    if (procount > pro100)
                    {
                        procount = Convert.ToInt32(pro100);
                    }
                    ProgressHub.SendMessage("Удаляем старые данные...", progress);
                    db.IPUs.RemoveRange(dbIPU);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                }


                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));

                //обрабатываем файл после загрузки
                string   Vkladka            = "для УЭВ по ГВС без ОПУ";
                string   Error              = "";
                string[] Names              = new string[] { "адрес", "начислениепонормативу(руб.)", "начислениепосчетчику(руб.)", "Номер счетчика" };
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, Vkladka);
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    if (!JQ)
                    {
                        return(View("NotUpload"));
                    }
                    else
                    {
                        return(Json(Error));
                    }
                }
                else
                {
                    List <Adres> Adresa = db.Adres.ToList();// грузим все адреса из БД
                    foreach (Adres A in Adresa)
                    {
                        A.Adress = A.Adress.Replace(" ", "");
                    }

                    if (!JQ)
                    {
                        ZapuskPoiska(excel, Date, Adresa);
                    }
                    else
                    {
                        Poisk(excel, Date, Adresa);
                    }
                    ViewBag.date = Date;
                    ViewBag.file = fileName;
                    if (!JQ)
                    {
                        return(View("UploadComplete"));
                    }
                    else
                    {
                        return(Json("Ошибок загрузки нет!"));
                    }
                }
            }
            if (!JQ)
            {
                return(RedirectToAction("NotUpload"));
            }
            else
            {
                return(Json("Файл не выбран или неверный формат файла."));
            }
        }
Exemplo n.º 4
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                HttpCookie cookie = new HttpCookie("My localhost cookie");

                //найдем старые данные за этот месяц и заменим их не щадя
                List <SVN> dbSVN = db.SVNs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();


                pro100 = dbSVN.Count;
                foreach (SVN S in dbSVN)
                {
                    try
                    {
                        db.SVNs.Remove(S);
                        db.SaveChanges();
                        procount++;
                        progress = Convert.ToInt16(procount / pro100 * 100);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                        ProgressHub.SendMessage("Удаляем старые данные...", progress);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                // Установить значения в нем
                cookie["Download"] = "0";
                // Добавить куки в ответ
                Response.Cookies.Add(cookie);



                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                //обрабатываем файл после загрузки



                string[] Names = new string[] { "STREET_HOUSE", "SERVICE", "DELIVER", "CHARGE_PLAN", "CHARGE_FACT", "MAKET" };
                string   Error = "";
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error);
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    return(View("NotUpload"));
                }
                else
                {
                    pro100 = excel.Count;
                    SVN          SVNKA  = new SVN();
                    List <Adres> Adresa = db.Adres.ToList();// грузим все адреса из БД

                    List <TableService>   TSdb     = db.TableServices.ToList();
                    List <List <string> > Services = new List <List <string> >();
                    //один раз преобразуем таблицу сервисов для сравнения чтоб в цикле не вызывать
                    int ser = 0;
                    foreach (TableService T in TSdb)
                    {
                        T.Type = T.Type.Replace(" ", "").ToUpper();
                        Services.Add(new List <string>());
                        Services[ser].Add(T.Type);//для проверки сохраняем
                        ser++;
                    }
                    //для каждой строки в экселе
                    foreach (List <string> L in excel)
                    {
                        string Service = L[1].Replace(" ", "").ToUpper();

                        bool EstService = false;
                        if (Service.Contains("ОБЩ.ИМУЩ."))
                        {
                        }


                        foreach (TableService TS in TSdb)
                        {
                            if (TS.Type.Equals(Service))
                            {
                                EstService      = true;
                                SVNKA.ServiceId = TS.Id;
                                ser             = TS.Id - 1;//номер сервиса по порядку с 0
                                break;
                            }
                        }
                        //если сервис не найден в списке то и адрес не проверяем идем дальше
                        if (EstService)
                        {
                            bool   EstName = false;
                            string Name    = L[0].Replace(" ", "");
                            foreach (Adres A in Adresa)
                            {
                                string AName = A.Adress.Replace(" ", "");
                                if (AName.Equals(Name))
                                {
                                    //если в массиве адресов есть адрес из строчки то сохраняем айдишник
                                    EstName       = true;
                                    SVNKA.AdresId = A.Id;
                                    if (ser < 4)
                                    {
                                        Services[ser].Add(Name);
                                    }
                                    // Adresa.Remove(A);//уменьшаем массив для дальнейшего ускорения поиска
                                    break;
                                }
                            }
                            //если имени нет в списке то и сохранять не будем
                            if (EstName)
                            {
                                try
                                {
                                    SVNKA.Plan  = Convert.ToDecimal(L[3]);
                                    SVNKA.Fact  = Convert.ToDecimal(L[4]);
                                    SVNKA.Maket = Convert.ToDecimal(L[5]);
                                    SVNKA.Agent = L[2];
                                    SVNKA.Date  = Date;
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + SVNKA.AdresId + " " + e.Message);
                                }

                                try
                                {
                                    db.SVNs.Add(SVNKA);
                                    db.SaveChanges();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                }
                            }
                        }
                        procount++;
                        progress = Convert.ToInt16(50 + procount / pro100 * 50);
                        ProgressHub.SendMessage("Обрабатываем файл СВН...", progress);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                    }
                    List <string> Adr = Adresa.Select(x => x.Adress).ToList();
                    for (int a = 0; a < Adr.Count; a++)
                    {
                        Adr[a] = Adr[a].Replace(" ", "").ToUpper();
                    }


                    ViewBag.VsegoServices = TSdb.Count;
                    ViewBag.Services      = Services;
                    ViewBag.date          = Date;
                    ViewBag.file          = fileName;



                    return(View("UploadComplete"));
                }
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 5
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date, bool JQ = false)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                //найдем старые данные за этот месяц и заменим их не щадя
                List <Arendator> dbArendator = db.Arendators.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();
                List <string>    AR          = new List <string>();

                pro100 = dbArendator.Count;

                try
                {
                    db.Arendators.RemoveRange(dbArendator);
                    db.SaveChanges();
                    procount++;
                    progress = Convert.ToInt16(procount / pro100 * 100);
                    if (procount > pro100)
                    {
                        procount = Convert.ToInt32(pro100);
                    }
                    ProgressHub.SendMessage("Удаляем старые данные...", progress);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }


                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                //обрабатываем файл после загрузки



                string OpenText = Server.MapPath("~/Files/" + fileName);

                string Vkladka = Date.Month.ToString();//укажем номер вкладки
                List <List <string> > Dannie;

                int[]    X     = new int[] { 1, 2, 3, 4, 6, 8, 10 };
                string[] Names = new string[] { "адрес", "№дома", "теплотаотопл, гкалфактич", "площадь", "теплота1/12(гкал,)", "гвкуб,м", "хвкуб,м" };
                string   Error;
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, Vkladka, X);
                if (excel.Count < 1)
                {
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    //если нифига не загрузилось то
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");

                    if (!JQ)
                    {
                        return(View("NotUpload"));
                    }
                    else
                    {
                        return(Json(Error));
                    }
                }

                string HomeAdress;
                string ADRESS = "";
                string CODE   = "";
                progress = 0;
                pro100   = excel.Count;
                procount = 0;
                for (int i = 0; i < excel.Count; i++)
                {
                    Arendator Ar     = new Arendator();
                    bool      swsave = false;
                    // for (int j = 0; j < Dannie[i].Count; j++)
                    //{
                    if (excel[i][1] != null)
                    {
                        excel[i][1] = excel[i][1].Replace(" ", "");
                    }
                    if (excel[i][1] != null && excel[i][1] != "")//Когда дошли до номера дома значит это дом и в нем есть арендаторы
                    {
                        decimal ploshad = 0;
                        try { ploshad = Convert.ToDecimal(excel[i][3]); } catch { }
                        decimal teplota12 = 0;
                        try { teplota12 = Convert.ToDecimal(excel[i][4]); } catch { }
                        string adr = excel[i][0].ToString();
                        adr = adr.ToUpper();
                        adr = adr.Replace("ПР.", "");
                        adr = adr.Replace("М.ДЖАЛИЛЯ", "МУСЫ ДЖАЛИЛЯ");
                        if (adr.Equals("ШЛЮЗОВАЯ"))
                        {
                        }
                        int ii = adr.IndexOf(" ");
                        if (ii == adr.Length - 1)
                        {
                            adr = adr.Replace(" ", "");
                        }
                        if (ii < adr.Length - 1 && ii != -1)
                        {
                            //  adr = adr.Replace(" ", "");
                            adr = adr.Replace(",", "");
                            string s1 = adr.Remove(ii);
                            s1 = s1.Replace(",", "");
                            s1 = s1.Replace(" ", "");

                            string s2 = adr.Remove(0, ii);
                            s2 = s2.Replace(",", "");

                            s2 = s2.Replace(" ", "");

                            adr = s1 + " " + s2;
                        }

                        string adr2 = excel[i][1].ToString();
                        adr += " " + adr2;                                              //сохраняем в формате [ХХХХ 123]
                        adr  = adr.ToUpper();
                        adr  = adr.Replace(",", "").Replace(" ", "").Replace("A", "А"); //Английскую в русскую А

                        int AdrId = 0;
                        try
                        {
                            AdrId = db.Adres.Where(x => x.Adress.Equals(adr)).Select(y => y.Id).First();//сохранили адрес
                        }
                        catch {
                            continue;
                        }//если адрес не нашли то пропустим данный шаг в цикле
                        string Adr = "";
                        if (AdrId != 0 && ploshad != 0)
                        {
                            Adres A = db.Adres.Where(x => x.Id == AdrId).First();
                            A.Ploshad = ploshad;
                            if (teplota12 != 0)
                            {
                                A.Teplota12 = teplota12;
                            }
                            db.Entry(A).State = EntityState.Modified;
                            db.SaveChanges();
                            Adr = A.Adress;
                        }

                        Ar.AdresId = AdrId;//пишем в адрес
                        Ar.Date    = Date;
                        int j = i + 1;

                        while (j < excel.Count && excel[j][1] == "0")
                        {
                            try { Ar.Name = excel[j][0]; } catch {
                            }
                            try { Ar.Teplota = Convert.ToDecimal(excel[j][2]); } catch {
                            }
                            try { Ar.Ploshad = Convert.ToDecimal(excel[j][3]); } catch {
                            }
                            try { Ar.Teplota12 = Convert.ToDecimal(excel[j][4]); } catch {
                            }
                            try { Ar.HotWater = Convert.ToDecimal(excel[j][5]); } catch {
                            }
                            try { Ar.ColdWater = Convert.ToDecimal(excel[j][6]); } catch {
                            }
                            db.Arendators.Add(Ar);
                            db.SaveChanges();
                            AR.Add(Adr + ";" + Ar.Name + ";" + Ar.HotWater);
                            j++;
                        }

                        i = j - 1;
                    }
                    procount++;
                    progress = Convert.ToInt16(i / pro100 * 100);
                    if (procount > pro100)
                    {
                        procount = Convert.ToInt32(pro100);
                    }
                    ProgressHub.SendMessage("Обрабатываем файл аренды...", progress);
                }



                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");

                    if (!JQ)
                    {
                        return(View("NotUpload"));
                    }
                    else
                    {
                        return(Json(Error));
                    }
                }
                else
                {
                    pro100 = excel.Count;
                    Arendator    ArendatorKA = new Arendator();
                    List <Adres> Adresa      = db.Adres.ToList();// грузим все адреса из БД

                    List <TableService>   TSdb     = db.TableServices.ToList();
                    List <List <string> > Services = new List <List <string> >();
                    //один раз преобразуем таблицу сервисов для сравнения чтоб в цикле не вызывать
                    int ser = 0;
                    foreach (TableService T in TSdb)
                    {
                        T.Type = T.Type.Replace(" ", "").ToUpper();
                        Services.Add(new List <string>());
                        Services[ser].Add(T.Type);//для проверки сохраняем
                        ser++;
                    }
                    //для каждой строки в экселе

                    List <string> Adr = Adresa.Select(x => x.Adress).ToList();
                    for (int a = 0; a < Adr.Count; a++)
                    {
                        Adr[a] = Adr[a].Replace(" ", "").ToUpper();
                    }


                    ViewBag.VsegoServices = TSdb.Count;
                    ViewBag.Services      = Services;
                    ViewBag.date          = Date;
                    ViewBag.file          = fileName;
                    ViewBag.AR            = AR;


                    if (!JQ)
                    {
                        return(View("UploadComplete"));
                    }
                    else
                    {
                        return(Json("Ошибок загрузки нет!"));
                    }
                }
            }
            if (!JQ)
            {
                return(RedirectToAction("NotUpload"));
            }
            else
            {
                return(Json("Файл не выбран или неверный формат файла."));
            }
        }
Exemplo n.º 6
0
        public ActionResult Upload(HttpPostedFileBase upload)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                //обрабатываем файл после загрузки



                string[] Names = new string[] { "Adres", "Code" };
                string   Error = "";
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error);
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    return(View("NotUpload"));
                }
                else
                {
                    pro100   = excel.Count;
                    procount = 0;
                    List <Adres> Adresdb = db.Adres.ToList();
                    foreach (List <string> e in excel)
                    {
                        string E = e[0].Replace(" ", "");
                        foreach (Adres A in Adresdb)
                        {
                            if (E.Equals(A.Adress.Replace(" ", "")))
                            {//модифицируем записи в ДБ
                                A.UEV             = Convert.ToInt16(e[1]);
                                db.Entry(A).State = EntityState.Modified;
                                db.SaveChanges();
                                break;
                            }
                        }
                        procount++;
                        progress = Convert.ToInt16(50 + procount / pro100 * 50);
                        ProgressHub.SendMessage("Обрабатываем файл, подождите чуток ...", progress);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                    }
                }
            }
            return(View("UploadComplete"));
        }
Exemplo n.º 7
0
        public ActionResult ActivePloshadUpload(HttpPostedFileBase upload)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = System.IO.Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                //обрабатываем файл после загрузки


                // 0       1         2      3                      4         5            6                       7                8                      9                                 10                                            11                      12               13             14                       15                      16
                string[] Names = new string[] { "№п.п.", "Адрес", "Дом", "Итогожилая+нежилая", "Этажей", "Подъездов", "Количествоквартир", "Количестволифтов", "Количествопроживающих", "Общаяплощадьквартир", "Нежилаяплощадьквартир,собственниковпобазеОРС", "Площадьподвала", "Площадьлестничныхклеток", "Площадькровли", "Площадьмусорокамер", "Площадьземельногоучастка", "Подрядчик" };
                string   Error = "";
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error);
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    return(View("NotUpload"));
                }
                else
                {
                    pro100   = excel.Count;
                    procount = 0;
                    List <Adres> Adresdb = db.Adres.ToList();
                    foreach (List <string> e in excel)
                    {
                        string E = e[1].Replace("ул.", "").ToUpper().Replace(" ", "").Replace("ПРОСПЕКТ", "").Replace("ПРОЕЗД", "").Replace("БУЛЬВАР", "").Replace(".", "");
                        string D = e[2].Replace(" ", "");
                        E = E + D;
                        Adres A = null;

                        //чистим от пр ул и т.д.
                        try
                        {
                            A = Adresdb.Where(x => x.Adress.Equals(E)).First();
                            try
                            {
                                A.ActivePloshad = Convert.ToDecimal(e[3]);
                                A.Etagi         = Convert.ToInt16(e[4]);
                                A.Podezds       = Convert.ToInt16(e[5]);
                                A.Kvartirs      = Convert.ToInt16(e[6]);
                                A.Lifts         = Convert.ToInt16(e[7]);
                                A.Peoples       = Convert.ToInt16(e[8]);

                                A.PloshadGilaya   = Convert.ToDecimal(e[9]);
                                A.PloshadNegilaya = Convert.ToDecimal(e[10]);
                                A.PloshadPodval   = Convert.ToDecimal(e[11]);
                                A.PloshadLestnica = Convert.ToDecimal(e[12]);
                                A.PloshadKrovlya  = Convert.ToDecimal(e[13]);
                                A.PloshadMusor    = Convert.ToDecimal(e[14]);
                                A.PloshadZemlya   = Convert.ToDecimal(e[15]);
                                A.IP = e[16];
                            }
                            catch (Exception exx)
                            {
                            }

                            db.Entry(A).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                        }

                        procount++;
                        progress = Convert.ToInt16(50 + procount / pro100 * 50);
                        ProgressHub.SendMessage("Обрабатываем файл, подождите чуток ...", progress);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                    }
                }
            }
            return(View("UploadComplete"));
        }
Exemplo n.º 8
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date, bool JQ = false)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            if (upload != null)
            {
                HttpCookie cookie = new HttpCookie("My localhost cookie");

                //найдем старые данные за этот месяц и заменим их не щадя
                List <UEV> dbUEV = db.UEVs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();

                pro100 = dbUEV.Count;
                foreach (UEV S in dbUEV)
                {
                    try
                    {
                        db.UEVs.Remove(S);
                        db.SaveChanges();
                        procount++;
                        progress = Convert.ToInt16(procount / pro100 * 100);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                        ProgressHub.SendMessage("Удаляем старые данные...", progress);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }
                upload.SaveAs(Server.MapPath("~/Files/" + fileName));

                //обрабатываем файл после загрузки

                string[] Names = new string[] { "Kp", "№прибора", "Тариф", "Общийотпуск", "ИтогосуммасНДСруб.", "Тариф", "Общийотпуск", "ИтогосуммасНДСруб.", "Тариф", "Общийотпуск", "ИтогосуммасНДСруб." };
                string   Error = "";
                List <List <string> > excel       = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error);
                List <string>         Errors      = new List <string>();
                List <string>         SmallErrors = new List <string>();
                List <string>         Codes       = new List <string>(); //коды УЭВ все построчно для сверки с таблицей
                List <string>         Teplos      = new List <string>(); //рубли тепло
                List <string>         HWs         = new List <string>(); //рубли гв
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    return(View("NotUpload"));
                }
                else
                {
                    procount = 0;
                    pro100   = excel.Count;
                    UEV          UEVKA  = new UEV();
                    List <Adres> Adresa = db.Adres.ToList();// грузим все адреса из БД


                    //для каждой строки в экселе
                    foreach (List <string> L in excel)
                    {
                        bool EstName = false;
                        int  CodUEV  = 0;
                        Codes.Add(L[0]);
                        Teplos.Add(L[4]);
                        HWs.Add(L[7]);
                        try
                        {
                            CodUEV = Convert.ToInt32(L[0]);
                        }
                        catch
                        {
                            SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Ошибка конвертации кода");
                        }
                        if (CodUEV != 0)
                        {
                            foreach (Adres A in Adresa)
                            {
                                if (A.UEV == CodUEV)
                                {
                                    //если в массиве адресов есть адрес из строчки то сохраняем айдишник
                                    EstName       = true;
                                    UEVKA.AdresId = A.Id;
                                    UEVKA.KodUEV  = A.UEV;
                                    UEVKA.Date    = Date;
                                    UEVKA.Name    = "";
                                    break;
                                }
                            }
                            //если имени нет в списке то и сохранять не будем
                            if (EstName)
                            {
                                int     Pribor       = 0;
                                decimal OtEnergyGkal = 0;
                                decimal OtEnergyRub  = 0;
                                decimal HwEnergyGkal = 0;
                                decimal HwEnergyRub  = 0;
                                decimal HwVodaM3     = 0;
                                decimal HwVodaRub    = 0;
                                try
                                {
                                    Pribor = Convert.ToInt32(L[1]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в инт " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется ПУ");
                                }
                                try
                                {
                                    OtEnergyGkal = Convert.ToDecimal(L[3]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется отопление энергия объём");
                                }
                                try
                                {
                                    OtEnergyRub = Convert.ToDecimal(L[4]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется отопление энергия руб.");
                                }
                                try
                                {
                                    HwEnergyGkal = Convert.ToDecimal(L[6]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется ГВ энергия");
                                }
                                try
                                {
                                    HwEnergyRub = Convert.ToDecimal(L[7]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется ГВ энергия руб");
                                }
                                try
                                {
                                    HwVodaM3 = Convert.ToDecimal(L[9]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется ГВ объём");
                                }
                                try
                                {
                                    HwVodaRub = Convert.ToDecimal(L[10]);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Не преобразуется в децимал " + UEVKA.AdresId + " " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не преобразуется ГВ руб");
                                }
                                UEVKA.Pribor       = Pribor;
                                UEVKA.OtEnergyGkal = OtEnergyGkal;
                                UEVKA.OtEnergyRub  = OtEnergyRub;
                                UEVKA.HwEnergyGkal = HwEnergyGkal;
                                UEVKA.HwEnergyRub  = HwEnergyRub;
                                UEVKA.HwVodaM3     = HwVodaM3;
                                UEVKA.HwVodaRub    = HwVodaRub;


                                try
                                {
                                    db.UEVs.Add(UEVKA);
                                    db.SaveChanges();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                    SmallErrors.Add(L[0] + ";" + L[1] + ";" + L[2] + " Не смогли сохранить в БД адрес ИД=" + UEVKA.AdresId);
                                }
                            }
                            else
                            {//если имени нет в списке, значит нужно вывести предупреждение чтобы часами не искать
                                if (CodUEV != 0)
                                {
                                    if (Errors.Count == 0)
                                    {
                                        Errors.Add("Найдены коды, отсутствующие в БД!");
                                    }
                                    Errors.Add("Код=" + CodUEV.ToString() + " не найден в БД.");
                                }
                            }
                        }
                        procount++;
                        progress = Convert.ToInt16(50 + procount / pro100 * 50);
                        ProgressHub.SendMessage("Обрабатываем файл УЭВ...", progress);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                    }
                    List <string> Adr = Adresa.Select(x => x.Adress).ToList();
                    for (int a = 0; a < Adr.Count; a++)
                    {
                        Adr[a] = Adr[a].Replace(" ", "").ToUpper();
                    }

                    if (Errors.Count == 0)
                    {
                        Errors.Add("Ошибок загрузки нет!");
                    }
                    ViewBag.VsegoUEV = db.UEVs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).Count();
                    //ViewBag.Services = Services;
                    ViewBag.UEV         = db.UEVs.Where(x => x.Date == Date).Include(z => z.Adres.Adress).Select(y => y.Adres.Adress + "ОТ(энергия руб.)=" + y.OtEnergyRub + " ГВ(энергия руб.)=" + y.HwEnergyRub + "ГВ(теплоноситель руб.)=" + y.HwVodaRub).ToList();
                    ViewBag.date        = Date;
                    ViewBag.file        = fileName;
                    ViewBag.Gkal        = db.UEVs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).Sum(y => y.OtEnergyGkal);
                    ViewBag.M3Water     = db.UEVs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).Sum(y => y.HwVodaM3);
                    ViewBag.GkalWater   = db.UEVs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).Sum(y => y.HwEnergyGkal);
                    ViewBag.Errors      = Errors;
                    ViewBag.Codes       = Codes;
                    ViewBag.HWs         = HWs;
                    ViewBag.Teplos      = Teplos;
                    ViewBag.SmallErrors = SmallErrors;
                    if (JQ == false)
                    {
                        return(View("UploadComplete"));
                    }
                    else
                    {
                        Errors.Add(Error);
                        return(Json(Errors));
                    }
                }
            }
            if (!JQ)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(Json("Файл не выбран! Выберните файл EXCEL формата XLS или XLSX НЕ CSV!!!"));
            }
        }
Exemplo n.º 9
0
        public ActionResult Upload(HttpPostedFileBase upload, DateTime Date)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            Date = new DateTime(Date.Year, Date.Month, 1);
            if (upload != null)
            {
                HttpCookie cookie = new HttpCookie("My localhost cookie");

                //найдем старые данные за этот месяц и заменим их не щадя
                List <DOMFundament> dbFundaments = db.DOMFundaments.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();

                int tek = 0;
                foreach (DOMFundament S in dbFundaments)
                {
                    try
                    {
                        db.DOMFundaments.Remove(S);
                        db.SaveChanges();
                        otklik(dbFundaments.Count, ref tek, "удаляем старые данные фундамента...");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                List <DOMRoof> dbRoofs = db.DOMRoofs.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();

                tek = 0;
                foreach (DOMRoof S in dbRoofs)
                {
                    try
                    {
                        db.DOMRoofs.Remove(S);
                        db.SaveChanges();
                        otklik(dbRoofs.Count, ref tek, "удаляем старые данные крыш...");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                List <DOMFasad> dbFasads = db.DOMFasads.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();
                tek = 0;
                foreach (DOMFasad S in dbFasads)
                {
                    try
                    {
                        db.DOMFasads.Remove(S);
                        db.SaveChanges();
                        otklik(dbRoofs.Count, ref tek, "удаляем старые данные фасадов...");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                List <DOMRoom> dbRooms = db.DOMRooms.Where(x => x.Date.Year == Date.Year && x.Date.Month == Date.Month).ToList();
                tek = 0;
                foreach (DOMRoom S in dbRooms)
                {
                    try
                    {
                        db.DOMRooms.Remove(S);
                        db.SaveChanges();
                        otklik(dbRoofs.Count, ref tek, "удаляем старые данные внутридомовых элементов...");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }


                // Установить значения в нем
                cookie["Download"] = "0";
                // Добавить куки в ответ
                Response.Cookies.Add(cookie);



                //call this method inside your working action
                ProgressHub.SendMessage("Инициализация и подготовка...", 0);

                // получаем имя файла
                string fileName = Path.GetFileName(upload.FileName);
                // сохраняем файл в папку Files в проекте
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }

                upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                //обрабатываем файл после загрузки


                //0адрес        1площадь_отмостки     2материал_фундамента    3тип_фундамента        4Кап_Ремонт_кровли        5Утеплитель          6ФормаКрыши      7КапРемонтНесущейЧасти    8ВидНесущейЧасти         9 ТипКровли       10 Износ фасада     11 Год ремонта фасада  12 Материал отделки фасада  13 Тип фасада      14 Утепление фасада  15 Балконы, лоджии 16 Количество балконов 17 Количество лоджий 18Тип внутренних стен 19Перекрытия                 20 Окна               21 Двери
                string[] Names = new string[] { "HOME_ADDRESS", "MKDSPECIFIED_14581", "MKDSPECIFIED_15016_1", "MKDSPECIFIED_13516_1", "MKDSPECIFIED_20083", "MKDSPECIFIED_15246_1", "MKDSPECIFIED_12179_1", "MKDSPECIFIED_20078", "MKDSPECIFIED_20152_1", "MKDSPECIFIED_12185_1", "MKDSPECIFIED_20072", "MKDSPECIFIED_20073", "MKDSPECIFIED_13049_1", "MKDSPECIFIED_14549_1", "MKDSPECIFIED_14011_1", "MKDSPECIFIED_20120", "MKDSPECIFIED_11556", "MKDSPECIFIED_13056", "MKDSPECIFIED_16590_1", "MKDSPECIFIED_15087_1", "MKDSPECIFIED_13059_1", "MKDSPECIFIED_12139_1" };
                string   Error = "";
                List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, "КонстЭлемОЖФ");
                if (excel.Count < 1)
                {
                    //если нифига не загрузилось то
                    ViewBag.Error = Error;
                    ViewBag.Names = Names;
                    Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                    return(View("NotUpload"));
                }
                else
                {
                    pro100 = excel.Count;
                    DOMFundament             Fundament     = new DOMFundament();
                    DOMRoof                  Roof          = new DOMRoof();
                    DOMFasad                 Fasad         = new DOMFasad();
                    DOMRoom                  Room          = new DOMRoom();
                    List <Adres>             Adresa        = db.Adres.ToList();// грузим все адреса из БД
                    List <FundamentMaterial> FundamentMat  = db.FundamentMaterials.ToList();
                    List <FundamentType>     FundamentType = db.FundamentTypes.ToList();
                    List <RoofType>          RT            = db.RoofTypes.ToList();
                    List <RoofForm>          RF            = db.RoofForms.ToList();
                    List <RoofVid>           RV            = db.RoofVids.ToList();
                    List <RoofUteplenie>     RU            = db.RoofUteplenies.ToList();
                    List <string>            save          = new List <string>();
                    List <string>            errors        = new List <string>();
                    List <string>            saveR         = new List <string>();
                    List <string>            errorsR       = new List <string>();
                    List <string>            saveRoom      = new List <string>();
                    List <string>            errorsRoom    = new List <string>();
                    List <string>            saveF         = new List <string>();
                    List <string>            errorsF       = new List <string>();


                    //для каждой строки в экселе
                    foreach (List <string> L in excel)
                    {
                        string adr = zachistkaAdresa(L[0]);
                        //сверяем улицу
                        bool go = false;
                        foreach (Adres A in Adresa)
                        {
                            if (A.Adress.Equals(adr))
                            {
                                //если улица совпала то сохраняем айдишник
                                Fundament.AdresId = A.Id;
                                Roof.AdresId      = A.Id;
                                Fasad.AdresId     = A.Id;
                                Room.AdresId      = A.Id;
                                go = true;
                                break;
                            }
                        }
                        //если нашли адрес то сохраняем все остальные данные

                        if (go)
                        {
                            Fundament.Date = Date;
                            //ищем материал
                            Fundament.MaterialId = 1;//если не найдет
                            Fundament.Ploshad    = Convert.ToDecimal(L[1]);

                            foreach (FundamentMaterial FM in FundamentMat)
                            {
                                if (FM.Material.Replace(" ", "").Equals(L[2].Replace(" ", "")))
                                {
                                    Fundament.MaterialId = FM.Id;
                                    break;
                                }
                            }
                            //ищем тип фундамента
                            Fundament.TypeId = 1;//если не найдет
                            foreach (FundamentType FT in FundamentType)
                            {
                                if (FT.Type.Replace(" ", "").Equals(L[3].Replace(" ", "")))
                                {
                                    Fundament.TypeId = FT.Id;
                                    break;
                                }
                            }

                            //сохраняем фундамент
                            if (Fundament.TypeId != 1 && Fundament.MaterialId != 1)
                            {
                                try
                                {
                                    db.DOMFundaments.Add(Fundament);
                                    db.SaveChanges();
                                    save.Add(L[0]);
                                }
                                catch (Exception e)
                                {
                                    errors.Add(L[0] + "(ошибка сохранения)");
                                }
                            }
                            else
                            {
                                errors.Add(L[0] + "(нулевые данные)");
                            }


                            //теперь ищем крыши
                            Roof.Date = Date;


                            Roof.Ploshad     = 0;
                            Roof.YearKrovlya = Convert.ToInt16(L[4]);
                            Roof.Year        = Convert.ToInt16(L[7]);
                            //Тип крыши
                            Roof.TypeId = 1;//если не найдет
                            foreach (RoofType R in RT)
                            {
                                if (R.Type.Replace(" ", "").Equals(L[9].Replace(" ", "")))
                                {
                                    Roof.TypeId = R.Id;
                                    break;
                                }
                            }
                            //Вид крыши
                            Roof.VidId = 1;//если не найдет
                            foreach (RoofVid R in RV)
                            {
                                if (R.Vid.Replace(" ", "").Equals(L[8].Replace(" ", "")))
                                {
                                    Roof.VidId = R.Id;
                                    break;
                                }
                            }
                            //Форма крыши
                            Roof.FormId = 1;//если не найдет
                            foreach (RoofForm R in RF)
                            {
                                if (R.Form.Replace(" ", "").Equals(L[6].Replace(" ", "")))
                                {
                                    Roof.FormId = R.Id;
                                    break;
                                }
                            }
                            //Утепление крыши
                            Roof.UteplenieId = 1;//если не найдет
                            foreach (RoofUteplenie R in RU)
                            {
                                if (R.Uteplenie.Replace(" ", "").Equals(L[5].Replace(" ", "")))
                                {
                                    Roof.UteplenieId = R.Id;
                                    break;
                                }
                            }

                            //если данные по крышам не нулевые то сохраняем
                            if (Roof.UteplenieId + Roof.TypeId + Roof.VidId + Roof.FormId > 4)
                            {
                                try
                                {
                                    db.DOMRoofs.Add(Roof);
                                    db.SaveChanges();
                                    saveR.Add(L[0]);
                                }
                                catch (Exception e)
                                {
                                    db.DOMRoofs.Remove(Roof);
                                    errorsR.Add(L[0] + "(ошибка сохранения)");
                                }
                            }
                            else
                            {
                                errorsR.Add(L[0] + "(нулевые данные)");
                            }
                            // Теперь ищем фасады 10 Износ фасада     11 Год ремонта фасада  12 Материал отделки фасада  13 Тип фасада      14 Утепление фасада
                            Fasad.Date       = Date;
                            Fasad.Iznos      = Convert.ToInt16(L[10]);
                            Fasad.Year       = Convert.ToInt16(L[11]);
                            Fasad.MaterialId = 1;
                            try
                            {
                                foreach (FasadMaterial F in db.FasadMaterials)
                                {
                                    if (F.Material.Replace(" ", "").ToUpper().Equals(L[12].Replace(" ", "").ToUpper()))
                                    {
                                        Fasad.MaterialId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            Fasad.UteplenieId = 1;
                            try
                            {
                                foreach (FasadUteplenie F in db.FasadUteplenies)
                                {
                                    if (F.Uteplenie.Replace(" ", "").ToUpper().Equals(L[14].Replace(" ", "").ToUpper()))
                                    {
                                        Fasad.UteplenieId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            Fasad.TypeId = 1;
                            try
                            {
                                foreach (FasadType F in db.FasadTypes)
                                {
                                    if (F.Type.Replace(" ", "").ToUpper().Equals(L[13].Replace(" ", "").ToUpper()))
                                    {
                                        Fasad.TypeId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            if (Fasad.UteplenieId + Fasad.TypeId + Fasad.MaterialId > 3)
                            {
                                try
                                {
                                    db.DOMFasads.Add(Fasad);
                                    db.SaveChanges();
                                    saveF.Add(L[0]);
                                }
                                catch (Exception e)
                                {
                                    db.DOMFasads.Remove(Fasad);
                                    errorsF.Add(L[0] + "(ошибка сохранения)");
                                }
                            }
                            else
                            {
                                errorsF.Add(L[0] + "(нулевые данные)");
                            }

                            //Теперь внутренности помещений 16 Количество балконов 17 Количество лоджий 18Тип внутренних стен 19Перекрытия 20 Окна 21 Двери
                            Room.Date   = Date;
                            Room.Lodgi  = Convert.ToInt16(L[17]);
                            Room.Balkon = Convert.ToInt16(L[16]);
                            Room.TypeId = 1;
                            try
                            {
                                foreach (RoomType F in db.RoomTypes)
                                {
                                    if (F.Type.Replace(" ", "").ToUpper().Equals(L[18].Replace(" ", "").ToUpper()))
                                    {
                                        Room.TypeId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            Room.WindowId = 1;
                            try
                            {
                                foreach (RoomWindow F in db.RoomWindows)
                                {
                                    if (F.Window.Replace(" ", "").ToUpper().Equals(L[20].Replace(" ", "").ToUpper()))
                                    {
                                        Room.WindowId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            Room.OverlapId = 1;
                            try
                            {
                                foreach (RoomOverlap F in db.RoomOverlaps)
                                {
                                    if (F.Overlap.Replace(" ", "").ToUpper().Equals(L[19].Replace(" ", "").ToUpper()))
                                    {
                                        Room.TypeId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            Room.DoorId = 1;
                            try
                            {
                                foreach (RoomDoor F in db.RoomDoors)
                                {
                                    if (F.Door.Replace(" ", "").ToUpper().Equals(L[21].Replace(" ", "").ToUpper()))
                                    {
                                        Room.DoorId = F.Id;
                                        break;
                                    }
                                }
                            }
                            catch { }
                            if (Room.DoorId + Room.TypeId + Room.OverlapId + Room.WindowId > 4)
                            {
                                try
                                {
                                    db.DOMRooms.Add(Room);
                                    db.SaveChanges();
                                    saveRoom.Add(L[0]);
                                }
                                catch (Exception e)
                                {
                                    db.DOMRooms.Remove(Room);
                                    errorsRoom.Add(L[0] + "(ошибка сохранения)");
                                }
                            }
                            else
                            {
                                errorsRoom.Add(L[0] + "(нулевые данные)");
                            }
                        }
                        else
                        {
                            errors.Add(L[0]);
                        }

                        procount++;
                        progress = Convert.ToInt16(50 + procount / pro100 * 50);
                        ProgressHub.SendMessage("Обрабатываем файл ГИС ЖКХ...", progress);
                        if (procount > pro100)
                        {
                            procount = Convert.ToInt32(pro100);
                        }
                    }

                    ViewBag.Save       = save;
                    ViewBag.Errors     = errors;
                    ViewBag.SaveR      = saveR;
                    ViewBag.ErrorsR    = errorsR;
                    ViewBag.SaveRoom   = saveRoom;
                    ViewBag.ErrorsRoom = errorsRoom;
                    ViewBag.SaveF      = saveF;
                    ViewBag.ErrorsF    = errorsF;


                    ViewBag.date = Date;
                    ViewBag.file = fileName;

                    //Грузим 2 часть файла!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                    upload.SaveAs(Server.MapPath("~/Files/" + fileName));
                    //обрабатываем файл после загрузки


                    //0адрес          1Износ ГВ         2материал ХВ              3Износ ХВ            4Материал ГВ             5Материал стояков    6КоличествоЭлектровводов  7МатериалВодоотведения  8Год кап. рем. водоотвед.  9Кап. рем. электро.  10Кап. рем. ХВ.   11Кап.рем.ГВ    12Износ отопл. 13Количество вводов отопления. 14.Материал отопления1 15.Материал отопления2  16.Материал труб отопления 17.Износ электро 18.Износ водоотвод
                    Names = new string[] { "HOME_ADDRESS", "MKDSPECIFIED_20114", "MKDSPECIFIED_14778_1", "MKDSPECIFIED_20107", "MKDSPECIFIED_12023_1", "MKDSPECIFIED_12060_1", "MKDSPECIFIED_12545", "MKDSPECIFIED_13412_1", "MKDSPECIFIED_20143", "MKDSPECIFIED_20122", "MKDSPECIFIED_20105", "MKDSPECIFIED_20112", "MKDSPECIFIED_20096", "MKDSPECIFIED_12035", "MKDSPECIFIED_14721_1", "MKDSPECIFIED_14721_2", "MKDSPECIFIED_15055_1", "MKDSPECIFIED_21834", "MKDSPECIFIED_21833" };
                    Error = "";
                    excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error, "ВнутрСистемыОЖФ");
                    if (excel.Count < 1)
                    {
                        //если нифига не загрузилось то
                        ViewBag.Error = Error;
                        ViewBag.Names = Names;
                        Console.WriteLine("Пустой массив значит файл не загрузился!(он уже удалился)");
                        return(View("NotUpload"));
                    }
                    else
                    {
                        DOMOtoplenie Otoplenie = new DOMOtoplenie();
                        DOMVodootvod Vodootvod = new DOMVodootvod();
                        DOMHW        HW        = new DOMHW();
                        DOMCW        CW        = new DOMCW();
                        DOMElectro   Electro   = new DOMElectro();

                        pro100 = excel.Count;
                        Material Material = new Material();

                        Adresa = db.Adres.ToList(); // грузим все адреса из БД
                                                    // List<Material> Materials = db.Materials.ToList();

                        //для каждой строки в экселе
                        foreach (List <string> L in excel)
                        {
                            string adr = zachistkaAdresa(L[0]);
                            //сверяем улицу

                            foreach (Adres A in Adresa)
                            {
                                if (A.Adress.Equals(adr))
                                {
                                    //если улица совпала то сохраняем айдишник
                                    bool s = false;
                                    try
                                    {
                                        Otoplenie = db.DOMOtoplenies.Where(x => x.AdresId == A.Id && x.Date.Year == Date.Year && x.Date.Month == Date.Month).First();
                                        s         = true;
                                    }
                                    catch { }
                                    Otoplenie.AdresId            = A.Id;
                                    Otoplenie.IznosOtop          = Convert.ToInt32(L[12]);
                                    Otoplenie.VvodsOtop          = Convert.ToInt32(L[13]);
                                    Otoplenie.MaterialOtop1Id    = PoiskMateriala(L[14].ToString());
                                    Otoplenie.MaterialOtop2Id    = PoiskMateriala(L[15].ToString());
                                    Otoplenie.MaterialOtopTrubId = PoiskMateriala(L[16].ToString());
                                    Otoplenie.MaterialTeploId    = PoiskMateriala(L[5].ToString());
                                    Otoplenie.Date = Date;
                                    if (s)
                                    {
                                        db.Entry(Otoplenie).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        db.DOMOtoplenies.Add(Otoplenie);
                                        db.SaveChanges();
                                    }


                                    s = false;
                                    try
                                    {
                                        Vodootvod = db.DOMVodootvods.Where(x => x.AdresId == A.Id && x.Date.Year == Date.Year && x.Date.Month == Date.Month).First();
                                        s         = true;
                                    }
                                    catch { }

                                    Vodootvod.AdresId    = A.Id;
                                    Vodootvod.Iznos      = Convert.ToInt32(L[18]);
                                    Vodootvod.MaterialId = PoiskMateriala(L[7].ToString());
                                    Vodootvod.Remont     = Convert.ToInt32(L[8]);
                                    Vodootvod.Date       = Date;
                                    if (s)
                                    {
                                        db.Entry(Vodootvod).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        db.DOMVodootvods.Add(Vodootvod);
                                        db.SaveChanges();
                                    }

                                    s = false;
                                    try
                                    {
                                        HW = db.DOMHWs.Where(x => x.AdresId == A.Id && x.Date.Year == Date.Year && x.Date.Month == Date.Month).First();
                                        s  = true;
                                    }
                                    catch { }


                                    HW.AdresId      = A.Id;
                                    HW.IznosHW      = Convert.ToInt32(L[1]);
                                    HW.MaterialHWId = PoiskMateriala(L[4].ToString());
                                    HW.RemontHW     = Convert.ToInt32(L[11]);
                                    HW.Date         = Date;
                                    if (s)
                                    {
                                        db.Entry(HW).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        db.DOMHWs.Add(HW);
                                        db.SaveChanges();
                                    }

                                    s = false;
                                    try
                                    {
                                        CW = db.DOMCWs.Where(x => x.AdresId == A.Id && x.Date.Year == Date.Year && x.Date.Month == Date.Month).First();
                                        s  = true;
                                    }
                                    catch { }

                                    CW.AdresId      = A.Id;
                                    CW.IznosCW      = Convert.ToInt32(L[3]);
                                    CW.MaterialCWId = PoiskMateriala(L[2].ToString());
                                    CW.RemontCW     = Convert.ToInt32(L[10]);
                                    CW.Date         = Date;
                                    if (s)
                                    {
                                        db.Entry(CW).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        db.DOMCWs.Add(CW);
                                        db.SaveChanges();
                                    }


                                    s = false;
                                    try
                                    {
                                        Electro = db.DOMElectroes.Where(x => x.AdresId == A.Id && x.Date.Year == Date.Year && x.Date.Month == Date.Month).First();
                                        s       = true;
                                    }
                                    catch { }
                                    Electro.AdresId       = A.Id;
                                    Electro.Electrovvods  = Convert.ToInt32(L[6]);
                                    Electro.IznosElectro  = Convert.ToInt32(L[17]);
                                    Electro.RemontElectro = Convert.ToInt32(L[9]);
                                    Electro.Date          = Date;


                                    if (s)
                                    {
                                        db.Entry(Electro).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        db.DOMElectroes.Add(Electro);
                                        db.SaveChanges();
                                    }
                                    break;
                                }
                            }
                            //если нашли адрес то сохраняем все остальные данные
                        }
                        return(View("UploadComplete"));
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 10
0
        public ActionResult Upload(HttpPostedFileBase upload, HttpPostedFileBase upload2)
        {
            Excel.Application ApExcel = new Excel.Application();
            Excel.Workbooks   WB      = null;
            WB = ApExcel.Workbooks;
            Excel.Workbook WbExcel = ApExcel.Workbooks.Add(System.Reflection.Missing.Value);
            List <Element> Defects = new List <Element>();
            // получаем имя файла
            string fileName  = Path.GetFileName(upload.FileName);
            string fileName2 = Path.GetFileName(upload2.FileName);

            // сохраняем файл в папку Files в проекте
            if (Directory.Exists(Server.MapPath("~/Files/")) == false)
            {
                Directory.CreateDirectory(Server.MapPath("~/Files/"));
            }
            upload.SaveAs(Server.MapPath("~/Files/" + fileName));
            upload2.SaveAs(Server.MapPath("~/Files/" + fileName2));

            //обрабатываем файл после загрузки
            //Загружаем файл ТБО
            string[] Names = new string[] { "Id", "Element" };
            string   Error = "";
            List <List <string> > excel = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName), Names, out Error);

            //Загружаем файл наших выездов
            string[] Names2 = new string[] { "ElementId", "Description", "Location", "DeffDesc" };
            string   Error2 = "";
            List <List <string> > excel2 = ExcelSVNUpload.IMPORT(Server.MapPath("~/Files/" + fileName2), Names2, out Error2);
            List <Musor>          Result = new List <Musor>();
            int elId = 0;

            if (excel.Count < 1 || excel2.Count < 1)
            {
                //если нифига не загрузилось то
                ViewBag.Error = Error + Error2;
                ViewBag.Names = Names;
                return(View("NotUpload"));
            }
            else
            {
                try
                {
                    List <Defect> Def = db.Defects.ToList();
                    if (Def.Count > 0)
                    {
                        foreach (Defect D in Def)
                        {
                            db.Defects.Remove(D);
                            db.SaveChanges();
                        }
                    }
                }
                catch { }
                try
                {
                    List <DefDescription> Def = db.DefDescriptions.ToList();
                    if (Def.Count > 0)
                    {
                        foreach (DefDescription D in Def)
                        {
                            db.DefDescriptions.Remove(D);
                            db.SaveChanges();
                        }
                    }
                }
                catch { }
                try
                {
                    List <DefWork> DefWorks = db.DefWorks.ToList();
                    if (DefWorks.Count > 0)
                    {
                        foreach (DefWork D in DefWorks)
                        {
                            db.DefWorks.Remove(D);
                            db.SaveChanges();
                        }
                    }
                }
                catch { }

                try
                {
                    List <Element> elem = db.Elements.ToList();
                    if (elem.Count > 0)
                    {
                        foreach (Element D in elem)
                        {
                            db.Elements.Remove(D);
                            db.SaveChanges();
                        }
                    }
                }
                catch { }

                for (int h = 1; h < excel.Count; h++)
                {
                    if (excel[h][1] != "NULL" && excel[h][1] != null && excel[h][1] != "")
                    {
                        Element E = new Element();
                        E.Name      = excel[h][1];
                        E.ElementId = Convert.ToInt32(excel[h][0]);
                        try
                        {
                            db.Elements.Add(E);
                            db.SaveChanges();
                        }
                        catch
                        {
                            db.Elements.Remove(E);
                        }
                    }
                }

                decimal pro100   = Convert.ToDecimal(excel2.Count);
                int     progress = 0;
                int     procount = 0;

                /*
                 * Excel.Range range;//рэндж
                 * ApExcel.Visible = false;//невидимо
                 * ApExcel.ScreenUpdating = false;//и не обновляемо
                 *
                 * //call this method inside your working action
                 * ProgressHub.SendMessage("Инициализация и подготовка...", 0);
                 * ApExcel.Visible = false;//невидимо
                 * ApExcel.ScreenUpdating = false;//и не обновляемо
                 */

                /*ApExcel.Worksheets.Add(Type.Missing);//Добавляем лист
                 * Excel.Worksheet WS = WbExcel.Sheets[1];
                 * try
                 * {
                 *  WS.Name = Defects[h].Element;
                 * }
                 * catch
                 * {
                 *  WS.Name = Defects[h].Element+h.ToString();
                 *
                 * }
                 */



                foreach (List <string> E in excel2)
                {
                    if (E[0] != null && E[0] != "")
                    {
                        int    id     = 0;
                        string E1     = E[1].ToLower().Replace(",", "").Replace(".", "").Replace("-", "");
                        string E3     = E[3].ToLower().Replace(",", "").Replace(".", "").Replace("-", "");
                        string E2     = E[2].ToLower().Replace(",", "").Replace(".", "").Replace("-", "");
                        Defect DEFECT = new Defect();
                        bool   go     = true;
                        try
                        {
                            id   = Convert.ToInt32(E[0]);
                            elId = db.Elements.Where(x => x.ElementId == id).Select(z => z.Id).First();
                        }
                        catch
                        {
                            go = false;
                        }
                        if (go)
                        {
                            List <Defect> D = new List <Defect>();



                            //если нет совпадений то ok
                            if (E1 != "" && E1 != "0" && E1 != "null")
                            {
                                DEFECT.Def       = E1;
                                DEFECT.ElementId = elId;

                                try
                                {
                                    db.Defects.Add(DEFECT);
                                    db.SaveChanges();
                                }
                                catch
                                {
                                    // db.DefDescriptions.Remove(DESC);
                                    // db.Defects.Remove(DEFECT);
                                }
                            }



                            //Работа
                            DefWork WORK = new DefWork();


                            //если нет совпадений то ok
                            if (E2 != "" && E2 != "0" && E2 != "null")
                            {
                                WORK.Work      = E2;
                                WORK.ElementId = elId;

                                try
                                {
                                    db.DefWorks.Add(WORK);
                                    db.SaveChanges();
                                }
                                catch
                                {
                                    // db.DefDescriptions.Remove(DESC);
                                    //db.DefWorks.Remove(WORK);
                                }
                            }
                            if (E3 != "" && E3 != "0" && E3 != "null")
                            {
                                WORK.Work      = E3;
                                WORK.ElementId = elId;

                                try
                                {
                                    db.DefWorks.Add(WORK);
                                    db.SaveChanges();
                                }
                                catch
                                {
                                    // db.DefDescriptions.Remove(DESC);
                                    // db.DefWorks.Remove(WORK);
                                }
                            }



                            //если нет совпадений то ok
                        }
                    }
                    procount++;
                    progress = Convert.ToInt16(50 + procount / pro100 * 50);
                    ProgressHub.SendMessage("Обрабатываем файл ...", progress);
                    if (procount > pro100)
                    {
                        procount = Convert.ToInt32(pro100);
                    }
                }
            }


            string patch    = Server.MapPath("~/Content/OtchetDefects.xlsx"); //@"C:\inetpub\Otchets\ASP" + "X" + Year.Remove(0, 2) + "X" + Month + ".xlsx";//Server.MapPath("~\\ASP" +"X"+ Year.Remove(0,2) +"X"+ Month + ".xlsx");
            string filename = "OtchetDefects.xlsx";
            string path2    = Url.Content("~/Content/OtchetDefects.xlsx");

            // RedirectToAction("DownloadPS", new {path,filename});
            string dat         = path2; //+ filename;
            string contentType = "application/vnd.ms-excel";

            //
            ViewBag.file = filename;
            ViewBag.dat  = dat;



            // Сохранение файла Excel.
            try
            {
                Opr.EstLiFile(patch);
                WbExcel.SaveCopyAs(patch);//сохраняем в папку
            }
            catch
            {
            }
            ApExcel.Visible        = true; //видимо
            ApExcel.ScreenUpdating = true; //и  обновляемо
            ApExcel.Quit();


            Marshal.FinalReleaseComObject(WbExcel);
            Marshal.FinalReleaseComObject(WB);



            GC.Collect();
            Marshal.FinalReleaseComObject(ApExcel);
            GC.WaitForPendingFinalizers();
            return(View("UploadComplete"));
        }