Пример #1
0
 public IActionResult Delete(string id, string type)
 {
     if (type == "Blog")
     {
         try
         {
             if (id != null)
             {
                 List <Review> r = new List <Review>();
                 r = c.Reviews.Where(x => x.ReviewID == id && x.IsDeleted == false).ToList();
                 foreach (var item in r)
                 {
                     item.Publish   = false;
                     item.IsDeleted = true;
                     c.Update(item);
                 }
                 c.SaveChanges();
                 return(Redirect("/Blogs"));
             }
             else
             {
                 ViewData["Error"] = "Bir hata oluştu #3303";
                 return(Redirect("/Blogs"));
             }
         }
         catch
         {
             ViewData["Error"] = "Bir hata oluştu #3305";
             return(Redirect("/Blogs"));
         }
     }
     if (type == "Comment")
     {
         string reviewID = "";
         var    x        = c.Comments.Where(x => x.CommentID == id).ToList();
         foreach (var item in x)
         {
             item.IsDeleted = true;
             reviewID       = item.ReviewID;
             c.Comments.Update(item);
         }
         c.SaveChanges();
         return(Redirect("/Blogs/Blog/" + reviewID));
     }
     else
     {
         return(Redirect("/"));
     }
 }
        public async Task <bool> SaveFileContainer(FileContainer container)
        {
            try
            {
                context.Update(container);
                await context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                //TODO: Logging
                return(false);
            }

            return(true);
        }
 private void Set(T model, EntityState state)
 {
     if (state == EntityState.Added)
     {
         _context.Add(model);
     }
     else if (state == EntityState.Modified)
     {
         _context.Update(model);
     }
     else if (state == EntityState.Deleted)
     {
         _context.Remove(model);
     }
 }
Пример #4
0
        public IActionResult AtualizarCarro(int id, Carro carro)
        {
            if (id == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                contexto.Update(carro);
                contexto.SaveChanges();
                return(RedirectToAction(nameof(Index)));
            }

            return(View(carro));
        }
Пример #5
0
        public async Task UpdateAsync(int id, T entity)
        {
            using (var context = new EFContext())
            {
                entity.Id = id;

                //context.Attach(entity);
                //context.Entry(entity).State = EntityState.Modified;
                context.Update(entity);

                context.ChangeTracker.DetectChanges();
                Console.WriteLine(context.ChangeTracker.DebugView.LongView);

                await context.SaveChangesAsync();
            }
        }
Пример #6
0
        public IActionResult Put([FromRoute] int id)
        {
            var animal = _context.Animals.SingleOrDefault(x => x.Id == id);

            if (animal == null)
            {
                return(BadRequest(new { invalid = "Animal is not found" }));
            }

            animal.ImageLikeCount = animal.ImageLikeCount + 1;

            _context.Update(animal);

            _context.SaveChanges();

            return(Ok(id));
        }
Пример #7
0
        public IActionResult Edit(int id,
                                  [Bind("Id,Title,Year")] Game game)
        {
            if (id != game.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                _context.Update(game);
                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(game));
        }
Пример #8
0
        /// <summary>
        /// Sets user's session timer
        /// </summary>
        /// <param name="id"></param>
        /// <returns>DateTime</returns>
        public static DateTime SetSessionTimer(int id)
        {
            DateTime setTime;

            setTime = DateTime.MaxValue;
            using (var db = new EFContext())
            {
                var user = db.Users?.FirstOrDefault(u => u.Id == id);
                if (user != null)
                {
                    user.SessionTimer = DateTime.Now;
                    db.Update(user);
                    db.SaveChanges();
                    setTime = user.SessionTimer;
                }
            }
            return(setTime);
        }
Пример #9
0
 public IActionResult Put(Product product)
 {
     if (product.Countt > 0)
     {
         product.IsAviable = true;
     }
     else
     {
         product.IsAviable = false;
     }
     if (ModelState.IsValid)
     {
         _context.Update(product);
         _context.SaveChanges();
         return(Ok(product));
     }
     return(BadRequest(ModelState));
 }
Пример #10
0
        /// <summary>
        ///Sends ping to server
        /// </summary>
        /// <param name="userId"></param>
        /// <returns>string</returns>
        public string Ping(int userId)
        {
            var ping = string.Empty;

            using (var db = new EFContext())
            {
                var user = db.Users?.FirstOrDefault(u => u.Id == userId);
                if (user != null && SessionTimer.CheckSessionTimer(user.SessionTimer) == false)
                {
                    ping = "Pong";
                    user.SessionTimer = DateTime.Now;
                    db.Update(user);
                    db.SaveChanges();
                    Startup.sessionCookie = user;
                }
            }

            return(ping);
        }
Пример #11
0
        public async Task <bool> UpdateAsync(AnswerDTO dto)
        {
            var orgEntity = _context.Answer.Single(u => u.Id == dto.Id);

            orgEntity.Id         = dto.Id;
            orgEntity.Field      = dto.Field.ConvertToEntity();
            orgEntity.FieldId    = dto.Field.Id;
            orgEntity.ReviewTask = dto.ReviewTask.ConvertToEntity();
            orgEntity.Value      = null;

            _context.Update(orgEntity);
            try {
                await _context.SaveChangesAsync();

                return(true);
            } catch (DbUpdateException) {
                return(false);
            }
        }
Пример #12
0
        /// <summary>
        /// Registers new user
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="passwordverify"></param>
        /// <returns>bool</returns>
        public bool Register(string name, string password, string passwordverify)
        {
            bool isUserCreated = false;

            using (var db = new EFContext())
            {
                var user = db.Users.FirstOrDefault(u => u.Name == name);
                if (user == null && password == passwordverify && password != "")
                {
                    user = new User {
                        Name = name, Password = password, IsAdmin = false, IsActive = true
                    };
                    db.Update(user);
                    db.SaveChanges();
                    isUserCreated = true;
                }
            }
            return(isUserCreated);
        }
Пример #13
0
        public async Task <bool> UpdateAsync(UserDTO dto)
        {
            var orgEntity = await _context.User.SingleAsync(u => u.Id == dto.Id);

            //orgEntity.Id = dto.Id;
            //orgEntity.Name = dto.Name;
            //orgEntity.Password = dto.Password;
            //_context.Update(orgEntity);
            orgEntity.UpdateProperties(dto.ConvertToEntity());
            _context.Update(orgEntity);

            try {
                await _context.SaveChangesAsync();

                return(true);
            } catch (DbUpdateException) {
                return(false);
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            EFContext context   = new EFContext("data source = DESKTOP-VGPBEL0; initial catalog = Study; user id = sa; password = jym0927*SqlServer");
            var       alumnos   = context.Alumnos.ToList();
            Alumno    newAlumno = new Alumno()
            {
                Name    = "Prueba",
                SurName = "Prueba"
            };

            context.Alumnos.Add(newAlumno);
            context.SaveChanges();

            var alumno = context.Alumnos.FirstOrDefault();

            alumno.SurName = "CAMBIANDO";
            context.Update(alumno);
            context.SaveChanges();
        }
Пример #15
0
        /// <summary>
        /// Login user
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>int</returns>
        public int?Login(string userName, string password)
        {
            using (var db = new EFContext())
            {
                var user = db.Users?.FirstOrDefault(u => u.Name == userName);
                if (user != null && user.Password == password && user.IsActive)
                {
                    user.SessionTimer = SessionTimer.SetSessionTimer(user.Id);
                    user.LastLogin    = user.SessionTimer;
                    db.Update(user);
                    db.SaveChanges();
                    Startup.sessionCookie = user;

                    return(user.Id);
                }
                else
                {
                    return(null);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Sets amount of book
        /// ADDENDUM: Added return value int amount
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="bookId"></param>
        /// <param name="amount"></param>
        /// <returns>Tuple (bool, int)</returns>
        public (bool isAmountSet, int amount) SetAmount(int adminId, int bookId, int amount)
        {
            bool isAmountSet = false;

            if (Security.AdminCheck(adminId) && SessionTimer.AdminCheckSessionTimer(adminId) == false)
            {
                using (var db = new EFContext())
                {
                    var book = db.Books?.FirstOrDefault(i => i.Id == bookId);
                    if (book != null)
                    {
                        book.Amount = amount;
                        SessionTimer.AdminSetSessionTimer(adminId);
                        db.Update(book);
                        db.SaveChanges();
                        isAmountSet = true;
                    }
                }
            }
            return(isAmountSet, amount);
        }
Пример #17
0
 public IActionResult Delete(string id, string type)
 {
     if (type == "Restaurant")
     {
         var Restaurant = c.Restaurants.Where(x => x.RestaurantID == id).ToList();
         foreach (var item in Restaurant)
         {
             item.IsAccepted = false;
             item.Deleted    = true;
             c.Update(item);
         }
         c.SaveChanges();
         return(Redirect("/editor/restaurants"));
     }
     if (type == "Blog")
     {
         List <Review> r = new List <Review>();
         r = c.Reviews.Where(x => x.ReviewID == id && x.IsDeleted == false).ToList <Review>();
         foreach (var item in r)
         {
             item.Publish   = true;
             item.IsDeleted = false;
             c.Update(item);
         }
         c.SaveChanges();
         return(Redirect("/editor/blogs"));
     }
     if (type == "Menu")
     {
         List <Menu> r = new List <Menu>();
         r = c.Menus.Where(x => x.MenuID == id && x.IsDeleted == false).ToList <Menu>();
         foreach (var item in r)
         {
             item.IsPublished = true;
             item.IsDeleted   = false;
             c.Update(item);
         }
         c.SaveChanges();
         return(Redirect("/editor/menus"));
     }
     else
     {
         return(Redirect("/editor"));
     }
 }
Пример #18
0
        /// <summary>
        /// Updates category
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="categoryId"></param>
        /// <param name="name"></param>
        /// <returns>bool</returns>
        public bool UpdateCategory(int adminId, int categoryId, string name)
        {
            bool isCategoryUpdated = false;

            if (Security.AdminCheck(adminId) && SessionTimer.AdminCheckSessionTimer(adminId) == false)
            {
                using (var db = new EFContext())
                {
                    var category = db.BookCategories?.FirstOrDefault(c => c.Id == categoryId);

                    if (category != null)
                    {
                        category.Name = name;
                        SessionTimer.AdminSetSessionTimer(adminId);
                        db.Update(category);
                        db.SaveChanges();
                        isCategoryUpdated = true;
                    }
                }
            }

            return(isCategoryUpdated);
        }
Пример #19
0
 public IActionResult Blog(string ReviewID, string Header)
 {
     try
     {
         if (Header == "Delete")
         {
             if (ReviewID != null)
             {
                 List <Review> r = new List <Review>();
                 r = c.Reviews.Where(x => x.ReviewID == ReviewID && x.IsDeleted == false).ToList <Review>();
                 foreach (var item in r)
                 {
                     item.Publish   = false;
                     item.IsDeleted = true;
                     c.Update(item);
                     c.SaveChanges();
                 }
                 return(RedirectToAction(nameof(Index)));
             }
             else
             {
                 ViewData["Error"] = "Bir hata oluştu #3303";
                 return(View());
             }
         }
         else
         {
             ViewData["Error"] = "Bir hata oluştu #3304";
             return(View());
         }
     }
     catch
     {
         ViewData["Error"] = "Bir hata oluştu #3305";
         return(View());
     }
 }
Пример #20
0
        /// <summary>
        /// Inactivates user
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="userId"></param>
        /// <returns>bool</returns>
        public bool InactivateUser(int adminId, int userId)
        {
            bool isInactivated = false;

            if (Security.AdminCheck(adminId) && SessionTimer.AdminCheckSessionTimer(adminId) == false)
            {
                using (var db = new EFContext())
                {
                    var user = db.Users?.FirstOrDefault(u => u.Id == userId);

                    if (user != null)
                    {
                        user.IsActive = false;

                        SessionTimer.AdminSetSessionTimer(adminId);
                        db.Update(user);
                        db.SaveChanges();

                        isInactivated = true;
                    }
                }
            }
            return(isInactivated);
        }
Пример #21
0
        /// <summary>
        /// Updates properties of book
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="id"></param>
        /// <param name="title"></param>
        /// <param name="author"></param>
        /// <param name="price"></param>
        /// <returns>bool</returns>
        public bool UpdateBook(int adminId, int id, string title, string author, int price)
        {
            bool isBookUpdated = false;

            if (Security.AdminCheck(adminId) && SessionTimer.AdminCheckSessionTimer(adminId) == false)
            {
                using (var db = new EFContext())
                {
                    var book = db.Books?.FirstOrDefault(x => x.Id == id);
                    if (book != null)
                    {
                        book.Title  = title;
                        book.Author = author;
                        book.Price  = price;
                        SessionTimer.AdminSetSessionTimer(adminId);
                        db.Update(book);
                        db.SaveChanges();
                        isBookUpdated = true;
                    }
                }
            }

            return(isBookUpdated);
        }
Пример #22
0
        public async Task <IActionResult> Create([Bind("NombreMedico,EpisodioId")] Epicrisis epicrisis)
        {
            if (ModelState.IsValid)
            {
                epicrisis.FechaYHora = DateTime.Now;

                var Episodio = await _context.Episodios
                               .FirstOrDefaultAsync(m => m.Id == epicrisis.EpisodioId);

                Episodio.EstadoAbierto = false;

                epicrisis.Episodio = Episodio;

                _context.Add(epicrisis);
                _context.Update(Episodio);

                await _context.SaveChangesAsync();


                return(RedirectToAction("Create", "Diagnosticos", new { @idEpi = epicrisis.Id }));
            }
            ViewData["EpisodioId"] = new SelectList(_context.Episodios, "Id", "Id", epicrisis.EpisodioId);
            return(View(epicrisis));
        }
Пример #23
0
 public void Save(T entity)
 => context.Update(entity);
Пример #24
0
        public string VerificaSaque(Saque saque, Cedulas cedulas, IQueryable <Cedulas> notas, EFContext context)
        {
            var Qtd200 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "200").Single();
            Qtd200       = pegarCedulas.Qtd;

            var Qtd100 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "100").Single();
            Qtd100       = pegarCedulas.Qtd;

            var Qtd50 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "50").Single();
            Qtd50        = pegarCedulas.Qtd;

            var Qtd20 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "20").Single();
            Qtd20        = pegarCedulas.Qtd;

            var Qtd10 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "10").Single();
            Qtd10        = pegarCedulas.Qtd;

            var Qtd5 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "5").Single();
            Qtd5         = pegarCedulas.Qtd;

            var Qtd2 = 0;

            pegarCedulas = notas.Where(a => a.Nota == "2").Single();
            Qtd2         = pegarCedulas.Qtd;

            var saldoCaixa = (200 * Qtd200) + (100 * Qtd100) + (50 * Qtd50) + (20 * Qtd20) + (10 * Qtd10) + (5 * Qtd5) + (2 * Qtd2);
            var valorSaque = saque.Valor;

            if (valorSaque < 1000 && valorSaque >= 2 && valorSaque < saldoCaixa)
            {
                // 200
                if (valorSaque >= 200)
                {
                    var QtdNotas = valorSaque / 200;

                    if (Qtd200 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 200;
                        Qtd200      -= QtdNotas;
                        saque.Notas += "Notas 200: " + QtdNotas + " - ";
                    }
                    else if (Qtd200 > 0)
                    {
                        valorSaque  -= Qtd200 * 200;
                        saque.Notas += "Notas 200: " + Qtd200 + " - ";
                        Qtd200      -= Qtd200;
                    }
                }
                // 100
                if (valorSaque >= 100)
                {
                    var QtdNotas = valorSaque / 100;

                    if (Qtd100 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 100;
                        Qtd100      -= QtdNotas;
                        saque.Notas += "Notas 100: " + QtdNotas + " - ";
                    }
                    else if (Qtd100 > 0)
                    {
                        valorSaque  -= Qtd100 * 100;
                        saque.Notas += "Notas 100: " + Qtd100 + " - ";
                        Qtd100      -= Qtd100;
                    }
                }
                // 50
                if (valorSaque >= 50)
                {
                    var QtdNotas = valorSaque / 50;

                    if (Qtd50 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 50;
                        Qtd50       -= QtdNotas;
                        saque.Notas += "Notas 50: " + QtdNotas + " - ";
                    }
                    else if (Qtd50 > 0)
                    {
                        valorSaque  -= Qtd50 * 50;
                        saque.Notas += "Notas 50: " + Qtd50 + " - ";
                        Qtd50       -= Qtd50;
                    }
                }
                // 20
                if (valorSaque >= 20)
                {
                    var QtdNotas = valorSaque / 20;

                    if (Qtd20 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 20;
                        Qtd20       -= QtdNotas;
                        saque.Notas += "Notas 20: " + QtdNotas + " - ";
                    }
                    else if (Qtd20 > 0)
                    {
                        valorSaque  -= Qtd20 * 20;
                        saque.Notas += "Notas 20: " + Qtd20 + " - ";
                        Qtd20       -= Qtd20;
                    }
                }
                // 10
                if (valorSaque >= 10)
                {
                    var QtdNotas = valorSaque / 10;

                    if (Qtd10 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 10;
                        Qtd10       -= QtdNotas;
                        saque.Notas += "Notas 10: " + QtdNotas + " - ";
                    }
                    else if (Qtd10 > 0)
                    {
                        valorSaque  -= Qtd10 * 10;
                        saque.Notas += "Notas 10: " + Qtd10 + " - ";
                        Qtd10       -= Qtd10;
                    }
                }
                // 5
                if (valorSaque >= 5)
                {
                    var QtdNotas = valorSaque / 5;

                    if (Qtd5 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 5;
                        Qtd5        -= QtdNotas;
                        saque.Notas += "Notas 5: " + QtdNotas + " - ";
                    }
                    else
                    {
                        valorSaque  -= Qtd5 * 5;
                        saque.Notas += "Notas 5: " + Qtd5 + " - ";
                        Qtd5        -= Qtd5;
                    }
                }
                // 2
                if (valorSaque >= 2)
                {
                    var QtdNotas = valorSaque / 2;

                    if (Qtd2 >= QtdNotas)
                    {
                        valorSaque   = valorSaque % 2;
                        Qtd2        -= QtdNotas;
                        saque.Notas += "Notas 2: " + QtdNotas + " - ";
                    }
                    else
                    {
                        valorSaque  -= Qtd2 * 2;
                        saque.Notas += "Notas 2: " + Qtd2 + " - ";
                        Qtd2        -= Qtd2;
                    }
                }
            }
            else
            {
                if (valorSaque > 1000)
                {
                    var resultado = "Erro1";

                    return(resultado);
                }
                else if (valorSaque < 2)
                {
                    var resultado = "Erro2";

                    return(resultado);
                }
                else if (valorSaque > saldoCaixa)
                {
                    var resultado = "Erro3";

                    return(resultado);
                }
            }

            if (valorSaque == 0)
            {
                // 200
                var cedulas200 = notas.Where(a => a.Nota == "200").Single();
                cedulas200.Qtd = Qtd200;
                context.Update(cedulas200);
                // 100
                var cedulas100 = notas.Where(a => a.Nota == "100").Single();
                cedulas100.Qtd = Qtd100;
                context.Update(cedulas100);
                // 50
                var cedulas50 = notas.Where(a => a.Nota == "50").Single();
                cedulas50.Qtd = Qtd50;
                context.Update(cedulas50);
                // 20
                var cedulas20 = notas.Where(a => a.Nota == "20").Single();
                cedulas20.Qtd = Qtd20;
                context.Update(cedulas20);
                // 10
                var cedulas10 = notas.Where(a => a.Nota == "10").Single();
                cedulas10.Qtd = Qtd10;
                context.Update(cedulas10);
                // 5
                var cedulas5 = notas.Where(a => a.Nota == "5").Single();
                cedulas5.Qtd = Qtd5;
                context.Update(cedulas5);
                // 2
                var cedulas2 = notas.Where(a => a.Nota == "2").Single();
                cedulas2.Qtd = Qtd2;
                context.Update(cedulas2);

                string resultado;
                if (saque.Notas != null && saque.Hora != null)
                {
                    context.Update(saque);
                    context.SaveChanges();
                    resultado = "Sucesso";
                }
                else
                {
                    resultado = "Erro4";
                }

                return(resultado);
            }
            else
            {
                return(valorSaque.ToString());
            }
        }
        private async Task SetupVendorData()
        {
            var vendor1 = await EFContext.Vendor.FirstOrDefaultAsync(v => v.Name == "Vendor_1");

            var vendor2 = await EFContext.Vendor.FirstOrDefaultAsync(v => v.Name == "Vendor_2");

            var usCurrency = await EFContext.Currency.FirstOrDefaultAsync(a => a.Symbol == "$");

            vendor1.Categories.Add(new VendorCategory
            {
                Name = plugins.Constants.VendorCategory.DistributionTrafficking,
                IsPreferredSupplier = false,
                HasDirectPayment    = false,
                Created             = DateTime.Now,
                Modified            = DateTime.Now,
                Currency            = usCurrency,
                DefaultCurrencyId   = usCurrency.Id,
                VendorCategoryRules = new List <VendorRule>
                {
                    //NORTH AMERICA AREA
                    new VendorRule
                    {
                        Name = "Rule 1 Trafficking",
                        Rule = new Rule
                        {
                            Name     = "1000 Volt_VendorPayment_Rule 1 Trafficking",
                            Created  = DateTime.Now,
                            Modified = DateTime.Now,
                            Criteria =
                                "{\"FieldName\":null,\"Operator\":\"And\",\"TargetValue\":null,\"Children\":[{\"FieldName\":\"BudgetRegion\",\"Operator\":\"Equal\",\"TargetValue\":\"NORTHERN AMERICA AREA\",\"Children\":[]},{\"FieldName\":\"CostType\",\"Operator\":\"Equal\",\"TargetValue\":\"Trafficking\",\"Children\":[]},{\"FieldName\":\"IsAIPE\",\"Operator\":\"Equal\",\"TargetValue\":\"False\",\"Children\":[]},{\"FieldName\":\"TotalCostAmount\",\"Operator\":\"GreaterThanOrEqual\",\"TargetValue\":\"0\",\"Children\":[]}]}",
                            Definition =
                                "{\"DetailedSplit\":false,\"Splits\":[{\"CostTotalName\":\"CostTotal\",\"AIPESplit\":0.0,\"OESplit\":0.0,\"FPSplit\":0.0,\"FASplit\":1.0}]}",
                            Priority = 0,
                            Type     = RuleType.VendorPayment
                        }
                    }
                }
            });
            vendor2.Categories.Add(new VendorCategory
            {
                Name = plugins.Constants.VendorCategory.DistributionTrafficking,
                IsPreferredSupplier = false,
                HasDirectPayment    = false,
                Created             = DateTime.Now,
                Modified            = DateTime.Now,
                Currency            = usCurrency,
                DefaultCurrencyId   = usCurrency.Id,
                VendorCategoryRules = new List <VendorRule>
                {
                    //JAPAN
                    new VendorRule
                    {
                        Name = "Rule 1 Trafficking",
                        Rule = new Rule
                        {
                            Name     = "1000 Volt_VendorPayment_Rule 1 Trafficking",
                            Created  = DateTime.Now,
                            Modified = DateTime.Now,
                            Criteria =
                                "{\"FieldName\":null,\"Operator\":\"And\",\"TargetValue\":null,\"Children\":[{\"FieldName\":\"BudgetRegion\",\"Operator\":\"Equal\",\"TargetValue\":\"JAPAN\",\"Children\":[]},{\"FieldName\":\"CostType\",\"Operator\":\"Equal\",\"TargetValue\":\"Trafficking\",\"Children\":[]},{\"FieldName\":\"IsAIPE\",\"Operator\":\"Equal\",\"TargetValue\":\"False\",\"Children\":[]},{\"FieldName\":\"TotalCostAmount\",\"Operator\":\"GreaterThanOrEqual\",\"TargetValue\":\"0\",\"Children\":[]}]}",
                            Definition =
                                "{\"DetailedSplit\":false,\"Splits\":[{\"CostTotalName\":\"CostTotal\",\"AIPESplit\":0.0,\"OESplit\":0.0,\"FPSplit\":0.0,\"FASplit\":1.0}]}",
                            Priority = 0,
                            Type     = RuleType.VendorPayment
                        }
                    }
                }
            });
            EFContext.Update(vendor1);
            EFContext.Update(vendor2);
            EFContext.SaveChanges();
            await ReindexItem <VendorSearchItem, Vendor>(vendor1, Constants.ElasticSearchIndices.VendorIndexName);
            await ReindexItem <VendorSearchItem, Vendor>(vendor2, Constants.ElasticSearchIndices.VendorIndexName);
        }
        public async Task Search_Vendor_By_Category_And_BudgetRegion()
        {
            // Arrange

            var vendor1 = await EFContext.Vendor.FirstOrDefaultAsync(v => v.Name == "Vendor_1");

            if (!vendor1.Categories.Any())
            {
                await SetupVendorData();
            }
            var usCurrency = await EFContext.Currency.FirstOrDefaultAsync(a => a.Symbol == "$");

            vendor1.Categories.Add(new VendorCategory
            {
                Name = plugins.Constants.VendorCategory.UsageBuyoutContract,
                IsPreferredSupplier = false,
                HasDirectPayment    = false,
                Created             = DateTime.Now,
                Modified            = DateTime.Now,
                Currency            = usCurrency,
                DefaultCurrencyId   = usCurrency.Id,
                VendorCategoryRules = new List <VendorRule>
                {
                    //NORTH AMERICA AREA
                    new VendorRule
                    {
                        Name = "Rule 1 Usage",
                        Rule = new Rule
                        {
                            Name     = "12 Film Ltd._VendorPayment_Rule 1 Usage",
                            Created  = DateTime.Now,
                            Modified = DateTime.Now,
                            Criteria =
                                "{\"FieldName\":null,\"Operator\":\"And\",\"TargetValue\":null,\"Children\":[{\"FieldName\":\"BudgetRegion\",\"Operator\":\"Equal\",\"TargetValue\":\"NORTHERN AMERICA AREA\",\"Children\":[]},{\"FieldName\":\"CostType\",\"Operator\":\"Equal\",\"TargetValue\":\"Buyout\",\"Children\":[]},{\"FieldName\":\"IsAIPE\",\"Operator\":\"Equal\",\"TargetValue\":\"False\",\"Children\":[]},{\"FieldName\":\"TotalCostAmount\",\"Operator\":\"GreaterThanOrEqual\",\"TargetValue\":\"0\",\"Children\":[]}]}",
                            Definition =
                                "{\"DetailedSplit\":false,\"Splits\":[{\"CostTotalName\":\"CostTotal\",\"AIPESplit\":0.0,\"OESplit\":0.0,\"FPSplit\":0.0,\"FASplit\":1.0}]}",
                            Priority = 0,
                            Type     = RuleType.VendorPayment
                        }
                    },
                    //GREATER CHINA AREA
                    new VendorRule
                    {
                        Name = "Rule 2 Usage",
                        Rule = new Rule
                        {
                            Name     = "12 Film Ltd._VendorPayment_Rule 2 Usage",
                            Created  = DateTime.Now,
                            Modified = DateTime.Now,
                            Criteria =
                                "{\"FieldName\":null,\"Operator\":\"And\",\"TargetValue\":null,\"Children\":[{\"FieldName\":\"BudgetRegion\",\"Operator\":\"Equal\",\"TargetValue\":\"GREATER CHINA AREA\",\"Children\":[]},{\"FieldName\":\"CostType\",\"Operator\":\"Equal\",\"TargetValue\":\"Buyout\",\"Children\":[]},{\"FieldName\":\"IsAIPE\",\"Operator\":\"Equal\",\"TargetValue\":\"False\",\"Children\":[]},{\"FieldName\":\"TotalCostAmount\",\"Operator\":\"GreaterThanOrEqual\",\"TargetValue\":\"0\",\"Children\":[]}]}",
                            Definition =
                                "{\"DetailedSplit\":false,\"Splits\":[{\"CostTotalName\":\"CostTotal\",\"AIPESplit\":0.0,\"OESplit\":0.5,\"FPSplit\":0.0,\"FASplit\":1.0}]}",
                            Priority = 0,
                            Type     = RuleType.VendorPayment
                        }
                    }
                }
            });

            EFContext.Update(vendor1);
            EFContext.SaveChanges();
            await ReindexItem <VendorSearchItem, Vendor>(vendor1, Constants.ElasticSearchIndices.VendorIndexName);

            const int    expectedCount        = 1;
            const string expectedBudgetRegion = plugins.Constants.BudgetRegion.China;
            // Act
            var query = new VendorQuery
            {
                AutoComplete = false,
                PageNumber   = 1,
                Limit        = 20,
                BudgetRegion = expectedBudgetRegion,
                Category     = plugins.Constants.VendorCategory.UsageBuyoutContract
            };
            var result = await _vendorSearchService.SearchVendors(query);

            // Assert
            result.Count.Should().Be(expectedCount);
            var expectedVendor = result.Items.First();

            expectedVendor.VendorCategoryModels.Count.Should().Be(1);
            expectedVendor.VendorCategoryModels.First().RuleBudgetRegions.Should().Contain(expectedBudgetRegion);
        }
        public async Task UpdateTechnicalFeeLineItem(Guid costId, Guid latestRevisionId)
        {
            var currentRevision = await _efContext.CostStageRevision
                                  .Include(x => x.Approvals)
                                  .ThenInclude(x => x.ApprovalMembers)
                                  .ThenInclude(x => x.CostUser)
                                  .ThenInclude(x => x.UserBusinessRoles)
                                  .ThenInclude(a => a.BusinessRole)
                                  .FirstOrDefaultAsync(x => x.Id == latestRevisionId);

            var costConsultantApprovals = currentRevision.Approvals?.Where(x =>
                                                                           x.Type == ApprovalType.IPM && x.ValidBusinessRoles?.Contains(Constants.BusinessRole.CostConsultant) == true)
                                          .ToList();

            var costConsultantSelected = costConsultantApprovals
                                         .Any(x => x.ApprovalMembers
                                              .Any(m => m.CostUser.UserBusinessRoles.Any(a => a.BusinessRole.Value == Constants.BusinessRole.CostConsultant)));
            var costLineItems = await _efContext.CostLineItem.Where(x => x.CostStageRevisionId == latestRevisionId).ToListAsync();

            var techFeeLineItem = costLineItems.FirstOrDefault(x => x.Name == Constants.CostSection.TechnicalFee);

            if (techFeeLineItem != null)
            {
                // tech fee is applicable, let's see if we need to recalculate the value
                if (costConsultantSelected && costConsultantApprovals.Any())
                {
                    // currently there is a cost consultant selected

                    var fee = await GetTechnicalFee(costId);

                    if (fee != null && fee.ConsultantRate != 0)
                    {
                        // we got a CC rate, but we only save it if current value is 0
                        if (techFeeLineItem.ValueInDefaultCurrency == 0)
                        {
                            // calculate values based on FX rate
                            var feeCurrency = await _currencyService.GetCurrency(fee.CurrencyCode);

                            if (feeCurrency != null && !feeCurrency.DefaultCurrency)
                            {
                                // only calculate fx rate for foreign currencies
                                var defaultFxRate = await _costExchangeRateService.GetExchangeRateByCurrency(costId, feeCurrency.Id);

                                techFeeLineItem.ValueInDefaultCurrency = fee.ConsultantRate * defaultFxRate.Rate;
                            }
                            else
                            {
                                techFeeLineItem.ValueInDefaultCurrency = fee.ConsultantRate;
                            }

                            var localCurrency = await _currencyService.GetCurrency(techFeeLineItem.LocalCurrencyId);

                            if (localCurrency != null && !localCurrency.DefaultCurrency)
                            {
                                var localFxRate = await _costExchangeRateService.GetExchangeRateByCurrency(costId, techFeeLineItem.LocalCurrencyId);

                                techFeeLineItem.ValueInLocalCurrency = techFeeLineItem.ValueInDefaultCurrency / localFxRate.Rate; // reverse conversion
                            }
                            else
                            {
                                techFeeLineItem.ValueInLocalCurrency = techFeeLineItem.ValueInDefaultCurrency;
                            }


                            _efContext.Update(techFeeLineItem);
                            await _efContext.SaveChangesAsync();
                        }
                    }
                }
                else if (techFeeLineItem.ValueInDefaultCurrency > 0)
                {
                    // cost consultant is not selected, but there is a fee - let's set the rate to 0 if previously we don't have any approved revisions/stages with tech fee

                    var previousRevision = await _costStageRevisionService.GetPreviousRevision(currentRevision.Id);

                    if (previousRevision != null)
                    {
                        var previousCostLineItems = await _costStageRevisionService.GetCostLineItems(previousRevision.Id);

                        var prevTechFeeLineItem = previousCostLineItems.FirstOrDefault(x => x.Name == Constants.CostSection.TechnicalFee);

                        if (prevTechFeeLineItem == null || prevTechFeeLineItem.ValueInDefaultCurrency == 0)
                        {
                            // we don't have a value - let's set it to 0
                            await SetToZeroAndSave(techFeeLineItem);
                        }
                    }
                    else
                    {
                        // we don't have a previous review - let's set it to 0
                        await SetToZeroAndSave(techFeeLineItem);
                    }
                }
            }
        }
Пример #28
0
        public async Task Run(UploadOriginData originData)
        {
            if (originData.uploadEntitys.Count <= 0)
            {
                return;
            }
            try
            {
                using var dbContext = new EFContext();
                using var trans     = await dbContext.Database.BeginTransactionAsync();

                try
                {
                    //UPLogger.Show("进来了,数据是" + originData.uploadEntitys.Count + "个。");
                    foreach (var Clight in originData.uploadEntitys)//针对多通道进行
                    {
                        var uploadPropertys = Clight.Value;
                        if (uploadPropertys.ContainsKey(NBRAC.DeviceType))
                        {
                            return;
                        }
                        //if (!uploadPropertys.ContainsKey(NBRAC.DimmingFeature)) return;
                        //logger.Info("进来了哦");

                        await Task.Delay(1000);

                        var Now = DateTime.Now;
                        //经纬度
                        double longitude = 0;
                        double latitude  = 0;

                        TNL_History_Summary summary = new TNL_History_Summary();
                        summary.Partition_ID = long.Parse(Now.ToString("yyyyMMddHHmmss"));

                        var keyObj = await DataBaseHelper.GetKey("TNL_History_Summary", "History_ID");

                        if (keyObj != 0)
                        {
                            summary.History_ID = keyObj;
                        }
                        else
                        {
                            summary.History_ID = 1000001;
                        }

                        var DeviceAddress = string.Join("", from d in originData.addressDomain select d.ToString("X")).PadLeft(12, '0');
                        var DeviceInfo    = await(from d in dbContext.TNL_DeviceInfos
                                                  where d.DeviceAddress == DeviceAddress
                                                  select d).AsNoTracking().FirstOrDefaultAsync();
                        var lightInfo = await(from d in dbContext.TNL_TunnelLights
                                              where d.LightPhysicalAddress_TX == DeviceAddress &&
                                              d.ChannelNumber == Clight.Key
                                              select d).AsNoTracking().FirstOrDefaultAsync();
                        //var lightInfo = await dbContext.TNL_TunnelLights
                        // .AsNoTracking()
                        // .FirstOrDefaultAsync(d => d.IMEI.Contains(DeviceAddress));
                        if (lightInfo == null)
                        {
                            SqlParameter[] Param =
                            {
                                new SqlParameter("@P_GatewayPAddress", System.Data.SqlDbType.VarChar)
                                {
                                    Value = "1"
                                },
                                new SqlParameter("@P_LightPAddress",   System.Data.SqlDbType.VarChar)
                                {
                                    Value = DeviceAddress
                                },
                                new SqlParameter("@P_longitude",       System.Data.SqlDbType.Float)
                                {
                                    Value = 0
                                },
                                new SqlParameter("@P_latitude",        System.Data.SqlDbType.Float)
                                {
                                    Value = 0
                                },
                                new SqlParameter("@P_RecDateTime",     System.Data.SqlDbType.DateTime)
                                {
                                    Value = Now
                                },
                                new SqlParameter("@P_ChannelNumber",   System.Data.SqlDbType.Int)
                                {
                                    Value = Clight.Key
                                },
                                new SqlParameter("@P_LightID",         System.Data.SqlDbType.Int)
                                {
                                    Value = 0,                         Direction = ParameterDirection.Output
                                },
                                new SqlParameter("@P_Msg",             System.Data.SqlDbType.VarChar)
                                {
                                    Value = string.Empty,              Direction = ParameterDirection.Output
                                },
                            };
                            var result = await dbContext.Database.ExecuteSqlCommandAsync("GPS_InsertDataDoubleLight @P_GatewayPAddress,@P_LightPAddress,@P_longitude,@P_latitude,@P_RecDateTime,@P_ChannelNumber,@P_LightID OUTPUT,@P_Msg OUTPUT", Param);

                            int lightid = Convert.ToInt32(Param[6].Value);
                            lightInfo = await dbContext.TNL_TunnelLights.AsNoTracking().FirstOrDefaultAsync(d => d.TunnelLight_ID == lightid);

                            //UPLogger.Show($"light发现了是空的:{lightInfo.TunnelLight_ID}");
                        }
                        //logger.Info("lightInfo");

                        if (DeviceInfo == null)//如果没发现设备信息
                        {
                            DeviceInfo = new TNL_DeviceInfo();
                            DeviceInfo.TunnelLight_ID = lightInfo.TunnelLight_ID;
                            DeviceInfo.DeviceAddress  = DeviceAddress;
                            //originData
                            //DeviceInfo.IMEI
                            DeviceInfo.LocalDate     = Now;
                            DeviceInfo.SampTime      = Now;
                            DeviceInfo.ChannelNumber = uploadPropertys[NBRAC.DimmingFeature].ChannelNumber;
                            await dbContext.TNL_DeviceInfos.AddAsync(DeviceInfo);
                        }
                        else
                        {
                            lightInfo.IMEI  = DeviceInfo.IMEI;
                            lightInfo.IMSI  = DeviceInfo.IMSI;
                            lightInfo.ICCID = DeviceInfo.ICCID;
                        }

                        //logger.Info("DeviceInfo");
                        #region 插入历史信息表
                        if (lightInfo != null)
                        {
                            summary.TunnelLight_ID = lightInfo.TunnelLight_ID;
                        }
                        else
                        {
                            summary.TunnelLight_ID = 0; //没找到这个灯具:DeviceInfo被删除、单灯表被删除
                        }
                        summary.SampTime_DT = Now;
                        //TNL_DeviceInfo DeviceInfo = new TNL_DeviceInfo();
                        //if (lightInfo != null)
                        //{
                        //    DeviceInfo = await dbContext.TNL_DeviceInfos
                        //                          .AsNoTracking()
                        //                          .FirstOrDefaultAsync(d => d.IMEI == lightInfo.IMEI);
                        //}
                        summary.AlmLevel_ID = 0;
                        if (uploadPropertys.ContainsKey(NBRAC.DimmingFeature))
                        {
                            summary.DimmingFeatureValue_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                              from d in uploadPropertys[NBRAC.DimmingFeature].MemeroyData
                                                                                              select d.ToString("X2")), NumberStyles.HexNumber) / 2.55, 0);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.VoltageFeature))
                        {
                            summary.VoltageFeatureValue_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                              from d in uploadPropertys[NBRAC.VoltageFeature].MemeroyData
                                                                                              select d.ToString("X2")), NumberStyles.HexNumber) * 0.1, 2);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.CurrentFeature))
                        {
                            summary.CurrentFeatureValue_NR = int.Parse(string.Join(string.Empty,
                                                                                   from d in uploadPropertys[NBRAC.CurrentFeature].MemeroyData
                                                                                   select d.ToString("X2")), NumberStyles.HexNumber);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.PowerFeature))
                        {
                            summary.PowerFeatureValue_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                            from d in uploadPropertys[NBRAC.PowerFeature].MemeroyData
                                                                                            select d.ToString("X2")), NumberStyles.HexNumber) * 0.1, 2);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.PowerFactor))
                        {
                            summary.PowerFactor_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                      from d in uploadPropertys[NBRAC.PowerFactor].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber) * 0.1, 2);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.PowerConsumption))
                        {
                            summary.PowerConsumption_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                           from d in uploadPropertys[NBRAC.PowerConsumption].MemeroyData
                                                                                           select d.ToString("X2")), NumberStyles.HexNumber) * 0.1, 2);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.WorkingTimeInMinute))
                        {
                            summary.WorkingTimeInMinute_NR = int.Parse(string.Join(string.Empty,
                                                                                   from d in uploadPropertys[NBRAC.WorkingTimeInMinute].MemeroyData
                                                                                   select d.ToString("X2")), NumberStyles.HexNumber);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.Temperature))
                        {
                            summary.Temperature_NR = Math.Round(int.Parse(string.Join(string.Empty,
                                                                                      from d in uploadPropertys[NBRAC.Temperature].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber) * 0.1, 2);
                        }
                        if (uploadPropertys.ContainsKey(NBRAC.LuminousIntensity))
                        {
                            summary.LuminousIntensity_NR = int.Parse(string.Join(string.Empty,
                                                                                 from d in uploadPropertys[NBRAC.LuminousIntensity].MemeroyData
                                                                                 select d.ToString("X2")), NumberStyles.HexNumber);
                        }

                        if (uploadPropertys.ContainsKey(NBRAC.GPSInfo))//GPSInfo
                        {
                            var GpsHex = string.Join(string.Empty, from d in uploadPropertys[NBRAC.GPSInfo].MemeroyData
                                                     select d.ToString("X2"));
                            var longitudeHex = GpsHex.Substring(0, 8);
                            var latitudeHex  = GpsHex.Substring(8);

                            longitude = int.Parse(longitudeHex, NumberStyles.HexNumber) / 1000000.0;
                            latitude  = int.Parse(latitudeHex, NumberStyles.HexNumber) / 1000000.0;
                            if (Math.Abs(longitude) > 0.01 && Math.Abs(latitude) > 0.01)//绝对值有效,才存入经纬度信息里
                            {
                                var pointInfo = Led.Tools.MapHelper.Nema2Google(new MapHelper.PointInfo(longitude, latitude));

                                //pointInfo.Lat = Math.Round(pointInfo.Lat, 8);
                                //pointInfo.Lon = Math.Round(pointInfo.Lon, 8);
                                lightInfo.Longitude  = pointInfo.Lon;
                                lightInfo.Longitude2 = pointInfo.Lon;
                                lightInfo.Latitude   = pointInfo.Lat;
                                lightInfo.Latitude2  = pointInfo.Lat;
                                summary.GpsInfo      = pointInfo.Lon + "," + pointInfo.Lat;
                            }
                        }
                        dbContext.Update(lightInfo);
                        summary.VehicleFlow_NR     = 0;
                        summary.VehicleSpeed_NR    = 0;
                        summary.FirmwareVersion_NR = 0;
                        summary.ChannelNumber      = uploadPropertys[NBRAC.DimmingFeature].ChannelNumber;
                        summary.LocalDate          = Now;
                        //summary.TimeZone_CD = new object();
                        //summary.LightningCount = new object();
                        //summary.IsDay = new object();
                        summary.DataSource = 0;
                        summary.Address    = null;
                        //summary.Signal_NR = new object();
                        summary.FirmwareVersion_NR = int.Parse((DeviceInfo.Version?.Replace(".", string.Empty) ?? "0"));
                        summary.RemoteEndPoint     = DeviceInfo.IP;
                        summary.Version            = DeviceInfo.Version;
                        summary.IMEI   = DeviceInfo.IMEI;
                        summary.IMSI   = DeviceInfo.IMSI;
                        summary.ICCID  = DeviceInfo.ICCID;
                        summary.bandNo = int.Parse(DeviceInfo.BAND ?? "0");
                        //summary.GpsInfo = DeviceInfo.GPSInfo;
                        summary.State      = 0;
                        summary.UploadData = DataHelper.BytesToHexStr(originData.OriginData);
                        //summary.CSQ = ;
                        await dbContext.TNL_History_Summarys.AddAsync(summary);

                        //UPLogger.Show($"历史表走完!");

                        //logger.Info("TNL_History_Summarys");
                        #endregion

                        #region 插入当前状态表
                        var lightalm = await dbContext.TNL_TunnelLightAlms.FirstOrDefaultAsync(d => d.TunnelLight_ID == summary.TunnelLight_ID);

                        //lightalm.TunnelLight_ID = summary.TunnelLight_ID;
                        bool Added = lightalm != null ? false : true;
                        if (Added)
                        {
                            lightalm = new TNL_TunnelLightAlm();
                        }
                        lightalm.TunnelLight_ID         = lightInfo.TunnelLight_ID;
                        lightalm.AlmLevel_ID            = summary.AlmLevel_ID;
                        lightalm.DimmingFeatureValue_NR = summary.DimmingFeatureValue_NR;
                        lightalm.CurrentFeatureValue_NR = summary.CurrentFeatureValue_NR;
                        lightalm.VoltageFeatureValue_NR = summary.VoltageFeatureValue_NR;
                        lightalm.PowerFeatureValue_NR   = summary.PowerFeatureValue_NR;
                        lightalm.LuminousIntensity_NR   = summary.LuminousIntensity_NR;
                        lightalm.Temperature_NR         = summary.Temperature_NR;
                        lightalm.PowerConsumption_NR    = summary.PowerConsumption_NR;
                        lightalm.WorkingTimeInMinute_NR = summary.WorkingTimeInMinute_NR;
                        lightalm.VehicleFlow_NR         = summary.VehicleFlow_NR;
                        lightalm.VehicleSpeed_NR        = summary.VehicleSpeed_NR;
                        lightalm.FirmwareVersion_NR     = summary.FirmwareVersion_NR;
                        lightalm.SampTime_DT            = summary.SampTime_DT;
                        lightalm.PowerFactor_NR         = summary.PowerFactor_NR;
                        lightalm.ChannelNumber          = summary.ChannelNumber;
                        lightalm.LocalDate      = summary.LocalDate;
                        lightalm.DataSource     = summary.DataSource;
                        lightalm.RemoteEndPoint = summary.RemoteEndPoint;
                        lightalm.Signal_NR      = summary.Signal_NR;
                        lightalm.Version        = summary.Version;
                        //lightalm.IMEI = summary.IMEI;
                        //lightalm.IMSI = summary.IMSI;
                        //lightalm.ICCID = summary.ICCID;
                        lightalm.bandNo = summary.bandNo;
                        lightalm.State  = summary.State;
                        if (Math.Abs(longitude) > 0.01 && Math.Abs(latitude) > 0.01)//绝对值有效,才存入经纬度信息里
                        {
                            lightalm.GpsInfo = summary.GpsInfo;
                        }
                        //lightalm.TimePlan = summary.time;
                        //lightalm.PhotoCell = summary.poho;
                        lightalm.InspectSuccess_DT = Now;
                        lightalm.IsDay             = summary.IsDay;
                        lightalm.LightningCount    = summary.LightningCount;
                        //lightalm.upUID = summary.upk;
                        lightalm.CSQ = summary.CSQ;
                        if (Added)
                        {
                            dbContext.Add(lightalm);
                        }
                        else
                        {
                            dbContext.Update(lightalm);
                        }
                        //logger.Info("lightalm");
                        #endregion

                        #region 插入告警数据
                        if (uploadPropertys.ContainsKey(NBRAC.AlarmInfo))
                        {
                            TNL_AlarmInfo alarmInfo    = new TNL_AlarmInfo();
                            var           hexAlarmInfo = string.Join(string.Empty,
                                                                     from d in uploadPropertys[NBRAC.AlarmInfo].MemeroyData
                                                                     select d.ToString());
                            alarmInfo.AlarmInfo = int.Parse(hexAlarmInfo, NumberStyles.HexNumber).ToString().PadLeft(8, '0');
                            char[] alarmsstatus = Convert.ToString(int.Parse(hexAlarmInfo), 2)
                                                  .PadLeft(30, '0')
                                                  .Reverse()
                                                  .ToArray();
                            //var alarms = uploadPropertys[NBRAC.AlarmInfo].MemeroyData;
                            //char[] alarmsstatus = alarmInfo.AlarmInfo.Reverse().ToArray();
                            if (alarmsstatus != null && alarmsstatus.Length > 5)
                            {
                                alarmInfo.Alarm0 = int.Parse(alarmsstatus[NBRAC.Alarm0].ToString());
                                alarmInfo.Alarm1 = int.Parse(alarmsstatus[NBRAC.Alarm1].ToString());
                                alarmInfo.Alarm2 = int.Parse(alarmsstatus[NBRAC.Alarm2].ToString());
                                alarmInfo.Alarm3 = int.Parse(alarmsstatus[NBRAC.Alarm3].ToString());
                                alarmInfo.Alarm4 = int.Parse(alarmsstatus[NBRAC.Alarm4].ToString());
                                alarmInfo.Alarm5 = int.Parse(alarmsstatus[NBRAC.Alarm5].ToString());
                                alarmInfo.Alarm6 = int.Parse(alarmsstatus[NBRAC.Alarm6].ToString());
                            }

                            if (alarmInfo.Alarm0 != 0 ||
                                alarmInfo.Alarm1 != 0 ||
                                alarmInfo.Alarm2 != 0 ||
                                alarmInfo.Alarm3 != 0 ||
                                alarmInfo.Alarm4 != 0 ||
                                alarmInfo.Alarm5 != 0 ||
                                alarmInfo.Alarm6 != 0)
                            {
                                alarmInfo.DeviceAddress          = DeviceAddress;
                                alarmInfo.TunnelLight_ID         = lightInfo.TunnelLight_ID;
                                alarmInfo.DimmingFeatureValue_NR = summary.DimmingFeatureValue_NR;
                                alarmInfo.VoltageFeatureValue_NR = summary.VoltageFeatureValue_NR;
                                alarmInfo.CurrentFeatureValue_NR = summary.CurrentFeatureValue_NR;
                                alarmInfo.PowerFeatureValue_NR   = summary.PowerFeatureValue_NR;
                                alarmInfo.PowerFactor            = summary.PowerFactor_NR;
                                alarmInfo.PowerConsumption_NR    = summary.PowerConsumption_NR;
                                alarmInfo.WorkingTimeInMinute_NR = summary.WorkingTimeInMinute_NR;
                                alarmInfo.Temperature_NR         = summary.Temperature_NR;
                                alarmInfo.WorkingTimeInMinute_NR = summary.WorkingTimeInMinute_NR;
                                alarmInfo.LuminousIntensity_NR   = summary.LuminousIntensity_NR;
                                alarmInfo.LocalDate = Now;
                                alarmInfo.SampTime  = Now;
                                await dbContext.TNL_AlarmInfos.AddAsync(alarmInfo);
                            }
                            //UPLogger.Show($"告警走完!");
                            //logger.Info("alarmInfo");
                        }
                        #endregion
                    }
                    await dbContext.SaveChangesAsync();

                    await trans.CommitAsync();
                }
                catch
                {
                    await trans.RollbackAsync();

                    throw;
                }
            }
            catch (Exception ex)
            {
                //logger.Info(ex.Message);
                logger.Error(this.GetType().FullName + " " + ex.ToString());
                throw;
            }
        }
Пример #29
0
        public async Task Run(UploadOriginData originData)
        {
            //首先判断是否存在数据包体,要不浪费
            if (originData.uploadEntitys.Count <= 0) return;
            using var dbContext = new EFContext();
            using var trans = await dbContext.Database.BeginTransactionAsync();
            foreach (var Clight in originData.uploadEntitys)//针对多通道进行
            {
                var uploadPropertys = Clight.Value;
                //关键判断是否存在IMEI号,如果存在,则认为是通电数据
                if (!uploadPropertys.ContainsKey(NBRAC.DeviceType)) return;
                try
                {
                    var upets = uploadPropertys;
                    //如果组织信息变动,则发送
                    TransmitData transmitData = null;
                    var NowDate = DateTime.Now;
                    //经纬度
                    double longitude = 0;
                    double latitude = 0;
                    //物理地址
                    var PhysicalAddress = string.Join(string.Empty, from d in originData.addressDomain
                                                                    select d.ToString("X")).PadLeft(12, '0');
                    #region 设备信息表
                    #region 获取设备信息主表
                    //设备表
                    TNL_DeviceInfo OrigindeviceInfo = dbContext.TNL_DeviceInfos.AsNoTracking().FirstOrDefault(d => d.DeviceAddress == PhysicalAddress);
                    //单灯表
                    TNL_TunnelLight light = await dbContext.TNL_TunnelLights
                                                           .AsNoTracking()
                                                           .FirstOrDefaultAsync(d => d.LightPhysicalAddress_TX == PhysicalAddress);
                    #endregion
                    //只需要找我要的寄存器地址就行了
                    if (OrigindeviceInfo == null)
                        OrigindeviceInfo = new TNL_DeviceInfo();
                    if (upets.ContainsKey(NBRAC.DeviceType))//DeviceType
                    {
                        OrigindeviceInfo.DeviceType = string.Join(string.Empty, from d in upets[NBRAC.DeviceType].MemeroyData
                                                                                select d.ToString("X2"));
                    }
                    if (upets.ContainsKey(NBRAC.HDVersion))//HDVersion
                    {
                        //OrigindeviceInfo.HDVersion = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.HDVersion].MemeroyData
                        //                                                                 select d.ToString("X2")), NumberStyles.HexNumber)
                        //                                                           .ToString();
                        var HDVersionHex = upets[NBRAC.HDVersion].MemeroyData;
                        OrigindeviceInfo.HDVersion = HDVersionHex[0] + "." + HDVersionHex[1];
                    }
                    if (upets.ContainsKey(NBRAC.Version))//Version
                    {
                        var VersionHex = upets[NBRAC.Version].MemeroyData;
                        OrigindeviceInfo.Version = VersionHex[0] + "." + VersionHex[1];
                        //OrigindeviceInfo.Version = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Version].MemeroyData
                        //                                                               select d.ToString("X2")), NumberStyles.HexNumber)
                        //                                                           .ToString();

                    }
                    if (upets.ContainsKey(NBRAC.GPSInfo))//GPSInfo
                    {
                        //OrigindeviceInfo.GPSInfo = string.Join(string.Empty, from d in upets[NBRAC.GPSInfo].MemeroyData
                        //                                                     select d.ToString("X2"));
                        var GpsHex = string.Join(string.Empty, from d in uploadPropertys[NBRAC.GPSInfo].MemeroyData
                                                               select d.ToString("X2"));
                        try
                        {

                            var longitudeHex = GpsHex.Substring(0, 8);
                            var latitudeHex = GpsHex.Substring(8);
                            longitude = int.Parse(longitudeHex, NumberStyles.HexNumber) / 1000000.0;
                            latitude = int.Parse(latitudeHex, NumberStyles.HexNumber) / 1000000.0;
                            if (Math.Abs(longitude) > 0.01 && Math.Abs(latitude) > 0.01)//绝对值有效,才存入经纬度信息里
                            {
                                var pointInfo = Led.Tools.MapHelper.Nema2Google(new MapHelper.PointInfo(longitude, latitude));
                                //pointInfo.Lat = Math.Round(pointInfo.Lat, 8);
                                //pointInfo.Lon = Math.Round(pointInfo.Lon, 8);
                                OrigindeviceInfo.GPSInfo = pointInfo.Lon + "," + pointInfo.Lat;
                            }
                        }
                        catch (Exception)
                        { }

                    }
                    if (upets.ContainsKey(NBRAC.ReportInterval))//ReportInterval
                    {
                        OrigindeviceInfo.ReportInterval = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.ReportInterval].MemeroyData
                                                                                              select d.ToString()));
                    }
                    if (upets.ContainsKey(NBRAC.TAVersion))//TAVersion
                    {
                        OrigindeviceInfo.TAVersion = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.TAVersion].MemeroyData
                                                                                         select d.ToString("X2")), NumberStyles.HexNumber)
                                                                                  .ToString();
                    }
                    if (upets.ContainsKey(NBRAC.IMEI))//IMEI
                    {
                        OrigindeviceInfo.IMEI = Encoding.ASCII.GetString(upets[NBRAC.IMEI].MemeroyData);
                    }
                    if (upets.ContainsKey(NBRAC.IMSI))//IMSI
                    {
                        OrigindeviceInfo.IMSI = Encoding.ASCII.GetString(upets[NBRAC.IMSI].MemeroyData);
                    }
                    if (upets.ContainsKey(NBRAC.ICCID))//ICCID
                    {
                        OrigindeviceInfo.ICCID = Encoding.ASCII.GetString(upets[NBRAC.ICCID].MemeroyData);
                    }
                    if (upets.ContainsKey(NBRAC.BAND))//BAND
                    {
                        OrigindeviceInfo.BAND = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.BAND].MemeroyData
                                                                                    select d.ToString("X2")), NumberStyles.HexNumber)
                                                        .ToString();
                    }
                    if (upets.ContainsKey(NBRAC.CELLID))//CELLID
                    {
                        OrigindeviceInfo.CELLID = string.Join(string.Empty, from d in upets[NBRAC.CELLID].MemeroyData
                                                                            select d.ToString("X2"));
                    }
                    if (upets.ContainsKey(NBRAC.RSSI))//RSSI
                    {
                        OrigindeviceInfo.RSSI = string.Join(string.Empty, from d in upets[NBRAC.RSSI].MemeroyData
                                                                          select d.ToString("X2"));
                    }
                    if (upets.ContainsKey(NBRAC.RSRP))//RSRP
                    {
                        OrigindeviceInfo.RSRP = string.Join(string.Empty, from d in upets[NBRAC.RSRP].MemeroyData
                                                                          select d.ToString("X2"));
                    }
                    if (upets.ContainsKey(NBRAC.UTC))//UTC
                    {
                        OrigindeviceInfo.UTC = string.Join(string.Empty, from d in upets[NBRAC.UTC].MemeroyData
                                                                         select d.ToString("X2"));
                    }
                    if (upets.ContainsKey(NBRAC.APN))//APN
                    {
                        OrigindeviceInfo.APN = Encoding.ASCII.GetString(upets[NBRAC.APN].MemeroyData);
                    }
                    if (upets.ContainsKey(NBRAC.IP))//Ip
                    {

                        OrigindeviceInfo.IP = Encoding.ASCII.GetString(upets[NBRAC.IP].MemeroyData);
                        //deviceInfo.IP = string.Join(string.Empty, from d in upets[NBRAC.IP].MemeroyData
                        //                                          select d.ToString());
                    }
                    if (upets.ContainsKey(NBRAC.Server))//Server
                    {
                        OrigindeviceInfo.Server = string.Join(string.Empty, from d in upets[NBRAC.Server].MemeroyData
                                                                            select d.ToString() + ".").TrimEnd('.');
                    }
                    if (upets.ContainsKey(NBRAC.Port))//Port
                    {
                        OrigindeviceInfo.Port = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Port].MemeroyData
                                                                                    select d.ToString("X2")), NumberStyles.HexNumber)
                                                                              .ToString();

                    }
                    if (upets.ContainsKey(NBRAC.Group0))//Group0
                    {
                        OrigindeviceInfo.Group0 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group0].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group1))//Group1
                    {
                        OrigindeviceInfo.Group1 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group1].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group2))//Group2
                    {
                        OrigindeviceInfo.Group2 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group2].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group3))//Group3
                    {
                        OrigindeviceInfo.Group3 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group3].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group4))//Group4
                    {
                        OrigindeviceInfo.Group4 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group4].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group5))//Group5
                    {
                        OrigindeviceInfo.Group5 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group5].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group6))//Group6
                    {
                        OrigindeviceInfo.Group6 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group6].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (upets.ContainsKey(NBRAC.Group7))//Group7
                    {
                        OrigindeviceInfo.Group7 = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.Group7].MemeroyData
                                                                                      select d.ToString("X2")), NumberStyles.HexNumber);
                    }
                    if (originData.hasAddress)
                    {
                        OrigindeviceInfo.DeviceAddress = string.Join(string.Empty, from d in originData.addressDomain
                                                                                   select d.ToString("X")).PadLeft(12, '0');
                    }

                    //OrigindeviceInfo.ChannelNumber = uploadPropertys[NBRAC.IMEI].ChannelNumber;
                    OrigindeviceInfo.ChannelNumber = 0;
                    OrigindeviceInfo.LocalDate = NowDate;
                    OrigindeviceInfo.SampTime = NowDate;
                    if (OrigindeviceInfo.ID > 0)
                    {
                        #region 弃用
                        //deviceInfo.LocalDate = NowDate;
                        //deviceInfo.SampTime = NowDate;
                        //deviceInfo.DeviceType = OrigindeviceInfo.DeviceType;
                        //deviceInfo.HDVersion = OrigindeviceInfo.HDVersion;
                        //deviceInfo.Version = OrigindeviceInfo.Version;
                        //if (Math.Abs(longitude) > 0.01 && Math.Abs(latitude) > 0.01)//绝对值有效,才存入经纬度信息里
                        //    deviceInfo.GPSInfo = OrigindeviceInfo.GPSInfo;
                        //deviceInfo.ReportInterval = OrigindeviceInfo.ReportInterval;
                        //deviceInfo.TAVersion = OrigindeviceInfo.TAVersion;
                        //deviceInfo.IMEI = OrigindeviceInfo.IMEI;
                        //deviceInfo.IMSI = OrigindeviceInfo.IMSI;
                        //deviceInfo.ICCID = OrigindeviceInfo.ICCID;
                        //deviceInfo.BAND = OrigindeviceInfo.BAND;
                        //deviceInfo.CELLID = OrigindeviceInfo.CELLID;
                        //deviceInfo.RSSI = OrigindeviceInfo.RSSI;
                        //deviceInfo.RSRP = OrigindeviceInfo.RSRP;
                        //deviceInfo.UTC = OrigindeviceInfo.UTC;
                        //deviceInfo.APN = OrigindeviceInfo.APN;
                        //deviceInfo.IP = OrigindeviceInfo.IP;
                        //deviceInfo.Server = OrigindeviceInfo.Server;
                        //deviceInfo.Port = OrigindeviceInfo.Port;
                        //deviceInfo.DeviceAddress = OrigindeviceInfo.DeviceAddress;
                        //deviceInfo.ChannelNumber = OrigindeviceInfo.ChannelNumber;
                        //deviceInfo.Group0 = OrigindeviceInfo.Group0;
                        //deviceInfo.Group1 = OrigindeviceInfo.Group1;
                        //deviceInfo.Group2 = OrigindeviceInfo.Group2;
                        //deviceInfo.Group3 = OrigindeviceInfo.Group3;
                        //deviceInfo.Group4 = OrigindeviceInfo.Group4;
                        //deviceInfo.Group5 = OrigindeviceInfo.Group5;
                        //deviceInfo.Group6 = OrigindeviceInfo.Group6;
                        //deviceInfo.Group7 = OrigindeviceInfo.Group7;
                        #endregion

                        dbContext.TNL_DeviceInfos.Update(OrigindeviceInfo);
                    }
                    else
                    {
                        await dbContext.TNL_DeviceInfos.AddAsync(OrigindeviceInfo);
                    }
                    #endregion

                    #region 单灯表
                    var LightType = 0;//默认单灯
                    if (upets.ContainsKey(NBRAC.LightType))//单双灯类型
                    {
                        var lightTypeNumber = int.Parse(string.Join(string.Empty, from d in upets[NBRAC.LightType].MemeroyData
                                                                                  select d.ToString("X2")), NumberStyles.HexNumber);
                        if (lightTypeNumber > 1)
                        {
                            LightType = 1;//双灯
                        }
                    }
                    if (light == null)
                    {
                        light = new TNL_TunnelLight();
                        #region 赋值单灯信息
                        //var lightKey = await DBHelper.GetDataKey("TNL_TunnelLight", "TunnelLight_ID");
                        //if (lightKey != 0) light.TunnelLight_ID = lightKey;
                        //else light.TunnelLight_ID = 1000001;
                        //light.TunnelLight_ID = 0;
                        ////light.TunnelSection_ID = 1;
                        ////light.TunnelGateway_ID = 0;
                        ////light.Tunnel_ID = 0;
                        ////if (originData.hasAddress)
                        ////{
                        ////    light.LightPhysicalAddress_TX = PhysicalAddress.PadLeft(12, '0');
                        ////}
                        ////else
                        ////{
                        ////    light.LightPhysicalAddress_TX = "000000000000";
                        ////}
                        ////light.LightLocationNumber_NR = 0;
                        //light.LightType_TX = null;
                        //light.PowerType_TX = null;
                        //light.VoltageHighValue_NR = null;
                        //light.VoltageLowValue_NR = null;
                        //light.CurrentHighValue_NR = null;
                        //light.CurrentLowValue_NR = null;
                        //light.Longitude = null;
                        //light.Latitude = null;
                        ////light.LightUsage_NR = 2;
                        //light.Mileage_TX = null;
                        //light.PowerModel_TX = null;
                        //light.PowerManufacturer_TX = null;
                        //light.LightModel_TX = null;
                        //light.LightManufacturer_TX = null;
                        ////light.GroupNumber_TX = ",,";
                        ////light.LightFunction_NR = 0;
                        ////light.LightSource_NR = 0;
                        ////light.LampType_NR = 0;
                        //light.PoleNumber_TX = null;
                        //light.PoleManufacturers_TX = null;
                        //light.FlangeSize_TX = null;
                        //light.BasicFrameSize_TX = null;
                        //light.CableType_NR = null;
                        //light.PowerPhase_NR = null;
                        ////light.DimmingFactor_NR = 1;
                        ////light.DefaultDimmingValue_NR = 100;
                        ////light.PowerOnDimmingValue_NR = 100;
                        ////light.MaximumDimmingValue_NR = 100;
                        ////light.MinimumDimmingValue_NR = 0;
                        //light.PowerGroundingType_NR = null;
                        //light.NorminalPower_NR = null;
                        //light.LightColor_NR = null;
                        //light.PoleHieght_NR = null;
                        //light.InstallationDate_DT = NowDate;
                        ////light.Active_YN = '1';
                        ////light.EnablePIRFunction_YN = '0';
                        ////light.PIRLastTimeMinutesOfDimming_NR = 30;
                        ////light.PIRRestoreTime_NR = 5;
                        ////light.PIRGroupNumber_NR = 1;
                        ////light.PIRIdleDimmingValue_NR = 30;
                        ////light.PIRDimmingValue_NR = 100;
                        ////light.PIRTTL_NR = 0;
                        ////light.LightConfig_ID = 0;
                        ////light.LightTimeControl_ID = 0;
                        //light.Longitude2 = null;
                        //light.Latitude2 = null;
                        //light.StorageInterval_NR = null;
                        //light.SamplingInterval_NR = null;
                        ////light.PIRSensorPlan_ID = 0;
                        //light.OID = null;
                        ////light.SampleDate = NowDate;
                        //light.RecDateTime = NowDate;
                        //light.LastUID = null;
                        //light.InfoLink = null;
                        //light.TemperatureHigh_NR = null;
                        //light.TemperatureLow_NR = null;
                        ////light.IsIot = 1;
                        ////light.IMEI = OrigindeviceInfo.IMEI;
                        ////light.IMSI = OrigindeviceInfo.IMSI;
                        ////light.ICCID = OrigindeviceInfo.ICCID;
                        //light.DeviceId = deviceEntity.ID;
                        //light.Scheme_ID = null;
                        ////light.ChannelNumber = upets[NBRAC.IMEI].ChannelNumber;
                        //light.RTCTimeDimmingPlan_ID = null;
                        //await dbContext.AddAsync(light);
                        #endregion

                        SqlParameter[] Param =
                      {
                        new SqlParameter("@P_GatewayPAddress", System.Data.SqlDbType.VarChar){ Value="1"},
                        new SqlParameter("@P_LightPAddress", System.Data.SqlDbType.VarChar){ Value=PhysicalAddress},
                        new SqlParameter("@P_longitude", System.Data.SqlDbType.Float){ Value=0},
                        new SqlParameter("@P_latitude", System.Data.SqlDbType.Float){ Value=0},
                        new SqlParameter("@P_RecDateTime", System.Data.SqlDbType.DateTime){ Value=NowDate},
                        new SqlParameter("@P_ChannelNumber", System.Data.SqlDbType.Int){ Value= Clight.Key},
                        new SqlParameter("@P_LightID", System.Data.SqlDbType.Int){ Value=0,Direction=ParameterDirection.Output},
                        new SqlParameter("@P_Msg", System.Data.SqlDbType.VarChar){ Value=string.Empty,Direction=ParameterDirection.Output},
                        };
                        var result = await dbContext.Database.ExecuteSqlCommandAsync("GPS_InsertDataDoubleLight @P_GatewayPAddress,@P_LightPAddress,@P_longitude,@P_latitude,@P_RecDateTime,@P_ChannelNumber,@P_LightID OUTPUT,@P_Msg OUTPUT", Param);
                        int lightid = Convert.ToInt32(Param[6].Value);
                        light = await dbContext.TNL_TunnelLights.AsNoTracking().FirstOrDefaultAsync(d => d.TunnelLight_ID == lightid);
                        if (light != null)
                        {
                            light.IMEI = OrigindeviceInfo.IMEI;
                            light.IMSI = OrigindeviceInfo.IMSI;
                            light.ICCID = OrigindeviceInfo.ICCID;
                            light.ChannelNumber = upets[NBRAC.DeviceType].ChannelNumber;
                            dbContext.Update(light);
                        }
                    }
                    else
                    {
                        if (originData.hasAddress)
                        {
                            light.LightPhysicalAddress_TX = PhysicalAddress;
                        }
                        else
                        {
                            light.LightPhysicalAddress_TX = "000000000000";
                        }
                        light.IMEI = OrigindeviceInfo.IMEI;
                        light.IMSI = OrigindeviceInfo.IMSI;
                        light.ICCID = OrigindeviceInfo.ICCID;
                        light.ChannelNumber = upets[NBRAC.DeviceType].ChannelNumber;
                        light.LightUsage_NR = LightType;
                        dbContext.Update(light);


                    }
                    OrigindeviceInfo.TunnelLight_ID = light.TunnelLight_ID;
                    //OrigindeviceInfo.TunnelLight_ID = 183;


                    //以下判断分组信息,如果不一致,则下发初始化信息。
                    #region 更新分组信息
                    if (upets.ContainsKey(NBRAC.Group0) ||
                        upets.ContainsKey(NBRAC.Group1) ||
                        upets.ContainsKey(NBRAC.Group2) ||
                        upets.ContainsKey(NBRAC.Group3) ||
                        upets.ContainsKey(NBRAC.Group4) ||
                        upets.ContainsKey(NBRAC.Group5) ||
                        upets.ContainsKey(NBRAC.Group6) ||
                        upets.ContainsKey(NBRAC.Group7))
                    {
                        ////暂时先不放开
                        //if (light.TunnelSection_ID != OrigindeviceInfo.Group0
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group1
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group2
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group3
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group4
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group5
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group6
                        // || light.TunnelSection_ID != OrigindeviceInfo.Group7)//如果分组信息不一样,那么则发送初始化信息过去
                        //{
                        //    #region 组装数据
                        //    //MoonsHelper
                        //    var rtc_guid = Guid.NewGuid();
                        //    rtc_guid.ToString().ToUpper();
                        //    //string GUID = string.Join("", guid.ToByteArray().Select(d => d.ToString("X2")));
                        //    var gval0 = TransmitHelper.GetGroupHex(deviceInfo.Group0);
                        //    var gval1 = TransmitHelper.GetGroupHex(deviceInfo.Group1);
                        //    var gval2 = TransmitHelper.GetGroupHex(deviceInfo.Group2);
                        //    var gval3 = TransmitHelper.GetGroupHex(deviceInfo.Group3);
                        //    var gval4 = TransmitHelper.GetGroupHex(deviceInfo.Group4);
                        //    var gval5 = TransmitHelper.GetGroupHex(deviceInfo.Group5);
                        //    var gval6 = TransmitHelper.GetGroupHex(deviceInfo.Group6);
                        //    var gval7 = TransmitHelper.GetGroupHex(deviceInfo.Group7);
                        //    gval0 = TransmitHelper.MergeBytes(gval0.Length, 4, gval0);
                        //    gval1 = TransmitHelper.MergeBytes(gval1.Length, 4, gval1);
                        //    gval2 = TransmitHelper.MergeBytes(gval2.Length, 4, gval2);
                        //    gval3 = TransmitHelper.MergeBytes(gval3.Length, 4, gval3);
                        //    gval4 = TransmitHelper.MergeBytes(gval4.Length, 4, gval4);
                        //    gval5 = TransmitHelper.MergeBytes(gval5.Length, 4, gval5);
                        //    gval6 = TransmitHelper.MergeBytes(gval6.Length, 4, gval6);
                        //    gval7 = TransmitHelper.MergeBytes(gval7.Length, 4, gval7);
                        //    List<byte> GroupBytes = new List<byte>();
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group0, upets[NBRAC.Group0].ChannelNumber, 0x04 }.Concat(gval0));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group1, upets[NBRAC.Group1].ChannelNumber, 0x04 }.Concat(gval1));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group2, upets[NBRAC.Group2].ChannelNumber, 0x04 }.Concat(gval2));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group3, upets[NBRAC.Group3].ChannelNumber, 0x04 }.Concat(gval3));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group4, upets[NBRAC.Group4].ChannelNumber, 0x04 }.Concat(gval4));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group5, upets[NBRAC.Group5].ChannelNumber, 0x04 }.Concat(gval5));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group6, upets[NBRAC.Group6].ChannelNumber, 0x04 }.Concat(gval6));
                        //    GroupBytes.AddRange(new byte[] { NBRAC.Group7, upets[NBRAC.Group7].ChannelNumber, 0x04 }.Concat(gval7));
                        //    #endregion

                        //    var TransmitHex = TransmitHelper.SendNBComand(rtc_guid.ToByteArray(), GroupBytes.ToArray());
                        //    transmitData = new TransmitData
                        //    {
                        //        Topic = AppSetting.LightTopicBefore + deviceInfo.IMEI,
                        //        CommandCode = DataHelper.BytesToHexStr(new byte[] { 0x04 }),
                        //        MesssageID = int.Parse(string.Join(string.Empty, from d in originData.messsageId select d.ToString())),
                        //        Data = TransmitHex,
                        //        UUID = rtc_guid
                        //    };
                        //}
                    }
                    #endregion
                    #endregion

                    #region 当前单灯表
                    var lightalm = await dbContext.TNL_TunnelLightAlms.FirstOrDefaultAsync(d => d.TunnelLight_ID == light.TunnelLight_ID);
                    //lightalm.TunnelLight_ID = summary.TunnelLight_ID;
                    if (lightalm == null)
                    {
                        lightalm = new TNL_TunnelLightAlm();
                        lightalm.AlmLevel_ID = 0;
                        lightalm.TunnelLight_ID = light.TunnelLight_ID;
                        lightalm.SampTime_DT = NowDate;
                        lightalm.ChannelNumber = light.ChannelNumber;
                        lightalm.LocalDate = NowDate;
                        lightalm.DataSource = 0;
                        lightalm.RemoteEndPoint = OrigindeviceInfo.IP;
                        //lightalm.Signal_NR = summary.Signal_NR;
                        lightalm.Version = OrigindeviceInfo.Version;
                        lightalm.IMEI = OrigindeviceInfo.IMEI;
                        lightalm.IMSI = OrigindeviceInfo.IMSI;
                        lightalm.ICCID = OrigindeviceInfo.ICCID;
                        lightalm.bandNo = int.Parse(OrigindeviceInfo.BAND);
                        //lightalm.State = OrigindeviceInfo.;
                        if (Math.Abs(longitude) > 0.01 && Math.Abs(latitude) > 0.01)//绝对值有效,才存入经纬度信息里
                            lightalm.GpsInfo = OrigindeviceInfo.GPSInfo;
                        lightalm.FirmwareVersion_NR = int.Parse(OrigindeviceInfo.Version.Replace(".", string.Empty));
                        //lightalm.PhotoCell = summary.poho;
                        //lightalm.InspectSuccess_DT = NowDate;
                        //lightalm.IsDay = summary.IsDay.ToString();
                        //lightalm.LightningCount = summary.LightningCount.ToString();
                        //lightalm.upUID = summary.upk;
                        //lightalm.CSQ = deviceInfo.csq;                   
                        await dbContext.AddAsync(lightalm);
                    }
                    else
                    {
                        lightalm.AlmLevel_ID = 0;
                        lightalm.TunnelLight_ID = light.TunnelLight_ID;
                        lightalm.SampTime_DT = NowDate;
                        lightalm.ChannelNumber = light.ChannelNumber;
                        lightalm.LocalDate = NowDate;
                        lightalm.DataSource = 0;
                        lightalm.RemoteEndPoint = OrigindeviceInfo.IP;
                        //lightalm.Signal_NR = summary.Signal_NR;
                        lightalm.Version = OrigindeviceInfo.Version;
                        lightalm.bandNo = int.Parse(OrigindeviceInfo.BAND);
                        //lightalm.State = OrigindeviceInfo.;
                        lightalm.GpsInfo = OrigindeviceInfo.GPSInfo;
                        lightalm.FirmwareVersion_NR = int.Parse(OrigindeviceInfo.Version.Replace(".", string.Empty));
                        //lightalm.PhotoCell = summary.poho;
                        //lightalm.InspectSuccess_DT = NowDate;
                        //lightalm.IsDay = summary.IsDay.ToString();
                        //lightalm.LightningCount = summary.LightningCount.ToString();
                        //lightalm.upUID = summary.upk;
                        //lightalm.CSQ = deviceInfo.csq;                   
                        dbContext.Update(lightalm);
                    }
                    #endregion

                    await dbContext.SaveChangesAsync();
                    await trans.CommitAsync();

                    //发送数据
                    try
                    {
                        //先把数据入库,再发送到设备上
                        if (transmitData != null) await TransmitContext.GetInstance().GetTransmitSchedule().Run(transmitData);

                        //校时
                        #region RTC校时
                        await Task.Delay(1000);
                        Guid guid = Guid.NewGuid();
                        DateTime NowTime = DateTime.Now;
                        var year = NowTime.Year.ToString("X4");
                        var month = NowTime.Month.ToString("X2");
                        var day = NowTime.Day.ToString("X2");
                        var week = ((int)NowTime.DayOfWeek).ToString("X2");
                        var hour = NowTime.Hour.ToString("X2");
                        var minute = NowTime.Minute.ToString("X2");
                        var second = NowTime.Second.ToString("X2");
                        var RTCHex = year + month + day + week + hour + minute + second;
                        var RTCBytes = HexFormatHelper.StringConvertHexBytes(RTCHex);
                        var RTCTransmitHex = TransmitHelper.SendNBComand(guid.ToByteArray(), RTCBytes, (byte)NBCommondCode.DateSync);
                        var RTCtransmitData = new TransmitData
                        {
                            Topic = AppSetting.LightTopicBefore + OrigindeviceInfo.IMEI,
                            CommandCode = DataHelper.BytesToHexStr(new byte[] { (byte)NBCommondCode.DateSync }),
                            MesssageID = int.Parse(string.Join(string.Empty, from d in originData.messsageId select d.ToString())),
                            Data = RTCTransmitHex,
                            UUID = guid
                        };
                        await TransmitContext.GetInstance().GetTransmitSchedule().Run(RTCtransmitData);
                        #endregion
                    }
                    catch (Exception e)
                    {
                        throw new ArgumentException("发送错误", e);
                    }

                }
                catch (ArgumentException ex)
                {
                    logger.Error("下发设备信息错误: " + ex.ToString());
                }
                catch (Exception ex)
                {
                    await trans.RollbackAsync();
                    logger.Error("Devcie Error:" + this.GetType().FullName + " " + ex.ToString());
                    throw;
                }

            }
        }