Exemplo n.º 1
0
        public ActionResult AddEditUser(AddEditUserViewModel model)
        {
            var user = _cdb.CtsUser.Include(s => s.CtsRoles)
                       .Where(x => x.Login == model.UserLogin)
                       .FirstOrDefault(s => s.Domain == model.UserDomain);

            if (user == null)
            {
                user = new CtsUser()
                {
                    Login  = model.UserLogin,
                    Domain = model.UserDomain
                };
                _cdb.CtsUser.Add(user);
            }
            foreach (var userRole in user.CtsRoles)
            {
                if (!model.CtsRoles.ContainsKey(userRole.RoleName))
                {
                    model.CtsRoles.Add(userRole.RoleName, true);
                }
            }

            user.CtsRoles.Clear();
            user.CtsRoles = model.CtsRoles?
                            .Where(x => x.Value)
                            .Select(x => _cdb.CtsRole.Find(x.Key))
                            .ToList();
            _cdb.SaveChanges();

            return(RedirectToAction(model.ReturnView ?? "index"));
        }
Exemplo n.º 2
0
        public ActionResult Add(WagonAnalysis model, string lotName)
        {
            if (ModelState.IsValid)
            {
                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = true;
                model.OperatorName    = User.Identity.Name;
                //cdb.WagonAnalyzes.Add(model);

                List <WagonTransfer> transfers = new List <WagonTransfer>();
                transfers = _cdb.WagonTransfers.Where(x => x.LotName == lotName).ToList();
                transfers = _cdb.WagonTransfers.Where(x => x.LotName == lotName).ToList();

                foreach (var t in transfers)
                {
                    t.Analysis          = model;
                    _cdb.Entry(t).State = EntityState.Modified;
                }

                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            @ViewBag.LotName = lotName;

            @ViewBag.Title = "Добавление анализа для вагонных весов";
            return(View("Add", model));
        }
        public ActionResult Add(BeltTransfer model, string name)
        {
            if (!((model.LotQuantity != null) && ((float)model.LotQuantity > 0)))
            {
                ModelState.AddModelError("LotQuantity", "Некорректный вес - должен быть больше нуля");
            }

            if (ModelState.IsValid)
            {
                var lastTransfer = _cdb.InternalTransfers.Where(x => x.EquipID == model.EquipID).Where(x => x.IsValid)
                                   .OrderByDescending(x => x.TransferTimeStamp).Take(1).FirstOrDefault();
                if (lastTransfer != null)
                {
                    model.TotalQuantity = lastTransfer.TotalQuantity - lastTransfer.LotQuantity + model.LotQuantity;
                }
                else
                {
                    model.TotalQuantity = model.LotQuantity;
                }

                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = false;
                model.Status          = 1;
                model.OperatorName    = User.Identity.Name;
                _cdb.InternalTransfers.Add(model);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            ViewBag.Name   = name;
            @ViewBag.Title = "Ввод данных конвейерных весов";
            return(View("Add", model));
        }
Exemplo n.º 4
0
        public ActionResult Add(WarehouseMeasure model, string name)
        {
            if ((model.TotalMeasured <= 0) || (model.TotalMeasured == null))
            {
                ModelState.AddModelError("TotalMeasured", "Количество на складе должно быть больше 0");
            }
            if (model.MeasureDate > System.DateTime.Now)
            {
                ModelState.AddModelError("MeasureDate", "Неправильная дата - замер не может быть произведен в будущем");
            }
            if (ModelState.IsValid)
            {
                model.OperatorName    = User.Identity.Name;
                model.LasEditDateTime = System.DateTime.Now;
                model.MeasureDate     = model.MeasureDate.Date;

                _cdb.WarehouseMeasures.Add(model);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            ViewBag.Name   = name;
            @ViewBag.Title = "Добавление данных маркшейдерского замера";
            return(View(model));
        }
Exemplo n.º 5
0
        public ActionResult Add(BeltAnalysis model, string alltransfers)
        {
            if (ModelState.IsValid)
            {
                //Get the list of transfers to add analysis
                string[]            transfersArray = alltransfers.Split(',');
                List <BeltTransfer> transfers      = new List <BeltTransfer>();

                foreach (var t in transfersArray)
                {
                    if (t != "")
                    {
                        try
                        {
                            transfers.Add(_cdb.InternalTransfers.Where(x => x.ID == t).FirstOrDefault());
                        }
                        catch
                        {
                        }
                    }
                }

                //Bind model
                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = true;
                model.OperatorName    = User.Identity.Name;

                foreach (var t in transfers)
                {
                    if (t.Analysis != null)
                    {
                        BeltAnalysis analisys = new BeltAnalysis();
                        analisys                   = _cdb.BeltAnalyzes.Where(x => x.ID == t.AnalysisID).FirstOrDefault();
                        analisys.IsValid           = false;
                        _cdb.Entry(analisys).State = EntityState.Modified;
                    }

                    t.Analysis          = model;
                    _cdb.Entry(t).State = EntityState.Modified;
                }

                try
                {
                    _cdb.SaveChanges();
                }
                catch
                (Exception)
                { }
                return(RedirectToAction("Index"));
            }

            @ViewBag.alltransfers = alltransfers;
            @ViewBag.Title        = "Добавление анализа для конвейерных весов";
            return(View("Add", model));
        }
Exemplo n.º 6
0
        public ActionResult WagonScalesAdd(WagonScalesLocations model)
        {
            if (String.IsNullOrEmpty(model.WagonScale.Name))
            {
                ModelState.AddModelError("WagonScale.Name", "Введите наименование - не может быть пустым");
            }
            if (String.IsNullOrEmpty(model.WagonScale.NameEng))
            {
                ModelState.AddModelError("WagonScale.NameEng", "Введите наименование - не может быть пустым");
            }
            if (String.IsNullOrEmpty(model.WagonScale.NameKZ))
            {
                ModelState.AddModelError("WagonScale.NameKZ", "Введите наименование - не может быть пустым");
            }
            if (ModelState.IsValid)
            {
                model.WagonScale.ID = _cdb.WagonScales.Max(x => x.ID) + 1;
                _cdb.WagonScales.Add(model.WagonScale);
                _cdb.SaveChanges();

                return(RedirectToAction("WagonScalesIndex"));
            }

            model.Locations = new SelectList(_cdb.Locations, "ID", "LocationName");
            @ViewBag.Title  = "Добавление вагонных весов";
            return(View("WagonScalesAdd", model));
        }
Exemplo n.º 7
0
        public ActionResult Add(MiningAnalysis model)
        {
            if (ModelState.IsValid)
            {
                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = true;
                model.OperatorName    = User.Identity.Name;
                _cdb.MiningAnalyzes.Add(model);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            model.Location = EquipmentProvider.GetUserLocations(_cdb, User.Identity).Where(x => x.ID == model.LocationID).FirstOrDefault();
            @ViewBag.Title = "Добавление анализа по добыче";
            return(View("Add", model));
        }
Exemplo n.º 8
0
        public static bool SyncWagonNums()
        {
            var recogns = new List <Recogn>();
            var nums    = new List <WagonNumsCache>();

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    recogns.AddRange(centralDB.Recogn.ToList());
                }

                using (var wagDB = new WagonDBcontext())
                {
                    foreach (var r in recogns)
                    {
                        nums.AddRange(wagDB.vagon_nums.Where(x => x.recognid == r.ID).OrderByDescending(x => x.date_time).Take(50)
                                      .Select(x => new WagonNumsCache
                        {
                            ID              = x.id,
                            Date_time       = x.date_time,
                            RecognID        = x.recognid,
                            Id_sostav       = x.id_sostav,
                            Number          = x.number,
                            Number_operator = x.number_operator,
                            Id_operator     = x.id_operator,
                            Camera          = x.camera,
                        }).ToList());
                    }
                }

                if (nums.Any())
                {
                    using (CtsDbContext centralDB = new CtsDbContext())
                    {
                        using (var transaction = centralDB.Database.BeginTransaction())
                        {
                            centralDB.WagonNumsCache.RemoveRange(centralDB.WagonNumsCache);
                            centralDB.WagonNumsCache.AddRange(nums);
                            centralDB.SaveChanges();
                            transaction.Commit();
                        }
                    }
                }

                _logger.Trace("Successfully Synchronized WagonNums");
                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error("Unsuccess with SyncWagonNums");
                _logger.Error(ex.Message.ToString());

                return(false);
            }
        }
Exemplo n.º 9
0
        public ActionResult Add(VehiTransfer model, string name)
        {
            if (ModelState.IsValid)
            {
                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = false;
                model.Status          = 1;
                model.OperatorName    = User.Identity.Name;
                _cdb.VehiTransfers.Add(model);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            GetDestinationsItemsAndScalesToVeiwBag(_cdb.VehiScales.Where(x => x.ID == model.EquipID).Select(x => x.LocationID).FirstOrDefault());
            ViewBag.Name   = name;
            @ViewBag.Title = "Ввод данных автомобильных весов";
            return(View("Add", model));
        }
Exemplo n.º 10
0
        public ActionResult Add(SkipTransferFormModel skipTransfer, string name)
        {
            if (ModelState.IsValid)
            {
                var transfer = new SkipTransfer();
                transfer.ID                = skipTransfer.ID;
                transfer.EquipID           = skipTransfer.EquipID;
                transfer.LiftingID         = skipTransfer.LiftingID;
                transfer.TransferTimeStamp = skipTransfer.TransferTimeStamp;
                transfer.LasEditDateTime   = DateTime.Now;
                transfer.TransferTimeStamp = skipTransfer.TransferTimeStamp;
                transfer.IsValid           = false;
                transfer.Status            = 1;
                transfer.OperatorName      = User.Identity.Name;
                _cdb.SkipTransfers.Add(transfer);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            ViewBag.Name   = name;
            @ViewBag.Title = "Добавление данных скиповых подъемов";
            return(View("Add", skipTransfer));
        }
Exemplo n.º 11
0
        public ActionResult Add(RockUtilTransfer model, string name)
        {
            string userName = User.Identity.Name ?? "";

            if (!((model.LotQuantity != null) && ((float)model.LotQuantity > 0)))
            {
                ModelState.AddModelError("LotQuantity", "Некорректный вес - должен быть больше 0");
            }
            if (ModelState.IsValid)
            {
                model.LasEditDateTime = DateTime.Now;
                model.IsValid         = false;
                model.Status          = 1;
                model.OperatorName    = User.Identity.Name;
                _cdb.RockUtilTransfers.Add(model);
                _cdb.SaveChanges();

                return(RedirectToAction("Index"));
            }

            ViewBag.Name   = name;
            @ViewBag.Title = "Ввод данных утилизации породы";
            return(View("Add", model));
        }
Exemplo n.º 12
0
        private static bool SyncFromCentralToLocalAndDeleteWarehouseTransfers(ConnectionStringSettings connectionStringSettings)
        {
            List <WarehouseTransfer> centralTransferList = new List <WarehouseTransfer>();
            string stringForLogger = "";

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    centralTransferList.AddRange(centralDB.WarehouseTransfers.Where(x => x.Warehouse.LocationID == connectionStringSettings.Name.ToString())
                                                 .Where(x => x.TransferTimeStamp > DbFunctions.AddDays(System.DateTime.Today, -2)));
                }

                if (centralTransferList.Count != 0)
                {
                    using (CtsDbContext localDB = new CtsDbContext(connectionStringSettings.ConnectionString))
                    {
                        using (var transaction = localDB.Database.BeginTransaction())
                        {
                            foreach (var t in centralTransferList)
                            {
                                localDB.WarehouseTransfers.AddOrUpdate(t);
                                stringForLogger = String.Concat(stringForLogger, t.ID, ";");
                            }

                            List <WarehouseTransfer> localTransferList = new List <WarehouseTransfer>();
                            localTransferList.AddRange(localDB.WarehouseTransfers.Where(x => x.TransferTimeStamp <= DbFunctions.AddDays(System.DateTime.Today, -3)));
                            localDB.WarehouseTransfers.RemoveRange(localTransferList);

                            localDB.SaveChanges();
                            transaction.Commit();
                        }
                    }
                }

                _logger.Trace(string.Format("{0} Successfully synchronized SyncFromCentralToLocalAndDeleteWarehouseTransfers: {1}", connectionStringSettings.Name.ToString(), stringForLogger));
                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("{0} Unsuccess with SyncFromCentralToLocalAndDeleteWarehouseTransfers", connectionStringSettings.Name.ToString()));
                _logger.Error(ex.ToString());

                return(false);
            }
        }
Exemplo n.º 13
0
        public static void ManageWeights()
        {
            var stringForLogger = new StringBuilder();

            try
            {
                CtsDbContext centralDB = new CtsDbContext();
                var          skips     = centralDB.Skips.ToList();

                foreach (var s in skips)
                {
                    var skipWeight = centralDB.SkipWeights.Where(x => x.SkipID == s.ID)
                                     .Where(d => d.ValidFrom <= System.DateTime.Now).OrderByDescending(m => m.ValidFrom).FirstOrDefault();
                    if (skipWeight != null)
                    {
                        if (s.Weight != skipWeight.Weight)
                        {
                            s.Weight = skipWeight.Weight;
                            centralDB.Entry(s).State = EntityState.Modified;
                            stringForLogger.Append("SkipID ");
                            stringForLogger.Append(s.ID);
                            stringForLogger.Append(" = ");
                            stringForLogger.Append(s.Weight);
                            stringForLogger.Append("; ");
                        }
                    }
                }

                centralDB.SaveChanges();
                stringForLogger.Insert(0, "Weight changed for ");
                _logger.Trace(stringForLogger.ToString());
            }
            catch (Exception ex)
            {
                _logger.Error("Unsuccess with SkipWeightHandler");
                _logger.Error(ex.ToString());
            }
        }
Exemplo n.º 14
0
        private static bool SyncFromCentralToLocalAndDeleteWagonNumsCache(ConnectionStringSettings connectionStringSettings)
        {
            var nums = new List <WagonNumsCache>();

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    nums.AddRange(centralDB.WagonNumsCache.Where(x => x.Recogn.LocationID == connectionStringSettings.Name.ToString()).ToList());
                }

                if (nums.Any())
                {
                    using (CtsDbContext localDB = new CtsDbContext(connectionStringSettings.ConnectionString))
                    {
                        using (var transaction = localDB.Database.BeginTransaction())
                        {
                            localDB.WagonNumsCache.RemoveRange(localDB.WagonNumsCache);
                            localDB.WagonNumsCache.AddRange(nums);
                            localDB.SaveChanges();
                            transaction.Commit();
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                lock (log)
                {
                    log.Message(ex);
                }
                return(false);
            }
        }
Exemplo n.º 15
0
        private static bool SyncFromCentralToLocalAndDeleteWagonNumsCache(ConnectionStringSettings connectionStringSettings)
        {
            var nums = new List <WagonNumsCache>();

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    nums.AddRange(centralDB.WagonNumsCache.Where(x => x.Recogn.LocationID == connectionStringSettings.Name.ToString()).ToList());
                }

                if (nums.Any())
                {
                    using (CtsDbContext localDB = new CtsDbContext(connectionStringSettings.ConnectionString))
                    {
                        using (var transaction = localDB.Database.BeginTransaction())
                        {
                            localDB.WagonNumsCache.RemoveRange(localDB.WagonNumsCache);
                            localDB.WagonNumsCache.AddRange(nums);
                            localDB.SaveChanges();
                            transaction.Commit();
                        }
                    }
                }

                _logger.Trace(string.Format("{0} Successfully synchronized SyncFromCentralToLocalAndDeleteWagonNumsCache", connectionStringSettings.Name.ToString()));
                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("{0} Unsuccess with SyncFromCentralToLocalAndDeleteWagonNumsCache", connectionStringSettings.Name.ToString()));
                _logger.Error(ex.ToString());

                return(false);
            }
        }
Exemplo n.º 16
0
        private bool SyncWagonRecognition()
        {
            var recogns = new List <Recogn>();
            var nums    = new List <WagonNumsCache>();

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    try
                    {
                        recogns.AddRange(centralDB.Recogn.ToList()); //распознование
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                string timeDate = null;

                using (var wagDB = new WagonDBcontext())
                {
                    for (recognition_records = recogns.Count;
                         recognition_records > 0;
                         recognition_records--)
                    {
                        Recogn r = recogns[recogns.Count - recognition_records];

                        nums.AddRange(wagDB.vagon_nums.Where(x => x.recognid == r.ID).OrderByDescending(x => x.date_time).Take(50)
                                      .Select(x => new WagonNumsCache
                        {
                            ID              = x.id,
                            Date_time       = x.date_time,
                            RecognID        = x.recognid == null ? 123123123 : x.recognid,
                            Id_sostav       = x.id_sostav == null ? 123123123 : x.id_sostav,
                            Number          = x.number.Equals(null) ? "???" : x.number,
                            Number_operator = x.number_operator == null ? "???" : x.number_operator,
                            Id_operator     = x.id_operator == null ? 123123123 : x.id_operator,
                            Camera          = x.camera == null ? "???" : x.camera,
                        }).ToList());

                        timeDate = nums.Select(x => x.Date_time).ToString();
                    }
                }

                if (nums.Any())
                {
                    using (CtsDbContext centralDB = new CtsDbContext())
                    {
                        //using (var transaction = centralDB.Database.BeginTransaction())
                        //{
                        centralDB.WagonNumsCache.RemoveRange(centralDB.WagonNumsCache);
                        centralDB.WagonNumsCache.AddRange(nums);
                        centralDB.SaveChanges();
                        //    transaction.Commit();
                        //}
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemplo n.º 17
0
        private void GetAsyncWagon(DateTime from_ts, DateTime to_ts)
        {
            try
            {
                List <WagonScale> wagonScales;
                List <Item>       items;

                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    wagonScales = centralDB.WagonScales.Include(m => m.Location).ToList();
                    items       = centralDB.Items.Include(m => m.Location).ToList();
                }

                var transfer = new List <ves_vagon>();
                var accept   = new List <WagonTransfer>();

                using (var vesWagon = new WagonDBcontext())
                {
                    transfer = vesWagon.ves_vagon/*.Where(x => x.id_operator != null)*/
                               .Where(x => x.id_operator != 0)
                               .Where(x => x.sync != 1)
                               .Where(x => x.date_time_brutto >= from_ts)
                               .Where(x => x.date_time_brutto <= to_ts)
                               .Include(m => m.scales).DefaultIfEmpty()
                               .Include(h => h.napravlenie).DefaultIfEmpty()
                               .Include(n => n.otpravl).DefaultIfEmpty()
                               .Include(k => k.poluch).DefaultIfEmpty()
                               .ToList();
                }

                if (transfer.Count > 0)
                {
                    using (var centralDB = new CtsDbContext())
                    {
                        for (ves_vagon_records = transfer.Count;
                             ves_vagon_records > 0;
                             ves_vagon_records--)
                        {
                            ves_vagon trans = transfer[transfer.Count - ves_vagon_records];

                            if (trans != null)
                            {
                                var scale = GetCTSWagonScale(trans.scales.name, wagonScales);
                                var item  = items.Where(x => x.Name == trans.gruz).FirstOrDefault();

                                var transfers = new WagonTransfer()
                                {
                                    ID = trans.id.ToString(),
                                    TransferTimeStamp = trans.date_time_brutto,
                                    LasEditDateTime   = DateTime.Now,
                                    OperatorName      = "DBSync",
                                    LotName           = trans.id_sostav.ToString() == "" ? "???" : trans.id_sostav.ToString(),
                                    SublotName        = trans.vagon_num,
                                    OrderNumber       = trans.nakladn,
                                    Tare         = (float)trans.ves_tara / 1000,
                                    Brutto       = (float)trans.ves_brutto / 1000,
                                    Netto        = (float)trans.ves_netto / 1000,
                                    NettoByOrder = (float)trans.ves_netto_docs / 1000,
                                    EquipID      = (scale != null) ? scale.ID : 1,
                                    ItemID       = (item != null) ? item.ID : 1,
                                    Direction    = trans.napravlenie.display_name ?? "",
                                    IsValid      = true,
                                    Status       = 0
                                };

                                //if (trans.otpravl != null)
                                //{
                                //    transfers.FromDestID = (trans.otpravl.name == "0") ? "???" : trans.otpravl.name;
                                //}

                                //if (trans.poluch != null)
                                //{
                                //    transfers.ToDest = (trans.poluch.display_name == "0") ? "???" : trans.poluch.display_name;
                                //}

                                centralDB.WagonTransfers.AddOrUpdate(transfers);
                                centralDB.SaveChanges();

                                using (var wagDB = new WagonDBcontext())
                                {
                                    var originalTransfer = wagDB.ves_vagon.Find(Int32.Parse(transfers.ID));
                                    if (originalTransfer != null)
                                    {
                                        originalTransfer.sync = 1;
                                        wagDB.Entry(originalTransfer).State = EntityState.Modified;
                                    }
                                    wagDB.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var eve in ex.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }
Exemplo n.º 18
0
        public static bool SyncVesWagon()
        {
            string stringForLoggerAccepted = "";
            string stringForLoggerRejected = "";
            string stringForLoggerWrong    = "";
            //int lastID;
            List <WagonScale> wagonScales;
            List <Item>       items;

            Int32.TryParse(ConfigurationManager.AppSettings["WagonDBSyncDepth_Days"], out int syncDepth);
            var dueDate = syncDepth == 0 ? default(DateTime) : DateTime.Now.AddDays(syncDepth * -1);

            try
            {
                using (CtsDbContext centralDB = new CtsDbContext())
                {
                    //var ltr = centralDB.WagonTransfers.Where(x => !x.ID.StartsWith("W")).OrderByDescending(t => t.TransferTimeStamp).Take(1000).Select(m => m.ID).ToArray();
                    //lastID = (ltr.Length != 0) ? ltr.Select(x => int.Parse(x)).OrderByDescending(m => m).FirstOrDefault() : 0;
                    wagonScales = centralDB.WagonScales.Include(m => m.Location).ToList();
                    items       = centralDB.Items.Include(m => m.Location).ToList();
                }

                var transfers = new List <ves_vagon>();
                using (var wagDB = new WagonDBcontext())
                {
                    //transfers = wagDB.ves_vagon.Where(x => x.id > lastID).Include(m => m.scales).Include(h => h.napravlenie)
                    //														.Include(n => n.otpravl).Include(k => k.poluch).ToList();

                    transfers = wagDB.ves_vagon.Where(x => x.id_operator != null)
                                .Where(x => x.id_operator != 0)
                                .Where(x => x.sync != 1)
                                .Where(x => x.date_time_brutto >= dueDate)
                                .Include(m => m.scales)
                                .Include(h => h.napravlenie)
                                .Include(n => n.otpravl).Include(k => k.poluch).ToList();
                }

                if (transfers.Count > 0)
                {
                    var acceptedTransfers = new List <WagonTransfer>();

                    using (var centralDB = new CtsDbContext())
                    {
                        using (var transaction = centralDB.Database.BeginTransaction())
                        {
                            foreach (var trans in transfers)
                            {
                                try
                                {
                                    var scale = GetCTSWagonScale(trans.scales.name, wagonScales);
                                    var item  = items.Where(x => x.Name == trans.gruz).FirstOrDefault();

                                    var transfer = new WagonTransfer()
                                    {
                                        ID = trans.id.ToString(),
                                        TransferTimeStamp = trans.date_time_brutto,
                                        LasEditDateTime   = DateTime.Now,
                                        OperatorName      = "DBSync",
                                        LotName           = trans.id_sostav.ToString() ?? "",
                                        SublotName        = trans.vagon_num ?? "",
                                        OrderNumber       = trans.nakladn ?? "",
                                        FromDestID        = trans.otpravl.name ?? "",
                                        ToDest            = trans.poluch.display_name ?? "",
                                        Tare         = (float)trans.ves_tara / 1000,
                                        Brutto       = (float)trans.ves_brutto / 1000,
                                        Netto        = (float)trans.ves_netto / 1000,
                                        NettoByOrder = (float)trans.ves_netto_docs / 1000,
                                        EquipID      = (scale != null) ? scale.ID : 1,
                                        ItemID       = (item != null) ? item.ID : 1,
                                        Direction    = trans.napravlenie.display_name ?? "",
                                        IsValid      = true,
                                        Status       = 0,
                                    };

                                    var vc       = new ValidationContext(transfer, null, null);
                                    var vResults = new List <ValidationResult>();
                                    var isValid  = Validator.TryValidateObject(transfer, vc, vResults, true);
                                    if (isValid && (transfer.SublotName != ""))
                                    {
                                        acceptedTransfers.Add(transfer);
                                        centralDB.WagonTransfers.AddOrUpdate(transfer);
                                        stringForLoggerAccepted = String.Concat(stringForLoggerAccepted, trans.id, ";");
                                    }
                                    else
                                    {
                                        stringForLoggerRejected = String.Concat(stringForLoggerRejected, trans.id, ";");
                                    }
                                }
                                catch (Exception)
                                {
                                    stringForLoggerWrong = String.Concat(stringForLoggerWrong, trans.id, ";");
                                }
                            }

                            centralDB.SaveChanges();
                            transaction.Commit();
                        }
                    }

                    using (var wagDB = new WagonDBcontext())
                    {
                        foreach (var t in acceptedTransfers)
                        {
                            var originalTransfer = wagDB.ves_vagon.Find(Int32.Parse(t.ID));
                            if (originalTransfer != null)
                            {
                                originalTransfer.sync = 1;
                                wagDB.Entry(originalTransfer).State = EntityState.Modified;
                            }
                        }

                        using (var transaction = wagDB.Database.BeginTransaction())
                        {
                            wagDB.SaveChanges();
                            transaction.Commit();
                        }
                    }
                }

                _logger.Trace(string.Format("Successfully Synchronized VesWagon: {0}", stringForLoggerAccepted));
                _logger.Trace(string.Format("Successfully Synchronized VesWagon, not accepted transfers: {0}", stringForLoggerRejected));
                _logger.Trace(string.Format("Successfully Synchronized VesWagon, transfers with wrong properties: {0}", stringForLoggerWrong));

                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error("Unsuccess with SyncVesWagon");
                _logger.Error(ex.Message.ToString());

                return(false);
            }
        }
Exemplo n.º 19
0
        public ActionResult _AllTransfers(TransferList model)
        {
            model.Transfer.LasEditDateTime = DateTime.Now;
            model.Transfer.IsValid         = false;
            model.Transfer.Status          = 1;
            model.Transfer.OperatorName    = User.Identity.Name;
            var oldid = model.Transfer.ID;

            model.Transfer.ID = "W" + model.Transfer.EquipID + (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            if (Request.Form["One"] != null)
            {
                var errorMessages = new List <string>();
                var modelbadstate = false;
                if (oldid == model.Transfer.ID)
                {
                    errorMessages.Add("Слишком быстро - попробуйте еще раз");
                    modelbadstate = true;
                }
                if (string.IsNullOrEmpty(model.Transfer.SublotName))
                {
                    errorMessages.Add("Необходимо указать номер вагона - поле не может быть пустым");
                    modelbadstate = true;
                }

                if (string.IsNullOrEmpty(model.Transfer.LotName))
                {
                    errorMessages.Add("Необходимо указать номер партии - поле не может быть пустым");
                    modelbadstate = true;
                }

                if (model.Transfer.Brutto <= 0 || model.Transfer.Brutto > 150)
                {
                    errorMessages.Add("Нет или неправильно указан вес вагона - должен быть больше 0 и меньше 150");
                    modelbadstate = true;
                }

                if (model.Transfer.Tare <= 0 || model.Transfer.Tare > model.Transfer.Brutto)
                {
                    errorMessages.Add("Нет или неправильно указан вес тары - должен быть больше нуля и меньше брутто");
                    modelbadstate = true;
                }

                if (modelbadstate)
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(Json(new { modelbadstate = modelbadstate, ErrorMessage = string.Join(", ", errorMessages) }));
                }
                model.Transfers.Add(model.Transfer);

                return(PartialView(model));
            }
            if (Request.Form["SaveAll"] != null)
            {
                foreach (var mod in model.Transfers)
                {
                    var vc       = new ValidationContext(mod, null, null);
                    var vResults = new List <ValidationResult>();
                    var isValid  = Validator.TryValidateObject(mod, vc, vResults, true);

                    _cdb.WagonTransfers.Add(mod);
                }
                string message;

                _cdb.SaveChanges();
                message = "Данные партии зафиксированы";

                return(JavaScript("RedirectToIndex('" + message + "');"));
            }
            return(View());
        }