public string SendAndReceiveMessage <T>(T obj, Header type)
        {
            byte[] bytes = new byte[2048];
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 11000);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                                      sender.RemoteEndPoint.ToString());

                    JMessage msg        = JMessage.FromValue <T>(obj, type);
                    string   serialized = JMessage.Serialize(msg);



                    byte[] send = Encoding.ASCII.GetBytes(serialized);
                    // Send the data through the socket.
                    int    bytesSent, bytesRec;
                    string received;
                    if (type == Header.ExchangePKs)
                    {
                        bytesSent = sender.Send(Encoding.ASCII.GetBytes(serialized));
                        bytesRec  = sender.Receive(bytes);
                        received  = Encoding.ASCII.GetString(bytes);
                        var cleaned = received.Replace("\0", string.Empty);
                        Console.WriteLine("Echoed = {0}", cleaned);
                        received = cleaned;
                    }
                    else
                    {
                        Console.WriteLine("Going to send {0}", Convert.ToBase64String(EncryptMessage(serialized, type)));
                        bytesSent = sender.Send(EncryptMessage(serialized, type));
                        Console.WriteLine("Sent data");
                        bytesRec = sender.Receive(bytes);
                        Console.WriteLine("Received data");
                        received = DecryptMessage(bytes);


                        received = received.TrimEnd('\0');
                        Console.WriteLine("Trimmed {0}", received);
                    }

                    sender.Close();


                    return(received);
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return(null);
        }
示例#2
0
        public async Task <IActionResult> UpdateUserInOrg([FromBody] OrgUserModel model)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                if (string.IsNullOrEmpty(model.OrgAddonCode))
                {
                    msg.Error = true;
                    msg.Title = string.Format(CommonUtil.ResourceValue("ERR_REQUIRED"), CommonUtil.ResourceValue("BRANCH").ToLower());
                }
                else
                {
                    var org = await _context.AdOrganizations.FirstOrDefaultAsync(x => x.OrgAddonCode == model.OrgAddonCode);

                    if (org == null)
                    {
                        msg.Error = true;
                        msg.Title = model.OrgAddonCode.StartsWith("d_") ? "This is Division, please select branch level!" : "Branch is not exists!";
                    }
                    else
                    {
                        if (model.ListUser.Count > 0)
                        {
                            // Add user to branch
                            var listAdd = _context.Users.Where(x => model.ListUser.Any(y => y == x.Id) && x.BranchId != model.OrgAddonCode);
                            if (listAdd.Any())
                            {
                                foreach (var user in listAdd)
                                {
                                    if (user.BranchId == model.OrgAddonCode)
                                    {
                                        continue;
                                    }
                                    var oldBranch = user.BranchId;
                                    user.BranchId    = model.OrgAddonCode;
                                    user.UpdatedDate = DateTime.Now;
                                    user.UpdatedBy   = ESEIM.AppContext.UserName;
                                    _context.Update(user);

                                    //_actionLog.InsertActionLog("ASP_NET_USERS", "Update branch of user: "******"Update", false, user.UserName);
                                }
                            }
                            // Remove user out branch
                            var listDel = _context.Users.Where(x => model.ListUser.All(y => y != x.Id) && x.BranchId == model.OrgAddonCode);
                            if (listDel.Any())
                            {
                                foreach (var user in listDel)
                                {
                                    var oldBranch = user.BranchId;
                                    user.BranchId    = null;
                                    user.UpdatedDate = DateTime.Now;
                                    user.UpdatedBy   = ESEIM.AppContext.UserName;
                                    _context.Update(user);

                                    //_actionLog.InsertActionLog("ASP_NET_USERS", "Update branch of user: "******"Update", false, user.UserName);
                                }
                            }
                        }
                        else
                        {
                            var listUser = _context.Users.Where(x => x.BranchId == model.OrgAddonCode);
                            if (listUser.Any())
                            {
                                foreach (var user in listUser)
                                {
                                    var oldBranch = user.BranchId;
                                    user.BranchId    = null;
                                    user.UpdatedDate = DateTime.Now;
                                    user.UpdatedBy   = ESEIM.AppContext.UserName;
                                    _context.Update(user);

                                    //_actionLog.InsertActionLog("ASP_NET_USERS", "Update branch of user: "******"Update", false, user.UserName);
                                }
                            }
                        }

                        await _context.SaveChangesAsync();

                        msg.Title = string.Format(CommonUtil.ResourceValue("MSG_UPDATE_SUCCESS"), "tài khoản");
                    }
                }
            }
            catch (Exception e)
            {
                msg.Error = true;
                msg.Title = "Lỗi khi cập nhập";
                _actionLog.InsertActionLog("ASP_NET_USERS", "Update branch of user failed: " + e.Message, null, null, "Error");
            }

            return(Json(msg));
        }
示例#3
0
        public JsonResult UpdateCandidateInfoMore([FromBody] CandidateInfoMore data)
        {
            var msg = new JMessage()
            {
                Error = false, Title = ""
            };

            try
            {
                #region check validate
                if (string.IsNullOrEmpty(data.CandidateCode))
                {
                    msg.Error = true;
                    msg.Title = "Bạn chưa lấy mã đăng ký!";
                    return(Json(msg));
                }

                //if (string.IsNullOrEmpty(data.Fullname))
                //{
                //    msg.Title = "Nhập họ tên!";
                //    return Json(msg);
                //}
                //else
                //{
                //    if (data.Fullname.Length > 255)
                //    {
                //        msg.Title = "Tên tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (string.IsNullOrEmpty(data.Phone))
                //{
                //    msg.Title = "Nhập số điện thoại!";
                //    return Json(msg);
                //}
                //else
                //{
                //    if (data.Phone.Length > 50)
                //    {
                //        msg.Title = "Số điện thoại chỉ tối đa 50 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (string.IsNullOrEmpty(data.Email))
                //{
                //    msg.Title = "Nhập email!";
                //    return Json(msg);
                //}
                //else
                //{
                //    if (data.Email.Length > 100)
                //    {
                //        msg.Title = "Email chỉ tối đa 100 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (!string.IsNullOrEmpty(data.Address))
                //{
                //    if (data.Address.Length > 255)
                //    {
                //        msg.Title = "Địa chỉ tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (!string.IsNullOrEmpty(data.Skype))
                //{
                //    if (data.Skype.Length > 255)
                //    {
                //        msg.Title = "Skype chỉ tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                if (!string.IsNullOrEmpty(data.MainSkill))
                {
                    if (data.MainSkill.Length > 255)
                    {
                        msg.Title = "MainSkill chỉ tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.SubSkill))
                {
                    if (data.SubSkill.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "SubSkill chỉ tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.LanguageUse))
                {
                    if (data.LanguageUse.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "Ngôn ngữ chỉ tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.Targeting))
                {
                    if (data.Targeting.Length > 500)
                    {
                        msg.Error = true;
                        msg.Title = "Mục tiêu chỉ tối đa 500 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.FileCv_1))
                {
                    if (data.FileCv_1.Length > 255)
                    {
                        msg.Title = "Tên file quá dài!";
                        return(Json(msg));
                    }
                }
                #endregion

                var can = _context.CandiateBasic.FirstOrDefault(x => x.CandidateCode.Equals(data.CandidateCode));
                can.Ability          = string.IsNullOrEmpty(data.Ability) ? "" : data.Ability.Remove(data.Ability.Length - 1, 1);
                can.CanJoinDate      = string.IsNullOrEmpty(data.CanJoinDate) ? (DateTime?)null : DateTime.ParseExact(data.CanJoinDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                can.MainPracticeTime = data.MainPracticeTime;
                can.SalaryHope       = string.IsNullOrEmpty(data.SalaryHope) ? 0 : decimal.Parse(data.SalaryHope);
                can.MainSkill        = data.MainSkill;
                can.SubSkill         = data.SubSkill;
                can.LanguageUse      = data.LanguageUse;
                can.SubPracticeTime  = data.SubPracticeTime;
                can.Targeting        = data.Targeting;
                can.FileCv_1         = data.FileCv_1;
                can.UpdatedTime      = DateTime.Now;
                can.LaptopInfo       = data.LaptopInfo;
                can.SmartphoneInfo   = data.SmartphoneInfo;
                can.WorkPlace        = data.WorkPlace;
                _context.CandiateBasic.Update(can);
                _context.SaveChanges();
                msg.Title = "Lưu lại thông tin thành công";
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = "Có lỗi xảy ra!" + ex;
            }
            return(Json(msg));
        }
示例#4
0
        public async Task <JsonResult> Update(edu_room obj, IFormFile image)
        {
            var msg = new JMessage()
            {
                Error = false, ID = 1
            };

            try
            {
                edu_room rs = _context.edu_room.FirstOrDefault(x => x.id == obj.id);
                if (rs != null)
                {
                    var icimage = "";

                    if (image != null && image.Length > 0)
                    {
                        var pathUpload = Path.Combine(_hostingEnvironment.WebRootPath, "pictures\\image");
                        if (!Directory.Exists(pathUpload))
                        {
                            Directory.CreateDirectory(pathUpload);
                        }

                        var fileName = DateTimeOffset.Now.ToUnixTimeMilliseconds() + image.FileName;
                        var filePath = Path.Combine(pathUpload, fileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await image.CopyToAsync(stream);
                        }
                        icimage = "/pictures/image/" + fileName;
                    }
                    if (icimage != "")
                    {
                        rs.image = icimage;
                    }
                    rs.number_room = obj.number_room;
                    rs.address     = obj.address;

                    rs.note       = obj.note;
                    rs.facilities = obj.facilities;

                    rs.seat = obj.seat;

                    rs.updatetime = DateTime.Now;
                    _context.edu_room.Update(rs);
                    _context.SaveChanges();
                    msg.Title = "Sửa thông tin phòng học thành công";
                    msg.Error = false;
                    _actionLog.InsertActionLog("edu_room", "update room successfully", rs, obj, "Update");
                }
                else
                {
                    msg.Title = "Xảy ra lỗi, vui lòng thử lại.";
                    msg.Error = true;
                }
            }
            catch (Exception ex)
            {
                msg.ID     = 0;
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi khi sửa khoản mục";
                _actionLog.InsertActionLog("edu_room", "update room fail", null, obj, "Update");
            }
            return(Json(msg));
        }
示例#5
0
        public static void ParseIJTypeMessage(Context context, JsonCapsula decoded, long senderId, long messageId, long myUserId)
        {
            if (decoded == null)
            {
                return;
            }
            if (context.Contacts
                .Where(u => u.PublicId == senderId)
                .Select(u => u.Trusted)
                .SingleOrDefault() != 1)
            {
                throw new Exception($"User with id {senderId} isn't trusted.");
            }

            bool permission = senderId == myUserId;

            switch (decoded.Message.GetJsonType())
            {
            case JsonTypes.ALARM:
                JAlarm alarm = (JAlarm)decoded.Message;
                permission = permission ||
                             context.Contacts
                             .Where(u => u.PublicId == senderId)
                             .Select(u => u.AlarmPermission)
                             .SingleOrDefault() == 1;

                if (permission)
                {
                    context.Alarms.Add(new Alarms()
                    {
                        BlobMessagesId = messageId,
                        Text           = alarm.Text,
                        Time           = alarm.Date.GetChatovatkoString()
                    });
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to set alarm.");
                }
                break;

            case JsonTypes.CONTACT:
                JContact detail = (JContact)decoded.Message;

                if (permission)
                {
                    var toUpdate = context.Contacts
                                   .Where(u => u.PublicId == detail.PublicId)
                                   .SingleOrDefault();
                    if (toUpdate != null)
                    {
                        toUpdate.NickName          = detail.NickName;
                        toUpdate.PublicCertificate = detail.PublicCertificate;
                        toUpdate.AlarmPermission   = detail.AlarmPermission ? 1 : 0;
                        toUpdate.PublicId          = detail.PublicId;

                        toUpdate.ReceiveAesKey = detail.ReceiveAesKey;
                        toUpdate.SendAesKey    = detail.SendAesKey;
                        toUpdate.UserName      = detail.UserName;
                        toUpdate.Trusted       = detail.Trusted ? 1 : 0;

                        toUpdate.BlobMessagesId = messageId;
                    }
                    else
                    {
                        context.Contacts.Add(new Contacts()
                        {
                            NickName          = detail.NickName,
                            PublicCertificate = detail.PublicCertificate,
                            AlarmPermission   = detail.AlarmPermission ? 1 : 0,
                            PublicId          = detail.PublicId,

                            ReceiveAesKey = detail.ReceiveAesKey,
                            SendAesKey    = detail.SendAesKey,
                            UserName      = detail.UserName,
                            Trusted       = detail.Trusted ? 1 : 0,

                            BlobMessagesId = messageId
                        });
                    }
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to set contact detail.");
                }
                break;

            case JsonTypes.MESSAGES:
                JMessage jmessage       = (JMessage)decoded.Message;
                long     threadWithUser = (
                    from threads in context.MessagesThread
                    where threads.PublicId == jmessage.MessageThreadId
                    select threads.WithUser
                    ).SingleOrDefault();
                permission = permission || threadWithUser == senderId;

                if (permission)
                {
                    bool onlive = (from threads in context.MessagesThread
                                   where threads.PublicId == jmessage.MessageThreadId
                                   select threads.Onlive)
                                  .SingleOrDefault() == 1;

                    bool updated = false;
                    if (onlive)
                    {
                        var toUpdateInfo = (from bmessages in context.BlobMessages
                                            join messages in context.Messages on bmessages.Id equals messages.BlobMessagesId
                                            where bmessages.SenderId == senderId && messages.IdMessagesThread == jmessage.MessageThreadId
                                            select new { messages.BlobMessagesId, messages.Id })
                                           .SingleOrDefault();
                        if (toUpdateInfo != null)
                        {
                            var toUpdate = context.Messages
                                           .Where(m => m.Id == toUpdateInfo.Id)
                                           .SingleOrDefault();
                            updated = true;

                            toUpdate.Text           = jmessage.Text;
                            toUpdate.Date           = jmessage.Time.GetChatovatkoString();
                            toUpdate.BlobMessagesId = messageId;

                            context.SaveChanges();
                        }
                    }

                    if (!updated)
                    {
                        context.Messages.Add(new Messages()
                        {
                            Date             = jmessage.Time.GetChatovatkoString(),
                            Text             = jmessage.Text,
                            IdMessagesThread = jmessage.MessageThreadId,
                            BlobMessagesId   = messageId
                        });
                        context.SaveChanges();
                    }
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to send this message.");
                }
                break;

            case JsonTypes.MESSAGES_THREAD:
                JMessageThread messageThread = (JMessageThread)decoded.Message;
                permission = permission || (messageThread.WithUserId == senderId && !messageThread.DoOnlyDelete);
                if (permission)
                {
                    var old = context.MessagesThread
                              .Where(u => u.PublicId == messageThread.PublicId)
                              .SingleOrDefault();
                    if (messageThread.DoOnlyDelete && old != null)
                    {
                        context.Remove(old);
                    }
                    else if (messageThread.DoOnlyDelete)
                    {
                    }
                    else if (old != null)
                    {
                        old.Name           = messageThread.Name;
                        old.BlobMessagesId = messageId;
                        old.Archived       = messageThread.Archived ? 1 : 0;
                    }
                    else
                    {
                        context.MessagesThread.Add(new MessagesThread
                        {
                            Name           = messageThread.Name,
                            PublicId       = messageThread.PublicId,
                            Onlive         = messageThread.Onlive ? 1 : 0,
                            Archived       = messageThread.Archived ? 1 : 0,
                            WithUser       = messageThread.WithUserId,
                            BlobMessagesId = messageId
                        });
                    }
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to create/edit/delete this message thread.");
                }
                break;

            default:
                throw new Exception($"Json type unknown.");
            }
        }
        public JsonResult Insert([FromBody]MaterialSBatchModel obj)
        {
            var msg = new JMessage() { Error = false, Title = "" };
            try
            {
                var query = from a in _context.MaterialStoreBatchGoodss
                            where a.Code == obj.Code
                            select a;
                if (query.Count() == 0)
                {
                    var temp = new MaterialStoreBatchGoods
                    {
                        Code = obj.Code,
                        Name = obj.Name,
                        ProductCode = obj.ProductCode,
                        StoreId = obj.StoreId,
                        Quantity = obj.Quantity,
                        Unit = obj.Unit,
                        Vat = obj.Vat,
                        Cost = obj.Cost,
                        Currency = obj.Currency,
                        Barcode = obj.Barcode,
                        SupplierId = obj.SupplierId,
                        Madein = obj.Madein,
                        Packing = obj.Packing,
                        Sale = obj.Sale,
                        DateProduce = !string.IsNullOrEmpty(obj.DateProduce) ? DateTime.ParseExact(obj.DateProduce, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                        DateExpire = !string.IsNullOrEmpty(obj.DateExpire) ? DateTime.ParseExact(obj.DateExpire, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                        DateReiceive = !string.IsNullOrEmpty(obj.DateReiceive) ? DateTime.ParseExact(obj.DateReiceive, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                        Description = obj.Description,
                        CreatedBy = ESEIM.AppContext.UserName,
                        CreatedTime = DateTime.Now
                    };
                    //double? total = 0;
                    //if (obj.Quantity != null && obj.Cost != null)
                    //{
                    //    total = obj.Quantity * obj.Cost;
                    //    if (obj.Sale != null)
                    //    {
                    //        total = (total * obj.Sale) / 100;
                    //    }
                    //    if (obj.Vat != null)
                    //    {
                    //        total = (total * obj.Vat) / 100;
                    //    }
                    //}
                    temp.Total = obj.Total;
                    _context.MaterialStoreBatchGoodss.Add(temp);
                    _context.SaveChanges();
                    msg.Title = "Thêm lô hàng thành công";
                }
                else
                {
                    msg.Error = true;
                    msg.Title = "Mã lô hàng đã tồn tại";
                    //return msg;
                }
                return Json(msg);


                //var temp = new MaterialStoreBatchGoods
                //{
                //    Code = obj.Code,
                //    Name = obj.Name,
                //    ProductCode = obj.ProductCode,
                //    StoreId = obj.StoreId,
                //    Quantity = obj.Quantity,
                //    Unit = obj.Unit,
                //    Vat = obj.Vat,
                //    Cost = obj.Cost,
                //    Currency = obj.Currency,
                //    Barcode = obj.Barcode,
                //    SupplierId = obj.SupplierId,
                //    Madein = obj.Madein,
                //    Packing = obj.Packing,
                //    Sale = obj.Sale,
                //    DateProduce = !string.IsNullOrEmpty(obj.DateProduce) ? DateTime.ParseExact(obj.DateProduce, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                //    DateExpire = !string.IsNullOrEmpty(obj.DateExpire) ? DateTime.ParseExact(obj.DateExpire, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                //    DateReiceive = !string.IsNullOrEmpty(obj.DateReiceive) ? DateTime.ParseExact(obj.DateReiceive, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                //    Description = obj.Description,
                //    CreatedBy = ESEIM.AppContext.UserName,
                //    CreatedTime = DateTime.Now
                //};
                //double? total = 0;
                //if (obj.Quantity != null && obj.Cost != null)
                //{
                //    total = obj.Quantity * obj.Cost;
                //    if (obj.Sale != null)
                //    {
                //        total = (total * obj.Sale) / 100;
                //    }
                //    if (obj.Vat != null)
                //    {
                //        total = (total * obj.Vat) / 100;
                //    }
                //}
                //temp.Total = total;
                //_context.MaterialStoreBatchGoodss.Add(temp);
                //_context.SaveChanges();
                //msg.Title = "Thêm lô hàng thành công";
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = "Thêm lô hàng lỗi!";
            }
            return Json(msg);
        }
示例#7
0
        public JsonResult insert([FromBody] edu_relative_student obj)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                var query = from a in _context.edu_relative_student
                            where a.idstudenta == 4 && a.idstudentb == obj.idstudentb
                            select a;
                if (query.Count() == 0)
                {
                    edu_relative_student obj2 = new edu_relative_student();
                    edu_relative_student obj1 = new edu_relative_student();
                    var rs  = _context.common_properties.SingleOrDefault(x => x.id == obj.idrelative);
                    var rs2 = _context.edu_student.SingleOrDefault(x => x.id == 4);
                    obj1.idstudenta = 4;
                    obj1.idstudentb = obj.idstudentb;
                    obj1.idrelative = obj.idrelative;
                    obj1.flag       = 1;
                    _context.edu_relative_student.Add(obj1);

                    obj2.idstudenta = obj.idstudentb;
                    obj2.idstudentb = 4;
                    if (rs2.sex == 0)//nữ
                    {
                        if (rs.value.Contains("Anh") || rs.value.Contains("Chị"))
                        {
                            obj2.idrelative = 489;
                        }
                        if (rs.value.Contains("Em"))
                        {
                            obj2.idrelative = 4;
                        }
                    }

                    if (rs2.sex == 1)//nam
                    {
                        if (rs.value.Contains("Anh") || rs.value.Contains("Chị"))
                        {
                            obj2.idrelative = 5;
                        }
                        if (rs.value.Contains("Em"))
                        {
                            obj2.idrelative = 3;
                        }
                    }
                    obj2.flag = 1;
                    _context.edu_relative_student.Add(obj2);

                    _context.SaveChanges();
                    msg.Title = "Thêm thành công";
                }
                else
                {
                    msg.Error = true;
                    msg.Title = "Hai người này đã được thêm mối quan hệ ";
                }
            }
            catch (Exception ex)
            {
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi khi thêm ";
            }
            return(Json(msg));
        }
示例#8
0
        public JsonResult GetItem([FromBody] int id)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                var userId = ESEIM.AppContext.UserId;
                var data   = _context.DispatchesHeaders.FirstOrDefault(x => x.Id == id);

                var model = new IncommingDispatchesResponseModel();
                //Header
                model.Header = new IncommingDispatchesResponseHeaderModel
                {
                    Id              = data.Id,
                    DocumentName    = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.DocumentCode)?.Name,
                    DocumentNumber  = data.DocumentNumber,
                    DocumentSymbol  = data.DocumentSymbol,
                    DocumentSymbols = data.DocumentSymbols,
                    //Origanization = _context.AdOrganizations.FirstOrDefault(x => x.OrgCode == data.Origanization)?.OrgName,
                    //FromDate = data.FromDate.HasValue ? data.FromDate.Value.ToString("dd/MM/yyyy") : null,
                    PromulgateDate = data.PromulgateDate.HasValue ? data.PromulgateDate.Value.ToString("dd/MM/yyyy") : null,
                    //Epitome = data.Epitome,
                    SignDate = data.SignDate.HasValue ? data.SignDate.Value.ToString("dd/MM/yyyy") : null,
                    //DocumentZone = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.DocumentZone)?.Name,
                    //DocumentType = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.DocumentType)?.Name,
                    SignUser = data.SignUser,
                    Position = _context.Roles.FirstOrDefault(x => x.Code == data.Position)?.Title,
                    //Confidentiality = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.Confidentiality)?.Name,
                    //ImportantLevel = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.ImportantLevel && x.Type == EnumHelper<DocumentTypeEnum>.GetDisplayValue(DocumentTypeEnum.DM))?.Name,
                    SecurityLevel = _context.DispatchesCategorys.FirstOrDefault(x => x.Code == data.SecurityLevel && x.Type == EnumHelper <DocumentTypeEnum> .GetDisplayValue(DocumentTypeEnum.DM))?.Name,
                    //GetMothod = _context.CommonSettings.FirstOrDefault(x => x.CodeSet == data.GetMothod)?.ValueSet,
                    CreatedEditor = data.CreatedEditor,
                    CreatedUser   = !string.IsNullOrEmpty(data.CreatedUserId) ? _context.Users.FirstOrDefault(x => x.Id == data.CreatedUserId)?.GivenName : null,
                    UnitEditor    = data.UnitEditor,
                    IsQPPL        = data.IsQppl,
                    //ExperiedReply = data.ExperiedReply.HasValue ? data.ExperiedReply.Value.ToString("dd/MM/yyyy") : null,
                    ReplyStatus = data.ReplyStatus,
                    Note        = data.Note,
                    Status      = data.Status,
                };

                var tracking = _context.DispatchTrackingProcesss.FirstOrDefault(x => x.DispatchCode == data.DispatchCode);
                //file
                var listFile = _context.DispatchesFileACTs.Where(x => x.ProcessCode == tracking.ProcessCode).Select(y => new IncommingDispatchesFile
                {
                    Id            = y.Id,
                    CreatedEditor = model.Header.CreatedUser,
                    User          = y.User.GivenName,
                    FileName      = y.FileName,
                    Fomart        = y.Fomart,
                    Source        = y.Soure,
                    CreatedTime   = y.CreatedTime,
                }).AsNoTracking();
                model.Detail.ListFile.AddRange(listFile);

                //GroupUser
                var listMember = _context.DispatchesMemberActivitys.Where(x => x.ProcessCode == tracking.ProcessCode).Select(x => new IncommingDispatchesMember
                {
                    Id            = x.Id,
                    Assigner      = x.Assigner,
                    Name          = x.User.GivenName,
                    UserId        = x.UserId,
                    CreatedTime   = x.CreatedTime,
                    GroupUserCode = x.GroupUserCode,
                    IsShowDelete  = false,
                    Role          = x.Role,
                }).AsNoTracking();
                var listMain = listMember.Where(x => x.Role == DocumentRoleEnum.Main.GetHashCode()).GroupBy(x => x.GroupUserCode).Select(x => x.Key);

                foreach (var item in listMain)
                {
                    if (item == null)
                    {
                        model.Detail.ListMember.AddRange(listMember.Where(x => x.Role == DocumentRoleEnum.Main.GetHashCode() && x.GroupUserCode == item));
                    }
                    else
                    {
                        if (item == EnumHelper <GroupUserEnum> .GetDisplayValue(GroupUserEnum.LD))
                        {
                            var getListMemberActiveVP = from a in _context.AdUserInGroups
                                                        join b in _context.Users on a.UserId equals b.Id
                                                        where a.GroupUserCode == item
                                                        select new
                            {
                                a.UserId,
                            };
                            var getListMemberVP = listMember.Where(x => x.GroupUserCode == item).Select(x => new IncommingDispatchesMember {
                                UserId = x.UserId, IsShowDelete = false
                            });
                            var listDeferent = getListMemberVP.Where(x => !getListMemberActiveVP.Any(y => y.UserId == x.UserId));
                            if (!listDeferent.Any())
                            {
                                var group = new IncommingDispatchesGroup
                                {
                                    GroupUserCode = item,
                                    Name          = _context.AdGroupUsers.FirstOrDefault(x => x.GroupUserCode == item).Title ?? null,
                                    IsShow        = false,
                                };
                                model.Detail.ListGroup.Add(group);
                            }
                            else
                            {
                                model.Detail.ListMember.AddRange(getListMemberVP);
                            }
                        }
                        else
                        {
                            var getListUserPermisionActive = _context.DispatchesUsers.Where(x => x.GroupUserCode == item)
                                                             .Select(x => new
                            {
                                x.UserId,
                            });
                            var getListUser = listMember.Where(x => x.GroupUserCode == item).Select(x => new IncommingDispatchesMember {
                                UserId = x.UserId, IsShowDelete = false
                            });
                            var listDeferent = getListUser.Where(x => !getListUserPermisionActive.Any(y => y.UserId == x.UserId));
                            if (!listDeferent.Any())
                            {
                                var group = new IncommingDispatchesGroup
                                {
                                    GroupUserCode = item,
                                    Name          = _context.AdGroupUsers.FirstOrDefault(x => x.GroupUserCode == item).Title ?? null,
                                    IsShow        = false,
                                };
                                model.Detail.ListGroup.Add(group);
                            }
                            else
                            {
                                model.Detail.ListMember.AddRange(getListUser);
                            }
                        }
                    }
                }
                //Người xử lý chính
                var checkUserMain = listMember.FirstOrDefault(x => x.UserId == userId);
                if (checkUserMain.Role == DocumentRoleEnum.Main.GetHashCode())
                {
                    var listAssignerActiveSend = listMember.Where(x => x.Assigner == userId).Distinct().Traverse(y => listMember.Where(child => y.UserId == child.Assigner && y.Role != DocumentRoleEnum.Main.GetHashCode()).DistinctBy(z => z.Assigner)).Select(x => new IncommingDispatchesMember
                    {
                        UserId       = x.UserId,
                        Name         = x.Name,
                        IsShowDelete = false,
                        IsShowSend   = true
                    });
                    model.Detail.ListMember.AddRange(listAssignerActiveSend);
                }
                else
                {
                    var userSend = listMember.Where(x => x.UserId == userId && x.Role != DocumentRoleEnum.Main.GetHashCode()).Flatten(y => listMember.Where(parent => y.Assigner == parent.UserId && parent.Role != DocumentRoleEnum.Main.GetHashCode())).Select(x => x.Assigner).FirstOrDefault();
                    if (userSend != null)
                    {
                        var listAssignerActiveSend = listMember.Where(x => x.Assigner == userSend).Distinct().Traverse(y => listMember.Where(child => y.UserId == child.Assigner && y.Role != DocumentRoleEnum.Main.GetHashCode()).DistinctBy(z => z.Assigner)).Select(x => new IncommingDispatchesMember
                        {
                            UserId       = x.UserId,
                            Name         = x.Name,
                            IsShowDelete = false,
                            IsShowSend   = true
                        });
                        model.Detail.ListMember.AddRange(listAssignerActiveSend);
                    }
                }
                msg.Object = model;
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = String.Format(CommonUtil.ResourceValue("DODP_MSG_FAIL_DOCUMENT"));
            }
            return(Json(msg));
        }
示例#9
0
        public async Task <JsonResult> UpdatePermission([FromBody] PermissionModel model)
        {
            JMessage msg = new JMessage {
                Error = true, Title = string.Format(CommonUtil.ResourceValue("MSG_UPDATE_FAIL"), CommonUtil.ResourceValue("PERMISSION").ToLower())
            };

            try
            {
                model.Resources = model.Resources.Where(x => !x.IsFunction).ToList();
                if (model.GroupCodes.Count > 0)
                {
                    var listFunctionChild = await _context.AdFunctions.Where(x => x.FunctionCode == model.FunctionCode || x.ParentCode == model.FunctionCode || x.Parent.ParentCode == model.FunctionCode).ToListAsync();

                    var listGroupUser = await _context.AdGroupUsers.Where(x => model.GroupCodes.Any(y => y == x.GroupUserCode)).ToListAsync();

                    var listUserInGroup = await _context.AdUserInGroups.Where(x => model.GroupCodes.Any(y => y == x.GroupUserCode) && x.RoleId == model.RoleId).ToListAsync();

                    var listPermissionAll = await _context.AdPermissions.Where(x => x.ApplicationCode == model.ApplicationCode && x.RoleId == model.RoleId && listGroupUser.Any(y => y.GroupUserCode == x.GroupUserCode) && (string.IsNullOrEmpty(model.FunctionCode) || listFunctionChild.Any(y => y.FunctionCode == x.FunctionCode))).ToListAsync();

                    var listPermissionDefault = listPermissionAll.Where(x => x.UserId == null).ToList();
                    var listPermissionUser    = listPermissionAll.Where(x => x.UserId != null).ToList();
                    if (listGroupUser.Count > 0)
                    {
                        foreach (var groupUser in listGroupUser)
                        {
                            if (!model.IsMultiple)
                            {
                                // Remove permission default
                                var delPermissionDefault = listPermissionDefault.Where(x => x.GroupUserCode == groupUser.GroupUserCode && !model.Resources.Any(y => y.HasPermission && !y.IsFunction && y.FunctionCode == x.FunctionCode && y.Code == x.ResourceCode));
                                _context.RemoveRange(delPermissionDefault);

                                // Remove permission user
                                var delPermissionUser = listPermissionUser.Where(x => x.GroupUserCode == groupUser.GroupUserCode && !model.Resources.Any(y => y.HasPermission && !y.IsFunction && y.FunctionCode == x.FunctionCode && y.Code == x.ResourceCode));
                                _context.RemoveRange(delPermissionUser);
                            }

                            // Add permission default
                            var addPermissionDefault = model.Resources.Where(x => x.HasPermission && !x.IsFunction && !listPermissionDefault.Any(y => y.GroupUserCode == groupUser.GroupUserCode && y.FunctionCode == x.FunctionCode && y.ResourceCode == x.Code))
                                                       .Select(x => new AdPermission
                            {
                                ApplicationCode = model.ApplicationCode,
                                FunctionCode    = x.FunctionCode,
                                ResourceCode    = x.Code,
                                GroupUserCode   = groupUser.GroupUserCode,
                                RoleId          = model.RoleId,
                                UserId          = null,
                            });
                            _context.AddRange(addPermissionDefault);

                            // Add permission user
                            var listUser = listUserInGroup.Where(x => x.GroupUserCode == groupUser.GroupUserCode).ToList();
                            //var permissionUser = listPermissionUser.Where(x => x.GroupUserCode == groupUser.GroupUserCode).GroupBy(g => g.UserId).ToList();
                            if (listUser.Count > 0)
                            {
                                foreach (var perUser in listUser)
                                {
                                    var addPermissionUser = model.Resources.Where(x => x.HasPermission && !x.IsFunction && x.Scope == false && !listPermissionUser.Any(y => y.GroupUserCode == groupUser.GroupUserCode && y.FunctionCode == x.FunctionCode && y.ResourceCode == x.Code))
                                                            .Select(x => new AdPermission
                                    {
                                        ApplicationCode = model.ApplicationCode,
                                        FunctionCode    = x.FunctionCode,
                                        ResourceCode    = x.Code,
                                        GroupUserCode   = groupUser.GroupUserCode,
                                        RoleId          = model.RoleId,
                                        UserId          = perUser.UserId,
                                    });
                                    _context.AddRange(addPermissionUser);
                                }
                            }
                        }
                    }

                    var result = await _context.SaveChangesAsync();
                }
                _actionLog.InsertActionLog("VIB_PERMISSION", "Update define permission for deparment/profit center success", null, null, "Update");

                msg.Error = false;
                msg.Title = string.Format(CommonUtil.ResourceValue("MSG_UPDATE_SUCCESS"), CommonUtil.ResourceValue("PERMISSION").ToLower());
            }
            catch (Exception ex)
            {
                _actionLog.InsertActionLog("VIB_PERMISSION", "Update define permission failed: " + ex.Message, null, null, "Error");
                msg.Object = ex;
            }

            return(Json(msg));
        }
示例#10
0
        public JsonResult CalculateSalary(string fromDate, string toDate)
        {
            var msg = new JMessage {
                Error = false, Title = ""
            };
            var timeWorking = new TimeSpan(8, 30, 0);
            var freeTime    = new TimeSpan(1, 30, 0);
            var listSalary  = new  List <SalaryUserModel>();
            var timeWork    = 0.0;
            var from        = !string.IsNullOrEmpty(fromDate) ? DateTime.ParseExact(fromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null;
            var to          = !string.IsNullOrEmpty(toDate) ? DateTime.ParseExact(toDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null;

            if (from != null && to != null)
            {
                var list = _context.StaffTimetableWorkings.Where(x => x.ActionTime >= from && x.ActionTime <= to);
                if (list.Any())
                {
                    var listUser = list.GroupBy(x => x.UserId).Select(x => x.Key);
                    foreach (var user in listUser)
                    {
                        var listForUser = list.Where(x => x.UserId == user);

                        var listGoLateForUser   = listForUser.Where(x => x.Action == StaffStauts.CheckIn.DescriptionAttr() && x.Session == 1 && x.ActionTime.TimeOfDay < timeWorking);
                        var listNoWorking       = listForUser.Where(x => x.Action == StaffStauts.NoWork.DescriptionAttr());
                        var dayNoWork           = Convert.ToInt32(listNoWorking.Where(x => x.ActionTo.HasValue).Select(x => x.ActionTo.Value.Subtract(x.ActionTime).Days).First());
                        var listCheckInCheckOut = listForUser.Where(x => x.Action != StaffStauts.NoWork.DescriptionAttr());
                        if (listCheckInCheckOut.Any())
                        {
                            var listSession = listCheckInCheckOut.GroupBy(x => x.Session).Select(x => x.Key);
                            foreach (var item in listSession)
                            {
                                var session = listCheckInCheckOut.Where(x => x.Session == item);
                                if (session.Any())
                                {
                                    var checkOut = session.FirstOrDefault(x => x.Action == StaffStauts.CheckOut.DescriptionAttr()).ActionTime;
                                    var checkIn  = session.FirstOrDefault(x => x.Action == StaffStauts.CheckIn.DescriptionAttr()).ActionTime;
                                    timeWork = timeWork + ((checkOut.Subtract(checkIn)).TotalMinutes);
                                }
                            }
                        }
                        var model = new SalaryUserModel
                        {
                            UserName      = _context.Users.FirstOrDefault(x => x.Id == listForUser.First().UserId)?.GivenName,
                            NumberLate    = listGoLateForUser.Count(),
                            TotalTimeLate = listGoLateForUser.Select(x => new
                            {
                                TimeLate = x.ActionTime.Subtract(timeWorking).TimeOfDay.TotalMinutes,
                            }).Sum(x => x.TimeLate),
                            NumberNoWork      = dayNoWork,
                            TimeNoWork        = (dayNoWork * 7.5),
                            NumberMinutesWork = timeWork - freeTime.TotalMinutes,
                            NumberHourseWork  = Math.Round((timeWork - freeTime.TotalMinutes) / 60, 2),
                            NumberDayWork     = Math.Round(((timeWork - freeTime.TotalMinutes) / 60) / 7.5, 2),
                        };
                        listSalary.Add(model);
                    }
                    msg.Object = listSalary;
                }
            }
            return(Json(msg));
        }
示例#11
0
        public async Task <JsonResult> DeleteItems([FromBody] List <string> listId)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                ////_logger.LogInformation(LoggingEvents.LogDb, "Delete list role");
                List <string>     listRef        = new List <string>();
                List <string>     listDel        = new List <string>();
                List <AspNetRole> listAspNetRole = new List <AspNetRole>();
                foreach (var id in listId)
                {
                    AspNetRole obj = await _roleManager.FindByIdAsync(id);

                    if (obj != null)
                    {
                        var lstRef = _context.AdUserInGroups.FirstOrDefault(x => x.RoleId == id);
                        if (lstRef != null)
                        {
                            listRef.Add(id);
                        }
                        else
                        {
                            var p = _context.AdPermissions.FirstOrDefault(x => x.RoleId == id);
                            if (p != null)
                            {
                                listRef.Add(id);
                            }
                            else
                            {
                                listDel.Add(id);
                            }
                        }
                    }
                }
                if (listRef.Count > 0)
                {
                    if (listDel.Count > 0)
                    {
                        foreach (var id in listDel)
                        {
                            AspNetRole obj = await _roleManager.FindByIdAsync(id);

                            listAspNetRole.Add(obj);
                            await _roleManager.DeleteAsync(obj);
                        }
                        msg.Error = true;
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_DEL_SUCCESS_LIST_ITEM_BUT_REF"), CommonUtil.ResourceValue("ADM_ROLE_LBL_ROLE").ToLower());
                        //_logger.LogError(LoggingEvents.LogDb, "Delete part of the role list successfully");
                        _actionLog.InsertActionLogDeleteItem("ASP_NET_ROLES", "Delete part of the role list successfully", listAspNetRole.ToArray(), null, "Delete");
                    }
                    else
                    {
                        msg.Error = true;
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_ERR_LIST_OBJ_REF"), CommonUtil.ResourceValue("ADM_ROLE_LBL_ROLE").ToLower());
                        //_logger.LogError(LoggingEvents.LogDb, "Delete list role fail");
                        _actionLog.InsertActionLogDeleteItem("ASP_NET_ROLES", "Delete list role fail", null, null, "Error");
                    }
                }
                else
                {
                    if (listDel.Count > 0)
                    {
                        foreach (var id in listDel)
                        {
                            AspNetRole obj = await _roleManager.FindByIdAsync(id);

                            listAspNetRole.Add(obj);
                            await _roleManager.DeleteAsync(obj);
                        }
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_DELETE_LIST_SUCCESS"), CommonUtil.ResourceValue("ADM_ROLE_LBL_ROLE").ToLower());
                        ////_logger.LogInformation(LoggingEvents.LogDb, "Delete list role successfully");
                        _actionLog.InsertActionLogDeleteItem("ASP_NET_ROLES", "Delete list role successfully", listAspNetRole.ToArray(), null, "Delete");
                    }
                }
            }
            catch (Exception ex)
            {
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = String.Format(CommonUtil.ResourceValue("COM_MSG_DELETE_LIST_FAIL"), CommonUtil.ResourceValue("ADM_ROLE_LBL_ROLE").ToLower());
                //_logger.LogError(LoggingEvents.LogDb, "Delete list role fail");
                _actionLog.InsertActionLogDeleteItem("ASP_NET_ROLES", "Delete list role failed: " + ex.Message, null, null, "Error");
            }
            return(Json(msg));
        }
        private void commutation()
        {
            while (flag)
            {
                int opt = commOption();

                foreach (IPort iport in this.ports.iports)
                {
                    //check if there is frame in queue and try to process it
                    if (iport.input.Count > 0)
                    {
                        STM1 frame = iport.input.Dequeue();

                        //if (frame.vc4 != null)
                        if (opt != 1)
                        {
                            Console.WriteLine("vc4");
                            int out_pos           = -1;
                            VirtualContainer4 vc4 = frame.vc4;
                            out_pos = switchField.commutateContainer(vc4, iport.port);
                            if (out_pos != -1)
                            {
                                log("ok", ConsoleColor.Green);
                                this.ports.oports[out_pos].addToOutQueue(vc4);
                            }
                        }
                        //else if (frame.vc4.vc3List.Count > 0)
                        else
                        {
                            Console.WriteLine("vc3->vc4");
                            Console.WriteLine("unpacking container");
                            foreach (var vc in frame.vc4.vc3List)
                            {
                                VirtualContainer3 vc3 = vc.Value;
                                if (vc3 != null)
                                {
                                    int[] out_pos = { -1, -1 };
                                    out_pos = switchField.commutateContainer(vc3, iport.port, vc.Key);
                                    if (out_pos[0] != -1)
                                    {
                                        log("ok", ConsoleColor.Green);
                                        this.ports.oports[out_pos[0]].addToTempQueue(vc3, out_pos[1]);
                                    }
                                }
                            }
                        }
                        //else
                        //{
                        //Console.WriteLine("smth wrong with stm1");
                        //}
                    }
                }
                foreach (OPort oport in this.ports.oports)
                {
                    //packing STM from tempQueue to outqueue
                    oport.addToOutQueue();
                }

                foreach (OPort oport in this.ports.oports)
                {
                    //check if there is frame in queue and try to send it
                    if (oport.output.Count > 0)
                    {
                        STM1 frame = oport.output.Dequeue();
                        if (frame.vc4 != null || frame.vc4.vc3List.Count > 0)
                        {
                            try
                            {
                                pathList.Add(this.virtualIp);
                                Signal signal = new Signal(oport.port, frame, pathList);
                                consoleWriter("sending signal port: " + signal.port);
                                string data = JMessage.Serialize(JMessage.FromValue(signal));
                                Console.WriteLine(data);
                                writer.Write(data);
                            }
                            catch (Exception e)
                            {
                                log("\nError sending signal: " + e.Message, ConsoleColor.Red);
                                Thread.Sleep(2000);
                                Environment.Exit(1);
                            }
                        }
                    }
                }
                Thread.Sleep(125);
            }
        }
示例#13
0
 public override int GetHashCode()
 {
     return(Type.GetHashCode() + JMessage.GetHashCode());
 }
示例#14
0
        public bool Equals(NotificationADO obj)
        {
            bool ret = Type == obj.Type && JMessage.Equals(obj.JMessage);

            return(ret);
        }
示例#15
0
        public async Task <JsonResult> Update(Jnana_news_cat obj, IFormFile cat_avarta)
        {
            var msg = new JMessage()
            {
                Error = false, ID = 1
            };

            try
            {
                Jnana_news_cat rs = _context.Jnana_news_cat.FirstOrDefault(x => x.id == obj.id);
                if (rs != null)
                {
                    var iccat_avarta = "";

                    if (cat_avarta != null && cat_avarta.Length > 0)
                    {
                        var pathUpload = Path.Combine(_hostingEnvironment.WebRootPath, "cat_avartas\\avatar");
                        if (!Directory.Exists(pathUpload))
                        {
                            Directory.CreateDirectory(pathUpload);
                        }

                        var fileName = DateTimeOffset.Now.ToUnixTimeMilliseconds() + cat_avarta.FileName;
                        var filePath = Path.Combine(pathUpload, fileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await cat_avarta.CopyToAsync(stream);
                        }
                        iccat_avarta = "/cat_avartas/avatar/" + fileName;
                    }
                    if (iccat_avarta != "")
                    {
                        rs.cat_avarta = iccat_avarta;
                    }
                    var query = from a in _context.Jnana_news_articles
                                join b in _context.Jnana_news_cat
                                on a.cat_code equals b.cat_code
                                where b.cat_code == rs.cat_code
                                select a;
                    foreach (var item in query)
                    {
                        item.cat_code    = obj.cat_code;
                        item.update_time = DateTime.Now;
                        _context.Jnana_news_articles.Update(item);
                    }
                    rs.cat_code        = obj.cat_code;
                    rs.cat_title       = obj.cat_title;
                    rs.cat_description = obj.cat_description;
                    rs.cat_parent_code = obj.cat_parent_code;
                    rs.update_time     = DateTime.Now;
                    _context.Jnana_news_cat.Update(rs);
                    _context.SaveChanges();
                    msg.Title = "Sửa thông tin danh mục thành công";
                    msg.Error = false;
                    _actionLog.InsertActionLog("Jnana_news_cat", "update category successfully", rs, obj, "Update");
                }
                else
                {
                    msg.Title = "Xảy ra lỗi, vui lòng thử lại.";
                    msg.Error = true;
                }
            }
            catch (Exception ex)
            {
                msg.ID     = 0;
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi khi sửa khoản mục";
                _actionLog.InsertActionLog("Jnana_news_cat", "update category fail", null, obj, "Update");
            }
            return(Json(msg));
        }
示例#16
0
        public async Task <JsonResult> GetResource([FromBody] ObjGetResourceModel obj)
        {
            List <AdResourcePermission> result = new List <AdResourcePermission>();

            try
            {
                var listPermissionDefault = await _context.AdPermissions.Include(i => i.Function).Where(x => x.ApplicationCode == obj.AppCode && x.UserId == null && x.RoleId == obj.RoleId && obj.ListGUserId.Any(y => y == x.GroupUserCode)).ToListAsync();

                var listPrivileges = await _context.AdPrivileges.Include(x => x.Function).Include(x => x.Resource).Where(x => x.Resource.Status && obj.ListFuncId.Any(y => y == x.FunctionCode)).ToListAsync();

                if (listPrivileges.Count > 0)
                {
                    var groupFunction = listPrivileges.GroupBy(g => g.Function).OrderBy(o => o.Key.ParentCode).ThenBy(t => t.Key.FunctionCode).ToList();
                    if (groupFunction.Count > 0)
                    {
                        foreach (var groupfunc in groupFunction)
                        {
                            var function = groupfunc.Key;
                            // Get all resource of function
                            var listPrivilegeOfFunction = listPrivileges.Where(x => x.FunctionCode == function.FunctionCode).ToList();
                            if (listPrivilegeOfFunction.Count > 0)
                            {
                                var defaultFunction = new AdResourcePermission();
                                defaultFunction.Id            = function.FunctionId;
                                defaultFunction.Code          = function.FunctionCode;
                                defaultFunction.Title         = function.Title;
                                defaultFunction.Description   = function.Description;
                                defaultFunction.Ord           = function.Ord;
                                defaultFunction.ParentCode    = function.ParentCode;
                                defaultFunction.FunctionCode  = function.FunctionCode;
                                defaultFunction.FunctionName  = function.Title;
                                defaultFunction.HasPermission = true;
                                defaultFunction.IsFunction    = true;
                                result.Add(defaultFunction); // Add first function

                                var query = from pr in listPrivilegeOfFunction
                                            join gfr in groupfunc on pr.ResourceCode equals gfr.ResourceCode into grpFunc
                                            from fr in grpFunc.DefaultIfEmpty()
                                            select new AdResourcePermission
                                {
                                    Id            = pr.PrivilegeId,
                                    Code          = pr.Resource.ResourceCode,
                                    Title         = pr.Resource.Title,
                                    Description   = pr.Resource.Description,
                                    Api           = pr.Resource.Api,
                                    Path          = pr.Resource.Path,
                                    Ord           = pr.Resource.Ord,
                                    Style         = pr.Resource.Style,
                                    Scope         = pr.Resource.Scope,
                                    ParentCode    = pr.Resource.ParentCode,
                                    FunctionCode  = pr.FunctionCode,
                                    FunctionName  = pr.Function.Title,
                                    IsFunction    = false,
                                    HasPermission = !obj.IsMultiple && listPermissionDefault.Any(x => x.FunctionCode == pr.FunctionCode && x.ResourceCode == pr.ResourceCode)
                                };
                                result.AddRange(query);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                JMessage objex = new JMessage()
                {
                    Error = true, Object = ex
                };
            }

            return(Json(result));
        }
示例#17
0
        public async Task <JsonResult> Insert(Jnana_news_cat obj, IFormFile cat_avarta)
        {
            var msg = new JMessage()
            {
                Error = false, ID = 1
            };

            try
            {
                Jnana_news_cat rs = _context.Jnana_news_cat.FirstOrDefault(x => x.cat_code == obj.cat_code);
                if (rs == null)
                {
                    var iccat_avarta = "";

                    if (cat_avarta != null && cat_avarta.Length > 0)
                    {
                        var pathUpload = Path.Combine(_hostingEnvironment.WebRootPath, "cat_avartas\\avatar");
                        if (!Directory.Exists(pathUpload))
                        {
                            Directory.CreateDirectory(pathUpload);
                        }

                        var fileName = DateTimeOffset.Now.ToUnixTimeMilliseconds() + cat_avarta.FileName;
                        var filePath = Path.Combine(pathUpload, fileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await cat_avarta.CopyToAsync(stream);
                        }
                        iccat_avarta = "/cat_avartas/avatar/" + fileName;
                    }
                    if (iccat_avarta != "")
                    {
                        obj.cat_avarta = iccat_avarta;
                    }


                    obj.created_time = DateTime.Now;
                    obj.cat_status   = 1;
                    _context.Jnana_news_cat.Add(obj);
                    _context.SaveChanges();

                    msg.Title = "Thêm mới danh mục thành công";
                    msg.Error = false;
                    _actionLog.InsertActionLog("Jnana_news_cat", "Insert new category successfully", null, obj, "Insert");
                }
                else
                {
                    msg.Title = "Mã đã tồn tại";
                    msg.Error = true;
                }
            }
            catch (Exception ex)
            {
                msg.ID     = 0;
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi khi thêm khoản mục";
                _actionLog.InsertActionLog("news_category", "Insert new category fail", null, obj, "Insert");
            }
            return(Json(msg));
        }
示例#18
0
        public static void ParseIJTypeMessage(Context context, IJType decoded, long senderId, long messageId, long myUserId)
        {
            if (decoded == null)
            {
                return;
            }
            if (context.Contacts
                .Where(u => u.PublicId == senderId)
                .Select(u => u.Trusted)
                .SingleOrDefault() != 1)
            {
                throw new Exception($"User with id {senderId} isn't trusted.");
            }

            bool permission = senderId == myUserId;

            switch (decoded.GetJsonType())
            {
            case JsonTypes.ALARM:
                JAlarm alarm = (JAlarm)decoded;
                permission = permission ||
                             context.ContactsDetail
                             .Where(u => u.ContactId == senderId)
                             .Select(u => u.AlarmPermission)
                             .SingleOrDefault() == 1;

                if (permission)
                {
                    context.Alarms.Add(new Alarms()
                    {
                        BlobMessagesId = messageId,
                        Text           = alarm.Text,
                        Time           = alarm.Date.GetChatovatkoString()
                    });
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to set alarm.");
                }
                break;

            case JsonTypes.CONTACT_DETAIL:
                JContactDetail detail = (JContactDetail)decoded;
                permission = permission ||
                             context.ContactsDetail
                             .Where(u => u.ContactId == senderId)
                             .Select(u => u.ChangeContactsPermission)
                             .SingleOrDefault() == 1;

                if (permission)
                {
                    var toUpdate = context.ContactsDetail
                                   .Where(u => u.ContactId == detail.ContactId)
                                   .SingleOrDefault();
                    if (toUpdate != null)
                    {
                        toUpdate.NickName                 = detail.NickName;
                        toUpdate.BlobMessagesId           = messageId;
                        toUpdate.AlarmPermission          = detail.AlarmPermission ? 1 : 0;
                        toUpdate.ChangeContactsPermission = detail.ChangeContactPermission;
                    }
                    else
                    {
                        context.ContactsDetail.Add(new ContactsDetail()
                        {
                            AlarmPermission          = detail.ChangeContactPermission,
                            NickName                 = detail.NickName,
                            BlobMessagesId           = messageId,
                            ContactId                = detail.ContactId,
                            ChangeContactsPermission = detail.ChangeContactPermission
                        });
                    }
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to set contact detail.");
                }
                break;

            case JsonTypes.MESSAGES:
                JMessage jmessage       = (JMessage)decoded;
                long     threadWithUser = (
                    from threads in context.MessagesThread
                    where threads.PublicId == jmessage.MessageThreadId
                    select threads.WithUser
                    ).SingleOrDefault();
                permission = permission || threadWithUser == senderId;

                if (permission)
                {
                    bool onlive = (from threads in context.MessagesThread
                                   where threads.PublicId == jmessage.MessageThreadId
                                   select threads.Onlive)
                                  .SingleOrDefault() == 1;

                    bool updated = false;
                    if (onlive)
                    {
                        var toUpdateInfo = (from bmessages in context.BlobMessages
                                            join messages in context.Messages on bmessages.Id equals messages.BlobMessagesId
                                            where bmessages.SenderId == senderId && messages.IdMessagesThread == jmessage.MessageThreadId
                                            select new { messages.BlobMessagesId, messages.Id })
                                           .SingleOrDefault();
                        if (toUpdateInfo != null)
                        {
                            var toUpdate = context.Messages
                                           .Where(m => m.Id == toUpdateInfo.Id)
                                           .SingleOrDefault();
                            updated = true;

                            toUpdate.Text           = jmessage.Text;
                            toUpdate.Date           = jmessage.Time.GetChatovatkoString();
                            toUpdate.BlobMessagesId = messageId;

                            context.SaveChanges();
                        }
                    }

                    if (!updated)
                    {
                        context.Messages.Add(new Messages()
                        {
                            Date             = jmessage.Time.GetChatovatkoString(),
                            Text             = jmessage.Text,
                            IdMessagesThread = jmessage.MessageThreadId,
                            BlobMessagesId   = messageId
                        });
                        context.SaveChanges();
                    }
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to send this message.");
                }
                break;

            case JsonTypes.MESSAGES_THREAD:
                JMessageThread messageThread = (JMessageThread)decoded;
                permission = permission || (messageThread.WithUserId == senderId && !messageThread.DoOnlyDelete);
                if (permission)
                {
                    var old = context.MessagesThread
                              .Where(u => u.PublicId == messageThread.PublicId)
                              .SingleOrDefault();
                    if (messageThread.DoOnlyDelete && old != null)
                    {
                        context.Remove(old);
                    }
                    else if (messageThread.DoOnlyDelete)
                    {
                    }
                    else if (old != null)
                    {
                        old.Name           = messageThread.Name;
                        old.BlobMessagesId = messageId;
                        old.Archived       = messageThread.Archived;
                    }
                    else
                    {
                        context.MessagesThread.Add(new MessagesThread
                        {
                            Name           = messageThread.Name,
                            PublicId       = messageThread.PublicId,
                            Onlive         = messageThread.Onlive,
                            Archived       = messageThread.Archived,
                            WithUser       = messageThread.WithUserId,
                            BlobMessagesId = messageId
                        });
                    }
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to create/edit/delete this message thread.");
                }
                break;

            case JsonTypes.AES_KEY:
                JAESKey aesKey = (JAESKey)decoded;
                if (permission)
                {
                    var contact = context.Contacts
                                  .Where(c => c.PublicId == aesKey.UserId)
                                  .SingleOrDefault();
                    if (contact.SendAesKey != null)
                    {
                        throw new Exception($"AES key of user {contact.UserName} already exist.");
                    }
                    contact.SendAesKey = aesKey.AESKey;
                    context.SaveChanges();
                }
                else
                {
                    throw new Exception($"User with id {senderId} doesn't have permission to create AES keys to send.");
                }
                break;
            }
        }
示例#19
0
        public JsonResult update([FromBody] edu_relative_student obj)
        {
            var msg = new JMessage()
            {
                Error = true
            };

            try
            {
                var rs4 = _context.common_properties.SingleOrDefault(x => x.id == obj.idrelative);
                var rs3 = _context.edu_student.SingleOrDefault(x => x.id == 4);
                //  var rs2 = _context.edu_relative_student.SingleOrDefault(x => x.id == obj.id);//trước
                var rs  = _context.edu_relative_student.SingleOrDefault(x => x.id == obj.id);                                                 //student đang xét
                var rs1 = _context.edu_relative_student.SingleOrDefault(x => x.idstudenta == rs.idstudentb && x.idstudentb == rs.idstudenta); //student ace
                if (rs != null)
                {
                    if (obj.idstudentb == rs.idstudentb)
                    {
                        rs.id         = obj.id;
                        rs.idstudenta = 4;
                        rs.idstudentb = obj.idstudentb;
                        rs.idrelative = obj.idrelative;
                        _context.edu_relative_student.Update(rs);


                        rs1.idstudentb = 4;
                        rs1.idstudenta = obj.idstudentb;

                        if (rs3.sex == 0)//nữ
                        {
                            if (rs4.value.Contains("Anh") || rs4.value.Contains("Chị"))
                            {
                                rs1.idrelative = 489;
                            }
                            if (rs4.value.Contains("Em"))
                            {
                                rs1.idrelative = 4;
                            }
                        }

                        if (rs3.sex == 1)//nam
                        {
                            if (rs4.value.Contains("Anh") || rs4.value.Contains("Chị"))
                            {
                                rs1.idrelative = 5;
                            }
                            if (rs4.value.Contains("Em"))
                            {
                                rs1.idrelative = 3;
                            }
                        }
                        _context.edu_relative_student.Update(rs1);

                        _context.SaveChanges();
                        msg.Title = "Cập nhật thông tin thành công";
                        msg.Error = false;
                    }

                    else
                    {
                        msg.Title = "Không được sửa tên người thân";
                        msg.Error = true;
                    }
                }
            }
            catch (Exception ex)
            {
                msg.Object = ex;
                msg.Title  = "Có lỗi khi cập nhật";
            }
            return(Json(msg));
        }
示例#20
0
        public object DeleteItems([FromBody] List <int> listId)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                //_logger.LogInformation(LoggingEvents.LogDb, "Delete list application");
                List <int>           listRef         = new List <int>();
                List <int>           listDel         = new List <int>();
                List <AdApplication> listApplication = new List <AdApplication>();
                foreach (var id in listId)
                {
                    AdApplication obj = _context.AdApplications.FirstOrDefault(x => x.ApplicationId == id);
                    if (obj != null)
                    {
                        var pms     = _context.AdPermissions.FirstOrDefault(x => x.ApplicationCode == obj.ApplicationCode);
                        var appFunc = _context.AdAppFunctions.FirstOrDefault(x => x.ApplicationCode == obj.ApplicationCode);
                        if (appFunc != null || pms != null)
                        {
                            listRef.Add(id);
                        }
                        else
                        {
                            listDel.Add(id);
                        }
                    }
                }
                if (listRef.Count > 0)
                {
                    if (listDel.Count > 0)
                    {
                        foreach (var id in listDel)
                        {
                            AdApplication obj = _context.AdApplications.FirstOrDefault(x => x.ApplicationId == id);
                            listApplication.Add(obj);
                            _context.Remove(obj);
                        }
                        _context.SaveChanges();
                        msg.Error = true;
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_DEL_SUCCESS_LIST_ITEM_BUT_REF"), CommonUtil.ResourceValue("ADM_APP_LBL_APP").ToLower());
                        //_logger.LogError(LoggingEvents.LogDb, "Delete part of the application list successfully");
                        _actionLog.InsertActionLogDeleteItem("VIB_APPLICATION", "Delete part of the application list successfully", listApplication.ToArray(), null, "Delete");
                    }
                    else
                    {
                        msg.Error = true;
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_ERR_LIST_OBJ_REF"), CommonUtil.ResourceValue("ADM_APP_LBL_APP").ToLower());
                        //_logger.LogError(LoggingEvents.LogDb, "Delete list application fail");
                        _actionLog.InsertActionLogDeleteItem("VIB_APPLICATION", "Delete list application fail", null, null, "Error");
                    }
                }
                else
                {
                    if (listDel.Count > 0)
                    {
                        foreach (var id in listDel)
                        {
                            AdApplication obj = _context.AdApplications.FirstOrDefault(x => x.ApplicationId == id);
                            listApplication.Add(obj);

                            _context.AdApplications.Attach(obj);
                            _context.AdApplications.Remove(obj);
                        }
                        _context.SaveChanges();
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_DELETE_LIST_SUCCESS"),
                                                  CommonUtil.ResourceValue("ADM_APP_LBL_APP").ToLower());
                        //_logger.LogError(LoggingEvents.LogDb, "Delete part of the application list successfully");
                        _actionLog.InsertActionLogDeleteItem("VIB_APPLICATION", "Delete application list successfully", listApplication.ToArray(), null, "Delete");
                    }
                }
            }
            catch (Exception ex)
            {
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = String.Format(CommonUtil.ResourceValue("COM_MSG_DELETE_LIST_FAIL"), CommonUtil.ResourceValue("ADM_APP_LBL_APP").ToLower());
                //_logger.LogError(LoggingEvents.LogDb, "Delete list application fail");
                _actionLog.InsertActionLogDeleteItem("VIB_APPLICATION", "Delete list application failed: " + ex.Message, null, null, "Error");
            }
            return(Json(msg));
        }
示例#21
0
        private void Listen()
        {
            TcpClient    clienttmp = new TcpClient("127.0.0.1", this.port);
            BinaryReader reader    = new BinaryReader(clienttmp.GetStream());
            BinaryWriter writer    = new BinaryWriter(clienttmp.GetStream());

            try
            {
                while (true)
                {
                    string            received_data     = reader.ReadString();
                    JSON              received_object   = JSON.Deserialize(received_data);
                    ManagmentProtocol received_Protocol = received_object.Value.ToObject <ManagmentProtocol>();

                    if (received_Protocol.State == ManagmentProtocol.WHOIS)
                    {
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " receiving: receivedWhoIs", ConsoleColor.Blue);
                        //send name to management
                        ManagmentProtocol protocol = new ManagmentProtocol();
                        protocol.Name = this.virtualIp;
                        String send_object = JMessage.Serialize(JMessage.FromValue(protocol));
                        writer.Write(send_object);
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " sending: " + protocol.Name, ConsoleColor.Blue);
                    }
                    else if (received_Protocol.State == ManagmentProtocol.ROUTINGTABLES)
                    {
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " receiving: receivedroutingtable", ConsoleColor.Blue);
                        //receiving fibs
                        if (received_Protocol.RoutingTable != null)
                        {
                            foreach (var fib in received_Protocol.RoutingTable)
                            {
                                SwitchingField.addToSwitch(fib);
                                //adding fib for two-way communication
                                SwitchingField.addToSwitch(new FIB(fib.oport, fib.out_cont, fib.iport, fib.in_cont));
                            }
                        }
                    }
                    else if (received_Protocol.State == ManagmentProtocol.ROUTINGENTRY)
                    {
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " receiving: receivedroutingentry", ConsoleColor.Blue);
                        //receiving fibs
                        if (received_Protocol.RoutingEntry != null)
                        {
                            SwitchingField.addToSwitch(received_Protocol.RoutingEntry);
                            //adding fib for two-way communication
                            SwitchingField.addToSwitch(new FIB(received_Protocol.RoutingEntry.oport, received_Protocol.RoutingEntry.out_cont,
                                                               received_Protocol.RoutingEntry.iport, received_Protocol.RoutingEntry.in_cont));
                        }
                    }
                    else if (received_Protocol.State == ManagmentProtocol.INTERFACEINFORMATION)
                    {
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " receiving: iterfaceinformation", ConsoleColor.Blue);
                        //send dictionary from LRM to management
                        ManagmentProtocol protocol = new ManagmentProtocol();
                        protocol.State      = ManagmentProtocol.INTERFACEINFORMATION;
                        protocol.Interfaces = LRM.getConn();
                        String send_object = JMessage.Serialize(JMessage.FromValue(protocol));
                        writer.Write(send_object);
                    }
                    else if (received_Protocol.State == ManagmentProtocol.GETTABLE)
                    {
                        NetNode.log(DateTime.Now.ToLongTimeString() + " [Management]" + " receiving: getTable", ConsoleColor.Blue);
                        //send dictionary from LRM to management
                        ManagmentProtocol protocol = new ManagmentProtocol();
                        protocol.State        = ManagmentProtocol.GETTABLE;
                        protocol.RoutingTable = SwitchingField.fib;
                        String send_object = JMessage.Serialize(JMessage.FromValue(protocol));
                        writer.Write(send_object);
                    }
                    else
                    {
                        NetNode.log("[Management] undefined protocol", ConsoleColor.Red);
                    }
                }
            }
            catch (Exception e)
            {
                NetNode.log("\nError sending signal: " + e.Message, ConsoleColor.Red);
                Thread.Sleep(2000);
                Environment.Exit(1);
            }
        }
示例#22
0
        public async Task <JsonResult> InsertFunction([FromBody] AppFuncModel obj)
        {
            var msg = new JMessage()
            {
                Error = false
            };

            try
            {
                var app = _context.AdApplications.Where(p => p.ApplicationCode == obj.ApplicationCode).AsNoTracking().SingleOrDefault();
                if (app != null)
                {
                    // Add function
                    if (obj.FunctionAdd != null && obj.FunctionAdd.Count > 0)
                    {
                        foreach (var funcCode in obj.FunctionAdd)
                        {
                            var function = await _context.AdFunctions.FirstOrDefaultAsync(x => x.FunctionCode == funcCode);

                            if (function != null)
                            {
                                var appFunc = await _context.AdAppFunctions.FirstOrDefaultAsync(x => x.ApplicationCode == app.ApplicationCode && x.FunctionCode == funcCode);

                                if (appFunc == null)
                                {
                                    appFunc = new AdAppFunction();
                                    appFunc.ApplicationCode = app.ApplicationCode;
                                    appFunc.FunctionCode    = function.FunctionCode;
                                    _context.Add(appFunc);
                                }
                            }
                        }
                    }
                    // Remove function
                    if (obj.FunctionDel != null && obj.FunctionDel.Count > 0)
                    {
                        foreach (var funcCode in obj.FunctionDel)
                        {
                            var function = await _context.AdFunctions.FirstOrDefaultAsync(x => x.FunctionCode == funcCode);

                            if (function != null)
                            {
                                var appFunc = await _context.AdAppFunctions.FirstOrDefaultAsync(x => x.ApplicationCode == app.ApplicationCode && x.FunctionCode == funcCode);

                                if (appFunc != null)
                                {
                                    _context.Remove(appFunc);
                                }
                            }
                        }
                    }
                    await _context.SaveChangesAsync();

                    msg.Title = "Cập nhập chức năng cho ứng dụng thành công";
                    _actionLog.InsertActionLog("VIB_APP_FUNCTION", "Update function to application successfully", null, null, "Update");
                }
                else
                {
                    msg.Error = true;
                    msg.Title = "Ứng dụng đã tồn tại!";
                    //_logger.LogError(LoggingEvents.LogDb, "Insert function fail");
                }
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_ADD_FAIL"), CommonUtil.ResourceValue("FUNCTION")); //"Có lỗi khi thêm chức năng";
                //_logger.LogError(LoggingEvents.LogDb, "Insert function fail");
                _actionLog.InsertActionLog("VIB_APP_FUNCTION", "Update function to application failed: " + ex.Message, null, null, "Error");
            }
            return(Json(msg));
        }
示例#23
0
        public async Task <JsonResult> Update(edu_cat_ranking obj, IFormFile picture)
        {
            var msg = new JMessage()
            {
                Error = false, ID = 1
            };

            try
            {
                edu_cat_ranking rs = _context.edu_cat_ranking.FirstOrDefault(x => x.id == obj.id);
                if (rs != null)
                {
                    var icpicture = "";

                    if (picture != null && picture.Length > 0)
                    {
                        var pathUpload = Path.Combine(_hostingEnvironment.WebRootPath, "pictures\\avatar");
                        if (!Directory.Exists(pathUpload))
                        {
                            Directory.CreateDirectory(pathUpload);
                        }

                        var fileName = DateTimeOffset.Now.ToUnixTimeMilliseconds() + picture.FileName;
                        var filePath = Path.Combine(pathUpload, fileName);
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await picture.CopyToAsync(stream);
                        }
                        icpicture = "/pictures/avatar/" + fileName;
                    }
                    if (icpicture != "")
                    {
                        rs.picture = icpicture;
                    }
                    rs.name     = obj.name;
                    rs.priority = obj.priority;
                    rs.note     = obj.note;

                    rs.updatetime = DateTime.Now;
                    _context.edu_cat_ranking.Update(rs);
                    _context.SaveChanges();
                    msg.Title = "Sửa thông tin xếp hạng thành công";
                    msg.Error = false;
                    _actionLog.InsertActionLog("edu_cat_ranking", "update edu_cat_ranking successfully", rs, obj, "Update");
                }
                else
                {
                    msg.Title = "Xảy ra lỗi, vui lòng thử lại.";
                    msg.Error = true;
                }
            }
            catch (Exception ex)
            {
                msg.ID     = 0;
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi khi sửa khoản mục";
                _actionLog.InsertActionLog("edu_cat_ranking", "update edu_cat_ranking fail", null, obj, "Update");
            }
            return(Json(msg));
        }
        public async Task <JsonResult> UpdateUserPermission([FromBody] UserPerModel model)
        {
            JMessage msg = new JMessage {
                Error = true, Title = string.Format(CommonUtil.ResourceValue("MSG_UPDATE_FAIL"), CommonUtil.ResourceValue("PERMISSION").ToLower())
            };
            string userName = string.Empty;

            try
            {
                var user = await _context.Users.FirstOrDefaultAsync(x => x.Id == model.UserId);

                if (user != null)
                {
                    var app = await _context.AdApplications.FirstOrDefaultAsync(x => x.ApplicationCode == model.AppCode);

                    if (app != null)
                    {
                        // Update user is exceeded permission
                        user.IsExceeded = model.IsExceeded;

                        //// Update Branch Reference
                        //var oldBranchRef = user.OrgReference;
                        //user.OrgReference = model.BranchRefs.Count > 0 ? string.Join(",", model.BranchRefs) : "";
                        user.UpdatedDate = DateTime.Now;
                        user.UpdatedBy   = ESEIM.AppContext.UserName;
                        _context.Update(user);
                        //_actionLog.InsertActionLog("ASP_NET_USERS", "Update success branch reference of user: "******"Update", false, user.UserName);

                        // Update Group User and Permission
                        var listOldGroup         = _context.AdUserInGroups.Where(x => x.UserId == user.Id && x.ApplicationCode == app.ApplicationCode).ToList();
                        var listOldPermissionAll = _context.AdPermissions.Where(x => x.ApplicationCode == app.ApplicationCode && x.UserId == user.Id && listOldGroup.Any(y => y.GroupUserCode == x.GroupUserCode)).ToList();

                        if (model.GroupUsers.Count > 0)
                        {
                            var listOldGroupDel = listOldGroup.Where(x => model.GroupUsers.All(y => y.GroupCode != x.GroupUserCode)).ToList();
                            _context.RemoveRange(listOldGroupDel);      // Remove all old group not selected
                            var listOldPermissionDel = listOldPermissionAll.Where(x => model.GroupUsers.All(y => y.GroupCode != x.GroupUserCode || (y.GroupCode == x.GroupUserCode && y.RoleId != x.RoleId))).ToList();
                            _context.RemoveRange(listOldPermissionDel); // Remove all old permission

                            var listPermissionAll     = _context.AdPermissions.Where(x => x.ApplicationCode == model.AppCode && model.GroupUsers.Any(y => y.GroupCode == x.GroupUserCode && y.RoleId == x.RoleId)).ToList();
                            var listPermissionDefault = listPermissionAll.Where(x => x.UserId == null).ToList();
                            var listPermissionUser    = listPermissionAll.Where(x => x.UserId == model.UserId).ToList();

                            foreach (var groupUser in model.GroupUsers)
                            {
                                var oldGroup            = listOldGroup.FirstOrDefault(x => x.GroupUserCode == groupUser.GroupCode && x.ApplicationCode == model.AppCode);
                                var listPerDefaultGroup = listPermissionDefault.Where(x => x.GroupUserCode == groupUser.GroupCode && x.ApplicationCode == model.AppCode);
                                if (oldGroup != null)
                                {
                                    //if (groupUser.RoleId != oldGroup.RoleId)
                                    //{
                                    // Update user in group
                                    oldGroup.BranchReference = model.BranchRefs.Count > 0 ? string.Join(",", model.BranchRefs) : "";
                                    if (!oldGroup.IsMain)
                                    {
                                        oldGroup.RoleId = groupUser.RoleId;
                                    }
                                    oldGroup.GrantAll = true;
                                    _context.Update(oldGroup); // Update entity
                                    //}
                                }
                                else
                                {
                                    // Add user to group
                                    var userInGroup = new AdUserInGroup();
                                    userInGroup.UserId          = model.UserId;
                                    userInGroup.GroupUserCode   = groupUser.GroupCode;
                                    userInGroup.ApplicationCode = model.AppCode;
                                    userInGroup.RoleId          = groupUser.RoleId;
                                    userInGroup.GrantAll        = true;
                                    userInGroup.BranchReference = model.BranchRefs.Count > 0 ? string.Join(",", model.BranchRefs) : "";
                                    _context.Add(userInGroup); // Add entity
                                }

                                // Add or Update permission
                                if (groupUser.Resources != null && groupUser.Resources.Count > 0)
                                {
                                    groupUser.Resources = groupUser.Resources.Where(x => x.HasPermission && !x.IsFunction).ToList();
                                    // Get all permission need remove
                                    var permissionDel = listPermissionUser.Where(x => x.GroupUserCode == groupUser.GroupCode && x.RoleId == groupUser.RoleId && !groupUser.Resources.Any(y => y.FunctionCode == x.FunctionCode && y.Code == x.ResourceCode));
                                    _context.RemoveRange(permissionDel); // Remove all permission not in selected
                                    // Get all permission need update
                                    var permissionUpdate = listPermissionUser.Where(x => x.GroupUserCode == groupUser.GroupCode && x.RoleId == groupUser.RoleId && groupUser.Resources.Any(y => y.FunctionCode == x.FunctionCode && y.Code == x.ResourceCode)).ToList();
                                    if (permissionUpdate.Count > 0)
                                    {
                                        foreach (var perUpdate in permissionUpdate)
                                        {
                                            var resUpdate = groupUser.Resources.FirstOrDefault(y => y.FunctionCode == perUpdate.FunctionCode && y.Code == perUpdate.ResourceCode);
                                            perUpdate.ExpiredDate = resUpdate?.ExpiredDate;
                                        }
                                    }
                                    // Get all permission need add
                                    var permissionAdd = groupUser.Resources.Where(x => !listPermissionUser.Any(y => y.FunctionCode == x.FunctionCode && y.ResourceCode == x.Code && y.GroupUserCode == groupUser.GroupCode && y.RoleId == groupUser.RoleId))
                                                        .Select(x => new AdPermission
                                    {
                                        ApplicationCode = model.AppCode,
                                        FunctionCode    = x.FunctionCode,
                                        ResourceCode    = x.Code,
                                        GroupUserCode   = groupUser.GroupCode,
                                        UserId          = model.UserId,
                                        RoleId          = groupUser.RoleId,
                                        ExpiredDate     = x.ExpiredDate,
                                    }).ToList();
                                    _context.AddRange(permissionAdd); // Add entity
                                }
                                else
                                {
                                    //var permissionDel = listPermissionUser.Where(x => x.GroupUserCode == groupUser.GroupCode && x.RoleId == groupUser.RoleId && !listPerDefaultGroup.Any(y => y.FunctionCode == x.FunctionCode && y.ResourceCode == x.ResourceCode));
                                    //_context.RemoveRange(permissionDel); // Remove all permission not in selected

                                    var permissionAdd = listPerDefaultGroup.Where(x => !listPermissionUser.Any(y => y.FunctionCode == x.FunctionCode && y.ResourceCode == x.ResourceCode && y.GroupUserCode == groupUser.GroupCode && y.RoleId == groupUser.RoleId))
                                                        .Select(x => new AdPermission
                                    {
                                        ApplicationCode = x.ApplicationCode,
                                        FunctionCode    = x.FunctionCode,
                                        ResourceCode    = x.ResourceCode,
                                        GroupUserCode   = x.GroupUserCode,
                                        UserId          = model.UserId,
                                        RoleId          = x.RoleId,
                                    }).ToList();
                                    _context.AddRange(permissionAdd); // Add entity
                                }
                            }
                        }
                        else
                        {
                            _context.RemoveRange(listOldGroup);         // Remove all old group
                            _context.RemoveRange(listOldPermissionAll); // Remove all old permission
                        }
                        //_actionLog.InsertActionLog("VIB_PERMISSION", "Update success permission for user: "******"Update", false, user.UserName);

                        var result = await _context.SaveChangesAsync();

                        msg.Error = false;
                        msg.Title = "Update user permission successfully";
                    }
                    else
                    {
                        msg.Title = "Application is not exists in system!";
                    }
                }
                else
                {
                    msg.Title = "User is not exists in system!";
                }
            }
            catch (Exception ex)
            {
                //_actionLog.InsertActionLog("VIB_PERMISSION", "Update failed permission for user " + userName + " : " + ex.Message, null, null, "Error", true, userName);
                msg.Object = ex;
            }

            return(Json(msg));
        }
示例#25
0
 public SendResult Send(JMessage msg)
 {
     return(ApiHelper.SendMessage(msg));
 }
示例#26
0
        public JsonResult update([FromBody] edu_student_contact obj)
        {
            var msg = new JMessage()
            {
                Error = true
            };

            try
            {
                edu_student_contact_history his = new edu_student_contact_history();
                var rs1 = _context.edu_student_contact.SingleOrDefault(x => x.id == obj.id);
                var rs  = _context.edu_student_contact.SingleOrDefault(x => x.id == obj.id);
                if (rs != null)
                {
                    rs.id           = obj.id;
                    rs.name         = obj.name;
                    rs.company      = obj.company;
                    rs.telephone    = obj.telephone;
                    rs.mobilephone  = obj.mobilephone;
                    rs.email        = obj.email;
                    rs.relationship = obj.relationship;
                    rs.address      = obj.address;
                    rs.note         = obj.note;
                    rs.studentID    = obj.studentID;
                    rs.position     = obj.position;
                    rs.career       = obj.career;
                    _context.edu_student_contact.Update(rs);
                    if (rs1.name != obj.name)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "name";
                        his.old_value              = rs1.name;
                        his.old_value              = obj.name;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    if (rs1.company != obj.company)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "company";
                        his.old_value              = rs1.company;
                        his.old_value              = obj.company;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    if (rs1.telephone != obj.telephone)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "telephone";
                        his.old_value              = rs1.telephone;
                        his.old_value              = obj.telephone;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    if (rs1.mobilephone != obj.mobilephone)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "mobilephone";
                        his.old_value              = rs1.mobilephone;
                        his.old_value              = obj.mobilephone;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    if (rs1.email != obj.email)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "email";
                        his.old_value              = rs1.email;
                        his.old_value              = obj.email;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    if (rs1.relationship != rs.relationship)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "relationship";
                        his.old_value              = rs1.relationship.ToString();
                        his.old_value              = obj.relationship.ToString();
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }

                    if (rs1.address != obj.address)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "address";
                        his.old_value              = rs1.address;
                        his.old_value              = obj.address;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }

                    if (rs1.note != obj.note)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "note";
                        his.old_value              = rs1.note;
                        his.old_value              = obj.note;
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }

                    if (rs1.position != rs.position)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "position";
                        his.old_value              = rs1.position.ToString();
                        his.old_value              = obj.position.ToString();
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }

                    if (rs1.career != rs.career)
                    {
                        his.date_change            = DateTime.Now;
                        his.column_change          = "career";
                        his.old_value              = rs1.career.ToString();
                        his.old_value              = obj.career.ToString();
                        his.edu_student_contact_id = obj.id;
                        _context.edu_student_contact_history.Add(his);
                    }
                    _context.SaveChanges();
                    msg.Title = "Cập nhật thông tin thành công";
                    msg.Error = false;
                }
            }
            catch (Exception ex)
            {
                msg.Object = ex;
                msg.Title  = "Có lỗi khi cập nhật";
            }
            return(Json(msg));
        }
示例#27
0
        public JsonResult UpdateCandidateInfo([FromBody] CandidateInfo data)
        {
            var msg = new JMessage()
            {
                Error = false, Title = ""
            };

            try
            {
                #region check validate
                if (string.IsNullOrEmpty(data.CandidateCode))
                {
                    msg.Error = true;
                    msg.Title = "Bạn chưa lấy mã đăng ký trước!";
                    return(Json(msg));
                }

                if (string.IsNullOrEmpty(data.Fullname))
                {
                    msg.Error = true;
                    msg.Title = "Nhập họ tên!";
                    return(Json(msg));
                }
                else
                {
                    if (data.Fullname.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "Tên tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                if (string.IsNullOrEmpty(data.Phone))
                {
                    msg.Error = true;
                    msg.Title = "Nhập số điện thoại!";
                    return(Json(msg));
                }
                else
                {
                    if (data.Phone.Length > 50)
                    {
                        msg.Error = true;
                        msg.Title = "Số điện thoại chỉ tối đa 50 ký tự!";
                        return(Json(msg));
                    }
                }

                if (string.IsNullOrEmpty(data.Email))
                {
                    msg.Error = true;
                    msg.Title = "Nhập email!";
                    return(Json(msg));
                }
                else
                {
                    if (data.Email.Length > 100)
                    {
                        msg.Error = true;
                        msg.Title = "Email chỉ tối đa 100 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.Address))
                {
                    if (data.Address.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "Địa chỉ tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                if (!string.IsNullOrEmpty(data.Skype))
                {
                    if (data.Skype.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "Skype chỉ tối đa 255 ký tự!";
                        return(Json(msg));
                    }
                }

                //if (!string.IsNullOrEmpty(data.MainSkill))
                //{
                //    if (data.MainSkill.Length > 255)
                //    {
                //        msg.Title = "MainSkill chỉ tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (!string.IsNullOrEmpty(data.SubSkill))
                //{
                //    if (data.SubSkill.Length > 255)
                //    {
                //        msg.Title = "SubSkill chỉ tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (!string.IsNullOrEmpty(data.LanguageUse))
                //{
                //    if (data.LanguageUse.Length > 255)
                //    {
                //        msg.Title = "Ngôn ngữ chỉ tối đa 255 ký tự!";
                //        return Json(msg);
                //    }
                //}

                //if (!string.IsNullOrEmpty(data.Targeting))
                //{
                //    if (data.Targeting.Length > 500)
                //    {
                //        msg.Title = "Mục tiêu chỉ tối đa 500 ký tự!";
                //        return Json(msg);
                //    }
                //}

                if (!string.IsNullOrEmpty(data.FileCv_1))
                {
                    if (data.FileCv_1.Length > 255)
                    {
                        msg.Error = true;
                        msg.Title = "Tên file quá dài!";
                        return(Json(msg));
                    }
                }

                Regex regex1 = new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
                Match match  = regex1.Match(data.Email);
                if (!match.Success)
                {
                    msg.Error = true;
                    msg.Title = "Email không hợp lệ!";
                    return(Json(msg));
                }
                #endregion

                var can = _context.CandiateBasic.FirstOrDefault(x => x.CandidateCode.Equals(data.CandidateCode));

                can.Fullname = data.Fullname;
                //can.Ability = string.IsNullOrEmpty(data.Ability) ? "" : data.Ability.Remove(data.Ability.Length - 1, 1);
                can.Address  = data.Address;
                can.Birthday = string.IsNullOrEmpty(data.Birthday) ? (DateTime?)null : DateTime.ParseExact(data.Birthday, "dd/MM/yyyy", CultureInfo.InvariantCulture);

                if (can.Birthday != null)
                {
                    decimal age = (decimal)(DateTime.Now - can.Birthday).Value.TotalDays / 365.25m;
                    if (age < 18)
                    {
                        msg.Error = true;
                        msg.Title = "Bạn chưa đủ 18 tuổi!";
                        return(Json(msg));
                    }
                }

                //can.CanJoinDate = string.IsNullOrEmpty(data.CanJoinDate) ? (DateTime?)null : DateTime.ParseExact(data.CanJoinDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                can.Email = data.Email;
                //can.MainPracticeTime = data.MainPracticeTime;
                can.Married = data.Married == "0" ? false : true;
                can.Phone   = data.Phone;
                //can.SalaryHope = string.IsNullOrEmpty(data.SalaryHope) ? 0 : decimal.Parse(data.SalaryHope);
                can.Sex   = int.Parse(data.Sex);
                can.Skype = data.Skype;
                //can.MainSkill = data.MainSkill;
                //can.SubSkill = data.SubSkill;
                //can.LanguageUse = data.LanguageUse;
                //can.SubPracticeTime = data.SubPracticeTime;
                can.Targeting   = data.Targeting;
                can.FileCv_1    = data.FileCv_1;
                can.UpdatedTime = DateTime.Now;
                //can.LaptopInfo = data.LaptopInfo;
                //can.SmartphoneInfo = data.SmartphoneInfo;
                //can.WorkPlace = data.WorkPlace;
                _context.CandiateBasic.Update(can);
                _context.SaveChanges();
                msg.Title = "Lưu lại thông tin thành công!";
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = "Có lỗi xảy ra!";
            }
            return(Json(msg));
        }
示例#28
0
        public JsonResult Insert(AddonAppModel obj, IFormFile icon)
        {
            var msg = new JMessage()
            {
                Error = false, Title = ""
            };

            try
            {
                var checkExist = _context.AddonApps.FirstOrDefault(x => x.AppCode.ToLower() == obj.AppCode.ToLower());
                if (checkExist != null)
                {
                    msg.Error = true;
                    msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_EXITS"), CommonUtil.ResourceValue("ADA_MSG_CODE_APP"));
                }
                else
                {
                    if (icon != null)
                    {
                        var upload = _upload.UploadImage(icon);
                        if (!upload.Error)
                        {
                            var model = new AddonApp
                            {
                                AppCode    = obj.AppCode,
                                AppTitle   = obj.AppTitle,
                                AppDate    = !string.IsNullOrEmpty(obj.AppDate) ? DateTime.ParseExact(obj.AppDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                                LinkChplay = obj.LinkChplay,
                                Icon       = "/uploads/images/" + upload.Object.ToString(),
                                Status     = obj.Status,
                                Note       = obj.Note
                            };
                            _context.AddonApps.Add(model);
                            _context.SaveChanges();
                            msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_ADD_SUCCESS"), CommonUtil.ResourceValue("ADA_MSG_APP"));
                        }
                    }
                    else
                    {
                        var model = new AddonApp
                        {
                            AppCode    = obj.AppCode,
                            AppTitle   = obj.AppTitle,
                            AppDate    = !string.IsNullOrEmpty(obj.AppDate) ? DateTime.ParseExact(obj.AppDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null,
                            LinkChplay = obj.LinkChplay,
                            Status     = obj.Status,
                            Note       = obj.Note
                        };
                        _context.AddonApps.Add(model);
                        _context.SaveChanges();
                        msg.Title = String.Format(CommonUtil.ResourceValue("COM_MSG_ADD_SUCCESS"), CommonUtil.ResourceValue("ADA_MSG_APP"));
                    }
                }
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = String.Format(CommonUtil.ResourceValue("COM_ERR_ADD"));
            }
            return(Json(msg));
        }
示例#29
0
        public JsonResult InsertEventCat([FromBody] EventCat data)
        {
            var msg = new JMessage()
            {
                Error = false, Title = ""
            };

            try
            {
                var fromDate        = DateTime.ParseExact(data.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                var toDate          = DateTime.ParseExact(data.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                var appointmentTime = string.IsNullOrEmpty(data.AppointmentTime) ? DateTime.ParseExact(data.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) : (DateTime?)null;

                var candidate = _context.CandiateBasic.FirstOrDefault(x => x.CandidateCode == data.CandidateCode);
                if (candidate != null)
                {
                    //update candidate
                    candidate.WorkFrom        = fromDate;
                    candidate.WorkTo          = toDate;
                    candidate.AppointmentTime = appointmentTime;
                    _context.CandiateBasic.Update(candidate);


                    //insert,update event
                    var listEvent = _context.CandidateWorkEvents.Where(x => x.CandidateCode == data.CandidateCode);
                    if (listEvent.Any())
                    {
                        _context.CandidateWorkEvents.RemoveRange(listEvent);
                    }

                    for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
                    {
                        string frameTime = data.Morning.ToString() + ";" +
                                           data.Afternoon.ToString() + ";" +
                                           data.Evening.ToString();
                        var evt = new CandidateWorkEvent
                        {
                            CandidateCode = data.CandidateCode,
                            FrameTime     = frameTime,
                            CreatedTime   = DateTime.Now,
                            DatetimeEvent = date,
                        };
                        _context.CandidateWorkEvents.Add(evt);
                    }
                    _context.SaveChanges();
                    msg.Title = "Đăng ký thành công!";
                }
                else
                {
                    msg.Error = true;
                    msg.Title = "Ứng viên không tồn tại!";
                }
            }
            catch (Exception ex)
            {
                msg.Error  = true;
                msg.Object = ex;
                msg.Title  = "Có lỗi xảy ra đăng ký!";
            }
            return(Json(msg));
        }
        public T GetMessage <T>(string message)
        {
            JMessage mess = JMessage.Deserialize(message);

            return(mess.ToValue <T>());
        }