Пример #1
0
        public JsonResult NotifyAboutMissingEditionImages(string key, string connectionId)
        {
            if (key == WebConfigHelper.TaskSchedulerSecretKey)
            {
                try
                {
                    var editions = TaskServices.GetEditionsWithMissingImages();

                    var pattern = "<a href='{0}'>{1}</a>";

                    var body = "<table>";

                    for (var i = 0; i < editions.Count; i++)
                    {
                        var edition = editions[i];

                        var url = _editionHelper.GetEditionUrl(new EditionEntity
                        {
                            EditionId   = edition.EditionId,
                            EditionName = edition.EventName,
                            Status      = edition.Status.ToEnum <EditionStatusType>()
                        });

                        body += "<tr><td class='font-lato' style='font-size: 14px; color: #888794'>" + string.Format(pattern, url, edition.EventName);
                        body += edition.EventBackGroundImage == null ? " [People Image] " : "";
                        body += edition.EventImage == null ? " [Web Logo] " : "";
                        body += edition.IconFileName == null ? " [Icon] " : "";
                        body += edition.MasterLogoFileName == null ? " [Master Logo] " : "";
                        body += edition.ProductImageFileName == null ? " [Product Image] " : "";
                        body += "</td></tr>";

                        if (!string.IsNullOrWhiteSpace(connectionId))
                        {
                            ProgressHub.SendProgress(connectionId, "Detecting missing images...", i + 1, editions.Count, TaskType.NotifyAboutMissingEditionImages.GetHashCode());
                        }
                    }

                    body += "</table>";

                    var subject    = "Events with Missing Images";
                    var recipients = WebConfigHelper.MarketingAdminEmails;

                    _emailNotificationHelper.Send(NotificationType.MissingEditionImages, subject, body, recipients);

                    var log = CreateInternalLog("The task NotifyAboutMissingEditionImages completed.", AutoIntegrationUser);
                    ExternalLogHelper.Log(log, LoggingEventType.Information);

                    return(Json("", JsonRequestBehavior.AllowGet));
                }
                catch (Exception exc)
                {
                    var message = "The task NotifyAboutMissingEditionImages failed! " + exc.GetFullMessage();
                    ExternalLogHelper.Log(message, LoggingEventType.Error);

                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
            }

            return(Json(false, JsonRequestBehavior.AllowGet));
        }
Пример #2
0
        public async void ZapuskPoiska(List <List <string> > excel, DateTime Date, List <Adres> Adresa)
        {
            ProgressHub.SendMessage("Запускаем обработку файла ...", 0);
            await Task.Run(() => Poisk(excel, Date, Adresa));

            ProgressHub.SendMessage("Файл успешно обработан ...", 100);
        }
Пример #3
0
        public void UpdateApprovedEditionsFromStagingDb(string key, string connectionId)
        {
            if (key == WebConfigHelper.TaskSchedulerSecretKey)
            {
                try
                {
                    var approvedEditions = GetApprovedEditions();

                    var stagingEditions = GetStagingEditionsPossiblyHaveNewEditions(approvedEditions);

                    if (approvedEditions.Count > 0)
                    {
                        for (var i = 0; i < approvedEditions.Count; i++)
                        {
                            var approvedEdition = approvedEditions[i];

                            var siblingsOnCed = GetSiblingEditionsByApprovedEdition(approvedEdition);

                            var siblingsOnStaging = stagingEditions.Where(x => x.EventMasterCode == approvedEdition.Event.MasterCode).ToList();

                            if (siblingsOnStaging.Count == siblingsOnCed.Count)
                            {
                                var newlyAddedEdition = siblingsOnStaging.OrderByDescending(x => x.EventStartDate).Take(1).SingleOrDefault();
                                UpdateApprovedEdition(newlyAddedEdition, approvedEdition);
                                break;
                            }

                            if (siblingsOnStaging.Count > siblingsOnCed.Count)
                            {
                                var message = "In Staging database there are more editions of the event " +
                                              $"{approvedEdition.Event.MasterCode} - {approvedEdition.Event.MasterName} than in CED database." +
                                              "Both must be equal or the ones CED database must be lesser.";
                                var log = CreateInternalLog(message);
                                ExternalLogHelper.Log(log, LoggingEventType.Fatal);
                            }

                            if (!string.IsNullOrWhiteSpace(connectionId))
                            {
                                ProgressHub.SendProgress(connectionId, "Done", i + 1, approvedEditions.Count, TaskType.UpdateApprovedEditionsFromStagingDb.GetHashCode());
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(connectionId))
                        {
                            ProgressHub.SendProgress(connectionId, "Done", 1, 1, TaskType.UpdateApprovedEditionsFromStagingDb.GetHashCode());
                        }
                    }

                    var log2 = CreateInternalLog("The task UpdateApprovedEditionsFromStagingDb completed.", AutoIntegrationUser);
                    ExternalLogHelper.Log(log2, LoggingEventType.Information);
                }
                catch (Exception exc)
                {
                    var message = "The task UpdateApprovedEditionsFromStagingDb failed! " + exc.GetFullMessage();
                    ExternalLogHelper.Log(message, LoggingEventType.Fatal);
                }
            }
        }
Пример #4
0
        async Task MakeOnePageAsync(string url, int executionPercent)
        {
            Page page = await new PageClient(url).MakePageAsync();

            pages.Add(page);
            percent += executionPercent;
            ProgressHub.SendMessage("", percent / 100);
        }
Пример #5
0
 private void Awake()
 {
     progress1      = p1.GetComponent <ProgressHub>();
     progress2      = p2.GetComponent <ProgressHub>();
     progresser1    = programer1.GetComponent <Progresser>();
     progresser2    = programer2.GetComponent <Progresser>();
     fadeAnim       = Fade.GetComponent <Animator>();
     transitionTime = new WaitForSeconds(1f);
 }
Пример #6
0
 public ActionResult StopParsing(string connectionID)
 {
     if (Session["_Cancel"] != null)
     {
         var _Cancel = (Session["_Cancel"] as CancellationTokenSource);
         _Cancel.Cancel();
         ProgressHub.HideProgress(connectionID);
     }
     return(new EmptyResult());
 }
Пример #7
0
        public void otklik(int max, ref int tek, string message)
        {
            tek++;
            int progress = Convert.ToInt16(tek / max * 100);

            if (tek > max)
            {
                tek = Convert.ToInt32(max);
            }
            ProgressHub.SendMessage(message, progress);
        }
        public async Task <Message> Post()
        {
            string contentBody;
            var    message = new Message();

            contentBody = await Request.Content.ReadAsStringAsync();

            message.ClientAddress = HttpContext.Current.Request.UserHostAddress;
            message.ContentBody   = contentBody;
            ProgressHub.SendMessage(JsonConvert.SerializeObject(message));

            return(message);
        }
Пример #9
0
        public async Task <ActionResult> Signup(RegisterUserViewModel model)
        {
            MusicEntities en    = new MusicEntities();
            var           login = en.Logins.FirstOrDefault(a => a.Username.Equals(model.Username));

            if (login != null)
            {
                return(Json(new { success = false, message = "Username exist, Please choose another username!" }));
            }
            else
            {
                try
                {
                    string storageUrl = "musicproject-9f3c5.appspot.com";
                    string date       = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                    var stream2 = model.ImageBase.InputStream;
                    var task2   = new FirebaseStorage(storageUrl)
                                  .Child("MusicProject")
                                  .Child("Images")
                                  .Child(date + "-" + model.ImageBase.FileName)
                                  .PutAsync(stream2);
                    task2.Progress.ProgressChanged += (s, e) => ProgressHub.SendMessage("Uploading User Avatar ... (" + Math.Round((e.Position * 1.0 / e.Length * 100), 0) + "%)");
                    string imageUrl = await task2;

                    Login newUser = new Login
                    {
                        Username = model.Username,
                        Password = model.Password,
                        User     = new User
                        {
                            Avatar    = imageUrl,
                            FirstName = model.Firstname,
                            LastName  = model.Lastname,
                            Phone     = model.Phone,
                            Gender    = model.Gender,
                            Email     = model.Email,
                        }
                    };
                    en.Logins.Add(newUser);
                    en.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(Json(new { success = false, message = ex.Message }));
                }
            }

            return(Json(new { success = true }));
        }
        public async Task StartProgress([Bind(Prefix = "id")] string connectionId)
        {
            var hub = new ProgressHub();

            hub.NotifyStart(connectionId);

            for (int i = 0; i <= 100; i += 5)
            {
                hub.NotifyProgress(connectionId, i);
                await Task.Delay(100);
            }

            hub.NotifyEnd(connectionId);
        }
Пример #11
0
        public async override Task DoStuff()
        {
            await _signalrClients.Client(_connectionId).SendAsync("logGuid", _myGuid);

            using (var logs = await GetClient().Containers.GetContainerLogsAsync(_id, new ContainerLogsParameters
            {
                ShowStderr = true,
                ShowStdout = true,
                Follow = true,
                Tail = "200",
                Timestamps = false,
            }, _cancellation.Token))
            {
                byte[] eight     = new byte[8];
                bool   foundData = false;
                while (logs.Read(eight, 0, 8) == 8)
                {
                    byte[] lastFour = eight.TakeLast(4).ToArray();
                    Array.Reverse(lastFour);
                    int size = BitConverter.ToInt32(lastFour, 0);

                    byte[] lineBytes = new byte[size];
                    logs.Read(lineBytes, 0, size);
                    string line = System.Text.Encoding.UTF8.GetString(lineBytes);
                    if (!foundData && line.Length > 0 && !line.StartsWith("Error grabbing logs: EOF"))
                    {
                        foundData = true;
                    }
                    if ((!foundData && line.Length == 0) || (line == "Error grabbing logs: EOF"))
                    {
                        await _signalrClients.Client(_connectionId).SendAsync("No data found. Either the container has not yet produced logs or the URL is wrong");
                    }

                    if (foundData)
                    {
                        /* string timestampS = line.Substring(0, 30);
                         * DateTime timestamp = DateTime.Parse(timestampS);
                         * line = timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "   " + line.Substring(31);*/

                        if (!ProgressHub.IsBroken(_myGuid))
                        {
                            await _signalrClients.Client(_connectionId).SendAsync("log", line);
                        }
                    }
                }
            }
        }
Пример #12
0
        public async Task <ActionResult> Index(SiteMapModel siteMap)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    ProgressHub.SendMessage("", 1);
                    await testService.MakeTestAsync(siteMap.Host);
                }
                catch (Exception ex)
                {
                    ViewBag.Error = ex.Message;
                    return(View(siteMap));
                }

                return(RedirectToAction("TestResult"));
            }
            return(View(siteMap));
        }
Пример #13
0
    private void Awake()
    {
        level    = new WaitForSeconds[3];
        level[0] = new WaitForSeconds(1f);
        level[1] = new WaitForSeconds(0.5f);
        level[2] = new WaitForSeconds(0.2f);

        gameController  = FindObjectOfType <GameController>();
        progressHub     = ProgressHubOBJ.GetComponent <ProgressHub>();
        anim            = GetComponent <Animator>();
        gamecontroller  = FindObjectOfType <GameController>();
        display         = RequestObj.GetComponent <RequestDisplay>();
        stopProgress    = 0;
        progressStatus  = 0;
        isStartProgress = true;
        isWorking       = true;
        isWinner        = false;
        anim.SetBool("isWorking", isWorking);
    }
Пример #14
0
        private void Process(bool multithread, string connectionID)
        {
            // Prepare
            var _Cancel = new CancellationTokenSource();

            Session["_Cancel"] = _Cancel;
            var FileName = Session["FileName"]?.ToString();
            var Parser   = _Facade.Parser;

            if (Parser.FileAlreadyParsed(FileName))
            {
                ProgressHub.SendMessage(connectionID, "File already parsed!");
                return;
            }
            // Fire and forget
            Task <bool> .Run(() =>
            {
                var progress = new Progress <int>();
                try
                {
                    var ProgressBarMaximum    = Parser.RowsInAnketa(FileName).Result;
                    progress.ProgressChanged += (sender, args) =>
                    {
                        ProgressHub.SendProgress(connectionID, args, ProgressBarMaximum);
                    };
                    if (!multithread)
                    {
                        Parser.Parse_SigleAsync(FileName, progress, _Cancel).Wait();
                    }
                    else
                    {
                        Parser.Parse_MultipleAsync(FileName, progress, _Cancel).Wait();
                    }
                }
                catch (Exception ex)
                {
                    ProgressHub.SendMessage(connectionID, ex.InnerException.Message);
                }
                int fileId = _Facade.Keeper.GetFile(Path.GetFileName(FileName)).ID;
                ProgressHub.ParsingCompleted(connectionID, fileId);
                return(true);
            });
        }
Пример #15
0
        public async Task MakeTestAsync(string host)
        {
            List <string> urlAddresses = new LinkUrl(host).GetURLAddresses();

            if (urlAddresses == null)
            {
                throw new ValidationException("Don't have any URL", "");
            }

            ProgressHub.SendMessage("determining sitemap", 5);

            List <Task> tasks = new List <Task>();

            percent = 500;
            int execPer = 8500 / urlAddresses.Count;

            foreach (var url in urlAddresses)
            {
                tasks.Add(MakeOnePageAsync(url, execPer));
            }
            await Task.WhenAll(tasks);

            ProgressHub.SendMessage("evaluating the time server response", 90);

            Test test = new Test()
            {
                Host = Database.Hosts.GetAll()
                       .Where(h => h.HostURL == host).FirstOrDefault()
                       ?? new Host()
                {
                    HostURL = host
                },
                TestDate = DateTime.Now,
                Pages    = pages
            };

            Database.Tests.Create(test);
            Database.Save();

            ProgressHub.SendMessage("saving test", 95);
        }
Пример #16
0
        public ActionResult TestResult(int?id)
        {
            try
            {
                MapperConfiguration config = new MapperConfiguration(map => map.CreateMap <PageDTO, PageViewModel>());
                var mapper = config.CreateMapper();
                pages = mapper.Map <IEnumerable <PageDTO>, IEnumerable <PageViewModel> >(testService.GetTestPages(id));

                TestDTO test = testService.GetTest(id);
                ViewBag.HostURL = test.HostURL;
                ViewBag.Date    = test.TestDate;

                ProgressHub.SendMessage("receiving data", 99);
                return(View(pages));
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                return(View());
            }
        }
        public async Task <ActionResult> ThisActionCanBeCancelled()
        {
            ViewBag.ExampleType = "Asynchronous examples - This Action Can Be Cancelled.";
            var asyncExamples = new AsyncExamples();

            var progressIndicator = new Progress <ProgressIndicator>(ReportProgress);

            try
            {
                _cancellationToken.Dispose();
                _cancellationToken = new CancellationTokenSource();
                await asyncExamples.AsyncMethodWithCancellation(
                    _cancellationToken.Token,
                    progressIndicator);
            }
            catch (Exception e)
            {
                ProgressHub.CancelProcessing(e.Message);
            }

            return(View("AsyncExamples", 10));
        }
        public async Task <ActionResult> ReportProgress()
        {
            ViewBag.ExperimentType = "Asynchronous experiments - Reporting Progress.";
            var asyncExperiments = new AsyncExperiments();

            var progressIndicator = new Progress <ProgressIndicator>(ReportProgress);

            try
            {
                _cancellationToken.Dispose();
                _cancellationToken = new CancellationTokenSource();
                await asyncExperiments.MarkedAsyncWithIntegerTaskReturningRandomValueToDifferentContext(
                    _cancellationToken.Token,
                    progressIndicator);
            }
            catch (Exception e)
            {
                ProgressHub.CancelProcessing(e.Message);
            }

            return(View("AsyncExperiments", 10));
        }
Пример #19
0
        public async override Task DoStuff()
        {
            await _signalrClients.Client(_connectionId).SendAsync("pullGuid", _myGuid);

            var progress = new Progress <JSONMessage>(async message =>
            {
                if (ProgressHub.IsBroken(_myGuid))
                {
                    _cancellation.Cancel();
                }
                else
                {
                    await _signalrClients.Client(_connectionId).SendAsync("pullProgress", message);
                }
            });
            AuthConfig authConfig = null;

            if (_regCreds != null)
            {
                authConfig = new AuthConfig()
                {
                    ServerAddress = _regCreds.Registry,
                    Username      = _regCreds.Username,
                    Password      = _regCreds.Password
                };
            }
            await GetClient().Images.CreateImageAsync(
                new ImagesCreateParameters()
            {
                FromImage = _fqin,
                Tag       = _tag
            },
                authConfig,
                progress,
                _cancellation.Token
                );

            await _signalrClients.Client(_connectionId).SendAsync("pullFinished");
        }
Пример #20
0
        public async Task <ActionResult> Edit(RegisterUserViewModel model)
        {
            MusicEntities en = new MusicEntities();

            try
            {
                string storageUrl = "musicproject-9f3c5.appspot.com";
                string date       = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                string imageUrl = null;
                if (model.ImageBase != null)
                {
                    var stream2 = model.ImageBase.InputStream;
                    var task2   = new FirebaseStorage(storageUrl)
                                  .Child("MusicProject")
                                  .Child("Images")
                                  .Child(date + "-" + model.ImageBase.FileName)
                                  .PutAsync(stream2);
                    task2.Progress.ProgressChanged += (s, e) => ProgressHub.SendMessage("Uploading User Avatar ... (" + Math.Round((e.Position * 1.0 / e.Length * 100), 0) + "%)");
                    imageUrl = await task2;
                }

                var user = en.Users.FirstOrDefault(a => a.Id == model.Id);
                user.Avatar    = string.IsNullOrEmpty(imageUrl) ? user.Avatar : imageUrl;
                user.FirstName = model.Firstname;
                user.LastName  = model.Lastname;
                user.Phone     = model.Phone;
                user.Gender    = model.Gender;
                user.Email     = model.Email;
                en.SaveChanges();
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, message = ex.Message }));
            }

            return(Json(new { success = true }));
        }
Пример #21
0
        // mock action that takes a while to complete and provides user feedback via signalR connection hub
        public ActionResult DoWork(string connectionId)
        {
            // loop to mock 5 sequential tasks (in a real world scenario you would invoke service/db calls)
            for (var i = 1; i <= 5; i++)
            {
                ProgressHub.SendMessage($"Starting <span class=\"violet\">Task {i}</span>...", connectionId);
                Thread.Sleep(1000);
                ProgressHub.SendMessage($"<span class=\"green\"> Completed!</span>\n\n", connectionId);
                Thread.Sleep(500);
            }

            // mock a failed task
            ProgressHub.SendMessage($"Starting <span class=\"violet\">Task 6</span>...", connectionId);
            Thread.Sleep(1000);
            ProgressHub.SendMessage($"<span class=\"red\"> Failed!</span>\n\n", connectionId);
            Thread.Sleep(500);

            // add a footer messages
            ProgressHub.SendMessage($"Ran 6 tasks,<span class=\"orange\"> 5 passed, 1 failed.</span>\n\n", connectionId);
            ProgressHub.SendMessage($"Finished! <span class=\"cursor\"></span>\n\n", connectionId);

            return(Content("Finished /DoWork"));
        }
        private static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel();

            kernel.Bind <IEnhancedOrgService>().ToMethod(context => CrmService.GetService());
            kernel.Bind <CrmLog>().ToMethod(
                context =>
            {
                var crmLog = new CrmLog(
                    "C:\\Logs\\LinkDev.DataMigration.csv",
                    LogLevel.Debug,
                    new FileConfiguration
                {
                    FileDateFormat = "yyyy-MM-dd_HH-mm-ss-fff",
                    FileSplitMode  = SplitMode.Size,
                    MaxFileSize    = 10000
                });
                crmLog.LogEntryAdded += (sender, args) => ProgressHub.PublishLog(
                    args.LogEntry.Message, args.LogEntry.StartDate?.ToLocalTime() ?? DateTime.Now,
                    args.LogEntry.Level, args.LogEntry.Information);
                return(crmLog);
            });
            return(kernel);
        }
Пример #23
0
        public void UpdateEventDirectors(string key, string connectionId)
        {
            if (key == WebConfigHelper.TaskSchedulerSecretKey)
            {
                try
                {
                    TaskServices.UpdateEventDirectors();

                    var log = CreateInternalLog("The task UpdateEventDirectors completed.", AutoIntegrationUser);
                    ExternalLogHelper.Log(log, LoggingEventType.Information);

                    if (!string.IsNullOrWhiteSpace(connectionId))
                    {
                        ProgressHub.SendProgress(connectionId, "Done", 1, 1, TaskType.UpdateEventDirectors.GetHashCode());
                    }
                }
                catch (Exception exc)
                {
                    var log     = CreateInternalLog("The task UpdateEventDirectors failed!", AutoIntegrationUser);
                    var message = log.AdditionalInfo + " | " + exc.GetFullMessage();
                    ExternalLogHelper.Log(message, LoggingEventType.Fatal);
                }
            }
        }
Пример #24
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            container.RegisterType <CrmLog>(
                new InjectionFactory(
                    c =>
            {
                var crmLog = new CrmLog("C:\\Logs\\LinkDev.DataMigration.csv", LogLevel.Debug,
                                        new FileConfiguration
                {
                    FileDateFormat = "yyyy-MM-dd_HH-mm-ss-fff",
                    FileSplitMode  = SplitMode.Size,
                    MaxFileSize    = 10000
                }, "");
                crmLog.LogEntryAdded += (sender, args) => ProgressHub.PublishLog(
                    args.LogEntry.Message, args.LogEntry.StartDate?.ToLocalTime() ?? DateTime.Now,
                    args.LogEntry.Level, args.LogEntry.Information);
                return(crmLog);
            }));
            container.RegisterType <IEnhancedOrgService>(new InjectionFactory(c => CrmService.GetService()));
        }
        public void Post([FromBody] DownloadRequest data)
        {
            //todo: start downloading the data.Url ....

            ProgressHub.UpdateProgressBar(10, data.ConnectionId);
            Thread.Sleep(2000);

            ProgressHub.UpdateProgressBar(40, data.ConnectionId);
            Thread.Sleep(3000);

            ProgressHub.UpdateProgressBar(64, data.ConnectionId);
            Thread.Sleep(2000);

            ProgressHub.UpdateProgressBar(77, data.ConnectionId);
            Thread.Sleep(2000);

            ProgressHub.UpdateProgressBar(92, data.ConnectionId);
            Thread.Sleep(3000);

            ProgressHub.UpdateProgressBar(99, data.ConnectionId);
            Thread.Sleep(2000);

            ProgressHub.UpdateProgressBar(100, data.ConnectionId);
        }
Пример #26
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"));
        }
Пример #27
0
        public async void Poisk(List <List <string> > excel, DateTime Date, List <Adres> Adresa)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            pro100 = excel.Count;
            IPU           IPUKA    = new IPU();
            List <string> NoAdress = new List <string>();
            //для каждой строки в экселе
            int     lastadres     = 0;
            int     summ          = 0;
            decimal summnorm      = 0;
            decimal summschetchik = 0;

            foreach (List <string> L in excel)
            {
                bool    EstService = false;
                string  adr        = L[0].Replace(" ", "").ToUpper();
                decimal Normativ   = 0;
                decimal Schetchik  = 0;
                bool    ignore     = false;
                try
                {
                    Normativ  = Math.Round(Convert.ToDecimal(L[1].Replace(",", ".")), 2);
                    summnorm += Normativ;
                }
                catch
                {
                }
                try
                {
                    Schetchik      = Math.Round(Convert.ToDecimal(L[2].Replace(",", ".")), 2);
                    summschetchik += Schetchik;
                }
                catch
                {
                }

                if (Normativ + Schetchik == 0)
                {
                    ignore = true;
                    summ++;
                }



                if (!ignore)//если ненулевые показания
                {
                    bool nashli = false;

                    for (int A = lastadres; A < Adresa.Count; A++)
                    {
                        if (Adresa[A].Adress.Equals(adr))//и адрес совпал
                        {
                            //если в массиве адресов есть адрес из строчки то сохраняем айдишник

                            IPUKA.AdresId         = Adresa[A].Id;
                            lastadres             = A;
                            nashli                = true;
                            IPUKA.Normativ        = Normativ;
                            IPUKA.Schetchik       = Schetchik;
                            IPUKA.NomerSchetchika = L[3];
                            IPUKA.Date            = Date;

                            using (WorkContext db = new WorkContext())
                            {
                                try//сохраняем в БД
                                {
                                    db.IPUs.Add(IPUKA);
                                    await db.SaveChangesAsync();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                }
                            }
                            // IPUKA.Name = "";
                            break;
                        }
                    }
                    if (!nashli && lastadres > 0)//если адрес не нашли то продолжаем поиск с начала списка
                    {
                        for (int A = 0; A < lastadres; A++)
                        {
                            if (Adresa[A].Adress.Equals(adr))//и адрес совпал
                            {
                                //если в массиве адресов есть адрес из строчки то сохраняем айдишник

                                IPUKA.AdresId         = Adresa[A].Id;
                                lastadres             = A;
                                nashli                = true;
                                IPUKA.Normativ        = Normativ;
                                IPUKA.Schetchik       = Schetchik;
                                IPUKA.NomerSchetchika = L[3];
                                using (WorkContext db = new WorkContext())
                                {
                                    try//сохраняем в БД
                                    {
                                        db.IPUs.Add(IPUKA);
                                        db.SaveChanges();
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                    }
                                }
                                // IPUKA.Name = "";
                                break;
                            }
                        }
                    }
                    if (!nashli)
                    {
                        NoAdress.Add(adr + "Не найден");
                    }
                }
                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();
            }
        }
Пример #28
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("Файл не выбран или неверный формат файла."));
            }
        }
Пример #29
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("Файл не выбран или неверный формат файла."));
            }
        }
Пример #30
0
        public async void Poisk(List <List <string> > excel, DateTime Date, List <Adres> Adresa, List <TableService> Services)
        {
            int    progress = 0;
            double pro100   = 0;
            int    procount = 0;

            pro100 = excel.Count;
            OBSD        OBSDKA  = new OBSD();
            CultureInfo culture = new CultureInfo("en-US");
            //для каждой строки в экселе
            int lastadres = 0;
            int counter   = 0;

            foreach (List <string> L in excel)
            {
                counter++;
                bool   EstService = false;
                string ser        = L[2].Replace(" ", "").ToUpper();
                string adr        = L[0].Replace(" ", "").ToUpper();

                decimal Saldo  = 0;
                decimal Nach   = 0;
                bool    ignore = false;
                try
                {
                    Saldo = Convert.ToDecimal(L[5], culture);
                }
                catch
                {
                }
                try
                {
                    Nach = Convert.ToDecimal(L[3], culture);
                }
                catch
                {
                }

                if (Nach == 0 && Saldo == 0)
                {
                    ignore = true;
                }

                if (!ignore)//Если не игнорить то ищем
                {
                    try
                    {
                        OBSDKA.TableServiceId = Services.Where(x => x.Type.Equals(ser)).Select(x => x.Id).First();
                        EstService            = true;
                    }
                    catch
                    {
                    }
                    //     foreach (TableService S in Services)
                    //    {

                    //       if (S.Type.Equals(ser))
                    //       {
                    //           OBSDKA.TableServiceId = S.Id;
                    //           EstService = true;
                    //           break;
                    //       }
                    //   }
                }



                if (EstService)//если есть такой сервис
                {
                    bool nashli = false;

                    for (int A = lastadres; A < Adresa.Count; A++)
                    {
                        if (Adresa[A].Adress.Equals(adr))//и адрес совпал
                        {
                            //если в массиве адресов есть адрес из строчки то сохраняем айдишник

                            OBSDKA.AdresId = Adresa[A].Id;
                            lastadres      = A;
                            nashli         = true;
                            int licevoi = 0;
                            try
                            {
                                licevoi = Convert.ToInt32(L[1]);
                            }
                            catch
                            { }
                            OBSDKA.Licevoi = licevoi;
                            OBSDKA.Date    = Date;


                            OBSDKA.Nachislenie = Nach;
                            OBSDKA.Saldo       = Saldo;
                            OBSDKA.FIO         = L[4];
                            OBSDKA.Kvartira    = L[6];
                            using (WorkContext db = new WorkContext())
                            {
                                try//сохраняем в БД
                                {
                                    db.OBSDs.Add(OBSDKA);
                                    await db.SaveChangesAsync();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                }
                            }
                            // OBSDKA.Name = "";
                            break;
                        }
                    }
                    if (!nashli && lastadres > 0)//если адрес не нашли то продолжаем поиск с начала списка
                    {
                        for (int A = 0; A < lastadres; A++)
                        {
                            if (Adresa[A].Adress.Equals(adr))//и адрес совпал
                            {
                                //если в массиве адресов есть адрес из строчки то сохраняем айдишник

                                OBSDKA.AdresId = Adresa[A].Id;
                                lastadres      = A;
                                nashli         = true;
                                int licevoi = 0;
                                try
                                {
                                    licevoi = Convert.ToInt32(L[1]);
                                }
                                catch
                                { }
                                OBSDKA.Licevoi = licevoi;
                                OBSDKA.Date    = Date;


                                OBSDKA.Nachislenie = Nach;
                                OBSDKA.Saldo       = Saldo;
                                OBSDKA.FIO         = L[4];
                                OBSDKA.Kvartira    = L[6];

                                try//сохраняем в БД
                                {
                                    db.OBSDs.Add(OBSDKA);
                                    await db.SaveChangesAsync();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Ошибка записи в базу данных " + e.Message);
                                }
                                // OBSDKA.Name = "";
                                break;
                            }
                        }
                    }
                }
                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();
            }
        }