Example #1
0
 public ActionResult UpdateAndCreate(string chkType, string chkAutoUpload, News newDetail)
 {
     try
     {
         if (newDetail.Id > 0)
         {
             if (isChief || (newDetail.CreatedBy == SysBaseInfor.GetCurrentUserId() && (newDetail.Status == 0 || newDetail.Status == 4)))
             {
                 NewsDAL objCtrl = new NewsDAL();
                 newDetail.Type      = !string.IsNullOrEmpty(chkType) ? (byte)1 : (byte)0;
                 newDetail.UpdatedAt = DateTime.Now;
                 newDetail.UpdatedBy = SysBaseInfor.GetCurrentUserId();
                 newDetail.UnitId    = SysBaseInfor.GetCurrentUnitId().ToInt32();
                 if (!string.IsNullOrEmpty(chkAutoUpload))
                 {
                     var tmpContent = UploadAllImageInNewsToServer(newDetail.FullContent, newDetail.Id);
                     if (!string.IsNullOrEmpty(tmpContent))
                     {
                         newDetail.FullContent = tmpContent;
                     }
                 }
                 objCtrl.UpdateItem(newDetail);
                 return(Json(new { msg = "Success", idNews = newDetail.Id, typeAction = "UpdateAndCreate" }));
             }
         }
         return(Json(new { msg = "Thao tác không thực hiện được" }));
     }
     catch (Exception ex)
     {
         return(Json(new { msg = ex.Message }));
     }
 }
Example #2
0
        public PartialViewResult FileUploadBrowser(int key)
        {
            try
            {
                var RootDir = Server.MapPath(string.Format("~/UserImages/{0}/{1}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment));
                if (!Directory.Exists(RootDir))
                {
                    Directory.CreateDirectory(RootDir);
                }

                var subDirectories = Directory.GetDirectories(RootDir);
                var lstDateTimeDir = new List <string>();
                foreach (var tmp in subDirectories)
                {
                    lstDateTimeDir.Add(tmp.Split('\\').LastOrDefault());
                }
                ViewBag.lstDateTimeDir = lstDateTimeDir;
                ViewBag.lastDir        = lstDateTimeDir.Last();
                return(PartialView("~/Views/NewsManage/UploadPartial/FileUploadBrowserView.cshtml"));
            }
            catch (Exception ex)
            {
                return(PartialView(blankViewUrl));
            }
        }
 public JsonResult SaveDetailUnitReport(UnitReport objReport)
 {
     try
     {
         UnitReportDAL objCtrl = new UnitReportDAL();
         if (objReport.DayReport != null)
         {
             objReport.DayReport = objReport.DayReport.ToLocalTime();
         }
         if (objReport.Id > 0)
         {
             objReport.UpdatedBy = SysBaseInfor.GetCurrentUserId();
             objCtrl.UpdateItem(objReport);
             return(Json(new { Msg = "Success", Type = "Edit" }));
         }
         else
         {
             objReport.Status    = 0;
             objReport.CreatedBy = SysBaseInfor.GetCurrentUserId();
             objReport.UnitId    = SysBaseInfor.GetCurrentUnitId().ToInt32();
             objCtrl.CreateItem(objReport);
             return(Json(new { Msg = "Success", Type = "Create" }));
         }
     }
     catch (Exception ex)
     {
         return(Json(new { Msg = "Fail" }));
     }
 }
Example #4
0
 public string UploadAllImageInNewsToServer(string contentNews, int newsId)
 {
     try
     {
         UnitsDAL unitCtrl = new UnitsDAL();
         var      unitTmp = unitCtrl.GetItemByID("Id", SysBaseInfor.GetCurrentUnitId().ToInt32());
         var      mediaUrl = unitTmp.MediaUrl;
         var      tmpContentNews = contentNews;
         var      linkParser = new Regex(@"\b(?:https?://|www\.)[^ \f\n\r\v\t\""\'\]]+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
         string   link, linkNew;
         foreach (Match m in linkParser.Matches(contentNews))
         {
             link = m.Value;
             if (link.IndexOf(mediaUrl) < 0)
             {
                 linkNew = UploadImageToServer(HttpUtility.HtmlDecode(link), newsId, mediaUrl);
                 if (!string.IsNullOrEmpty(linkNew))
                 {
                     tmpContentNews = tmpContentNews.Replace(link, linkNew);
                 }
             }
         }
         return(tmpContentNews);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Example #5
0
        public JsonResult SaveDetailWorkCalendar(UnitWorkCalendar objWorkCalendar)
        {
            try
            {
                UnitWorkCalendarDAL objCtrl = new UnitWorkCalendarDAL();

                if (objWorkCalendar.DayWorkCalendar != null)
                {
                    objWorkCalendar.DayWorkCalendar = objWorkCalendar.DayWorkCalendar.ToLocalTime();
                }

                if (objWorkCalendar.Id > 0)
                {
                    objWorkCalendar.UpdatedBy = SysBaseInfor.GetCurrentUserId();
                    objCtrl.UpdateItem(objWorkCalendar);
                    return(Json(new { Msg = "Success", Type = "Edit" }));
                }
                else
                {
                    objWorkCalendar.Status    = 0;
                    objWorkCalendar.CreatedBy = SysBaseInfor.GetCurrentUserId();
                    objWorkCalendar.UnitId    = SysBaseInfor.GetCurrentUnitId().ToInt32();
                    objCtrl.CreateItem(objWorkCalendar);
                    return(Json(new { Msg = "Success", Type = "Create" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { Msg = "Fail" }));
            }
        }
 public JsonResult GetListAlum()
 {
     try
     {
         var ctrlPUA  = new PictureUserAlbumDAL();
         var lstAlbum = ctrlPUA.GetListUserAlbumByUnitAndUser(SysBaseInfor.GetCurrentUnitId().ToInt32(), SysBaseInfor.GetCurrentUserId());
         return(Json(lstAlbum));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
Example #7
0
        public ActionResult CreateNews(string chkType, string chkAutoUpload, News newDetail)
        {
            try
            {
                if (string.IsNullOrEmpty(newDetail.Title))
                {
                    return(Json(new { msg = "Bạn phải nhập tiêu đề" }));
                }
                if (string.IsNullOrEmpty(newDetail.Summary))
                {
                    return(Json(new { msg = "Bạn phải nhập tóm tắt" }));
                }
                if (newDetail.CategoryID <= 0)
                {
                    return(Json(new { msg = "Bạn phải chọn chuyên mục" }));
                }
                if (newDetail.Id == 0)
                {
                    CategoriesDAL categoryCtrl = new CategoriesDAL();
                    var           category     = categoryCtrl.GetItemByID("Id", newDetail.CategoryID);

                    NewsDAL objCtrl = new NewsDAL();
                    newDetail.Type      = !string.IsNullOrEmpty(chkType) ? (byte)1 : (byte)0;
                    newDetail.Active    = 1;
                    newDetail.UnitId    = SysBaseInfor.GetCurrentUnitId().ToInt32();
                    newDetail.CreatedAt = DateTime.Now;
                    newDetail.CreatedBy = SysBaseInfor.GetCurrentUserId();
                    newDetail.Status    = isChief ? (byte)1 : (byte)0;
                    objCtrl.CreateItem(newDetail);

                    if (newDetail.Id > 0 && !string.IsNullOrEmpty(chkAutoUpload))
                    {
                        var tmpContent = UploadAllImageInNewsToServer(newDetail.FullContent, newDetail.Id);
                        if (!string.IsNullOrEmpty(tmpContent))
                        {
                            newDetail.FullContent = tmpContent;
                        }
                        objCtrl.UpdateItem(newDetail);
                    }
                    return(Json(new { msg = "Success", idNews = newDetail.Id, typeAction = "Create" }));
                }
                else
                {
                    return(Json(new { msg = "Thao tác không thực hiện được" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { msg = ex.Message }));
            }
        }
Example #8
0
 public PartialViewResult GetListImg(string inDir)
 {
     if (!string.IsNullOrEmpty(inDir))
     {
         var RootDir  = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, inDir, SysBaseInfor.GetCurrentUserId()));
         var uriImage = string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, inDir, SysBaseInfor.GetCurrentUserId());
         var images   = Directory.GetFiles(RootDir).Select(x => new ImageUploadView
         {
             Url = Url.Content(uriImage + Path.GetFileName(x))
         });
         return(PartialView("~/Views/NewsManage/UploadPartial/_ListImageShow.cshtml", images));
     }
     return(PartialView(blankViewUrl));
 }
 public JsonResult GetListUserInUnit(string roleId)
 {
     try
     {
         var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
         int unitId      = SysBaseInfor.GetCurrentUnitId().ToInt32();
         var usersInUnit = userManager.Users.Where(x => x.UnitId == unitId && x.Type != 0 && x.Type != 1).ToList();
         return(Json(usersInUnit));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
        public JsonResult UploadDropZone(int?idAlbum)
        {
            string urlImage = "";

            try
            {
                if (idAlbum != null && idAlbum.GetValueOrDefault() > 0)
                {
                    var ctrlUI = new PictureUserDAL();
                    foreach (string fileName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[fileName];

                        if (file != null && file.ContentLength > 0)
                        {
                            var strDateTime = DateTime.Now.ToString("dd-MM-yyyy");
                            var fName       = idAlbum + "_" + Guid.NewGuid() + Path.GetExtension(file.FileName);
                            urlImage = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), SysBaseDirectory.pictureUploaded, strDateTime, fName);
                            var userPath = string.Format("{0}{1}/", userPictureUploadedPath, strDateTime);
                            if (!Directory.Exists(userPath))
                            {
                                Directory.CreateDirectory(userPath);
                            }
                            string path = Path.Combine(userPath, fName);
                            file.SaveAs(path);

                            var pictureSave = new PictureUser();
                            pictureSave.IdAlbum     = idAlbum.GetValueOrDefault();
                            pictureSave.IdUnit      = SysBaseInfor.GetCurrentUnitId().ToInt32();
                            pictureSave.CreatedBy   = SysBaseInfor.GetCurrentUserId();
                            pictureSave.CreatedAt   = DateTime.Now;
                            pictureSave.PictureUrl  = urlImage;
                            pictureSave.PictureName = fName;
                            ctrlUI.CreateItem(pictureSave);
                        }
                    }
                    return(Json(new { urlImage = urlImage }));
                }
                else
                {
                    return(Json("Có lỗi khi tải lên"));
                }
            }
            catch (Exception ex)
            {
                return(Json("Có lỗi khi tải lên"));
            }
        }
        public async Task <JsonResult> Register(RegisterViewModel model)
        {
            var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email, DisplayName = model.DisplayName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    //await UserManager.SendEmailAsync(user.Id, "Kích hoạt tài khoản", "Để kích hoạt tài khoản,vui lòng bấm vào đường dẫn <a href=\"" + callbackUrl + "\">link</a>");

                    user.Type     = 2;
                    user.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                    user.UnitName = SysBaseInfor.GetCurrentUnitCode().ToLower();
                    var resultActive = UserManager.SetLockoutEnabled(user.Id, false);
                    if (resultActive.Succeeded)
                    {
                        var roleForUserName = user.UserName + "_" + SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject;
                        var roleForUser     = roleManager.FindByName(roleForUserName);
                        if (roleForUser == null)
                        {
                            roleForUser          = new ApplicationRole(roleForUserName);
                            roleForUser.RoleType = 3;
                            roleForUser.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                            var roleResult = roleManager.Create(roleForUser);
                            if (roleResult.Succeeded)
                            {
                                UserManager.AddToRole(user.Id, roleForUserName);
                                return(Json("Success"));
                            }
                        }
                    }
                    else
                    {
                        return(Json(resultActive.Errors.FirstOrDefault()));
                    }
                }
                return(Json(result.Errors.FirstOrDefault()));
            }
            return(Json("Không thể tạo người dùng"));
        }
        // Create Sample Admin User: [email protected] with password: Admin@123456 in the Admin role
        private static void InitializeIdentity(IOwinContext context)
        {
            var userManager = context.GetUserManager <ApplicationUserManager>();

            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                // This disables the validation check on email addresses
                RequireUniqueEmail = false
            };
            var    roleManager = context.Get <ApplicationRoleManager>();
            string name        = SysBaseInfor.SuperAdmin;
            string password    = SysBaseInfor.SuperAdminPass;
            string roleName    = SysBaseInfor.SuperAdminRoleName;

            //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);

            if (role == null)
            {
                role          = new ApplicationRole(roleName);
                role.RoleType = 0;
                role.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationUser {
                    UserName = name
                };
                user.Type     = 0;
                user.TypeInfo = 0;
                user.UnitId   = 0;
                user.UnitName = SysBaseInfor.DefaultUnit;
                var result = userManager.Create(user, password);
                result = userManager.SetLockoutEnabled(user.Id, false);
            }
            // Add user admin to Role Admin if not already added
            var rolesForUser = userManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                var result = userManager.AddToRole(user.Id, role.Name);
            }
        }
        private bool Create(string username, string displayname, string password, string roleId)
        {
            var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName    = username,
                    DisplayName = displayname
                };
                var result = UserManager.Create(user, password);
                if (result.Succeeded)
                {
                    user.Type     = 2;
                    user.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                    user.UnitName = SysBaseInfor.GetCurrentUnitCode().ToLower();
                    try { user.TypeInfo = int.Parse(DBLibs.ExecuteScalar($"SELECT TOP 1 id FROM GiaoVien WHERE magv = N'{username.Replace("'", "''")}'", _cnn).ToString()); }
                    catch { }
                    var resultActive = UserManager.SetLockoutEnabled(user.Id, false);
                    if (resultActive.Succeeded)
                    {
                        try
                        {
                            var sql = $@"
                            INSERT INTO dbo.AspNetUserRoles
                            ( UserId, RoleId )
                            VALUES
                            (
	                            N'{user.Id}', -- UserId - nvarchar(128)
	                            N'{roleId}'  -- RoleId - nvarchar(128)
                            )";
                            DBLibs.ExecuteNonQuery(sql, _cnn);
                        }
                        catch { }
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                return(false);
            }
            return(false);
        }
        public async Task <JsonResult> Create(RoleViewModel roleViewModel)
        {
            if (ModelState.IsValid)
            {
                var sign = "_" + SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject;
                var role = new ApplicationRole(roleViewModel.Name + sign);
                role.RoleType = 2;
                role.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                var roleresult = await RoleManager.CreateAsync(role);

                if (!roleresult.Succeeded)
                {
                    ModelState.AddModelError("", roleresult.Errors.First());
                    return(Json("Có lỗi xảy ra, vui lòng thử lại"));
                }
                return(Json("Success"));
            }
            return(Json("Có lỗi xảy ra, vui lòng thử lại"));
        }
Example #15
0
 public JsonResult GetListUnitWorkCalendarByWeek(byte?IPS, int?limit, int?offset)
 {
     try
     {
         DateTime            startOfWeek            = DateTime.Today.AddDays(-1 * (int)(DateTime.Today.DayOfWeek) + 1);
         DateTime            endOfWeek              = startOfWeek.AddDays(6);
         UnitWorkCalendarDAL WorkCalendarReportCtrl = new UnitWorkCalendarDAL();
         var lstResult = new List <UnitWorkCalendar>();
         if (IPS == 1)
         {
             lstResult = WorkCalendarReportCtrl.GetListWorkCalendarByWeek(SysBaseInfor.GetCurrentUnitId().ToInt32(), startOfWeek, endOfWeek);
             return(Json(lstResult));
         }
         return(Json(lstResult));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
 public JsonResult GetListReportByDay(byte?IPS, int?limit, int?offset)
 {
     try
     {
         UnitReportDAL UnitReportReportCtrl = new UnitReportDAL();
         var           lstResult            = new List <UnitReport>();
         if (IPS == 1)
         {
             var parameterList = new List <KeyValuePair <string, string> >();
             parameterList.Add(new KeyValuePair <string, string>("UnitId", SysBaseInfor.GetCurrentUnitId()));
             parameterList.Add(new KeyValuePair <string, string>("DayReport", DateTime.Now.Date.ToString("yyyy-MM-dd")));
             lstResult = UnitReportReportCtrl.GetListItems(parameterList);
             return(Json(lstResult));
         }
         return(Json(lstResult));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
 public PartialViewResult TabDefaultGalleryView(string dirSelect)
 {
     if (!string.IsNullOrEmpty(dirSelect))
     {
         int idAlbum = 0;
         if (int.TryParse(dirSelect, out idAlbum))
         {
             var ctrlUI = new PictureUserDAL();
             var lstImg = ctrlUI.GetLstByUnitAndUser(SysBaseInfor.GetCurrentUnitId().ToInt32(), SysBaseInfor.GetCurrentUserId(), idAlbum).Select(item => new GalereyaImage
             {
                 lowsrc      = item.PictureUrl,
                 fullsrc     = item.PictureUrl,
                 description = "Ngày tải: " + item.CreatedAt.ToString("dd/MM/yyyy"),
                 category    = item.IdAlbum.ToString()
             }).ToArray();
             ViewBag.lstImgTabDefault = lstImg;
             ViewBag.dirSelect        = dirSelect;
             return(PartialView("~/Views/PictureManage/_PictureDefaultGallery.cshtml"));
         }
         else
         {
             var           uriImage   = string.Format("/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), dirSelect);
             DirectoryInfo currentDir = new DirectoryInfo(userPicturePath + "/" + dirSelect + "/");
             var           lstImg     = currentDir.GetFiles().OrderBy(fi => fi.CreationTime).Select(fi => new GalereyaImage
             {
                 lowsrc      = Url.Content(uriImage + Path.GetFileName(fi.Name)),
                 fullsrc     = Url.Content(uriImage + Path.GetFileName(fi.Name)),
                 description = "Ngày tải: " + fi.CreationTime.ToString("dd/MM/yyyy"),
                 category    = dirSelect
             }).ToArray();
             ViewBag.lstImgTabDefault = lstImg;
             ViewBag.dirSelect        = dirSelect;
             return(PartialView("~/Views/PictureManage/_PictureDefaultGallery.cshtml"));
         }
     }
     else
     {
         return(PartialView("~/Views/Shared/_blank.cshtml"));
     }
 }
        public async Task <ActionResult> Details(string roleId)
        {
            if (roleId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
            int unitId      = SysBaseInfor.GetCurrentUnitId().ToInt32();
            var usersInUnit = userManager.Users.Where(x => x.UnitId == unitId && x.Type != 0 && x.Type != 1);

            ViewBag.lstAllUser = new SelectList(usersInUnit.ToList(), "Id", "UserName");
            var role = await RoleManager.FindByIdAsync(roleId);

            RoleViewModel roleModel = new RoleViewModel();

            roleModel.Id = role.Id;
            var sign = "_" + SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject;

            roleModel.Name     = role.Name.Replace(sign, "");
            roleModel.unitId   = role.UnitId;
            roleModel.roleType = role.RoleType;
            return(PartialView(roleModel));
        }
 public JsonResult SaveListAlbum(List <PictureUserAlbum> lstListAlbum)
 {
     try
     {
         var ctrlPUA = new PictureUserAlbumDAL();
         if (lstListAlbum != null && lstListAlbum.Count > 0)
         {
             foreach (PictureUserAlbum item in lstListAlbum)
             {
                 item.IdUser    = SysBaseInfor.GetCurrentUserId();
                 item.IdUnit    = SysBaseInfor.GetCurrentUnitId().ToInt32();
                 item.CreatedAt = DateTime.Now;
                 item.Active    = true;
                 ctrlPUA.CreateNewOrUpdate(item);
             }
         }
         return(Json("Success"));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
Example #20
0
        public JsonResult GetListUnitWorkCalendarByDay(byte?IPS, int?limit, int?offset)
        {
            try
            {
                UnitWorkCalendarDAL workCalendarCtrl = new UnitWorkCalendarDAL();
                var lstResult = new List <UnitWorkCalendar>();
                if (IPS == 1)
                {
                    //var parameterList = new List<KeyValuePair<string, string>>();
                    //parameterList.Add(new KeyValuePair<string, string>("UnitId", SysBaseInfor.GetCurrentUnitId()));
                    //parameterList.Add(new KeyValuePair<string, string>("DayWorkCalendar", DateTime.Now.Date.ToString("yyyy-MM-dd")));
                    //lstResult = workCalendarCtrl.GetListItems(parameterList);

                    lstResult = workCalendarCtrl.GetListWorkCalendarByDay(SysBaseInfor.GetCurrentUnitId().ToInt32(), DateTime.Now);
                    return(Json(lstResult));
                }
                return(Json(lstResult));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message));
            }
        }
        //[ProjectCustomFilter(UserPermissions.QuyenXem)]
        public ActionResult Index()
        {
            var roleManager        = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();
            var GetCurrentUserName = SysBaseInfor.GetCurrentUserName().ToLower();

            if (SysBaseInfor.GetCurrentUserName().ToLower() == SysBaseInfor.SuperAdmin)
            {
                //var lstRoles = roleManager.Roles;
                //ViewBag.SelectLstRoles = new SelectList(lstRoles, "ID", "Name", "RoleType", 0);
                var sql = "SELECT * FROM AspNetRoles ORDER BY RoleType";
                ViewBag.SelectLstRoles = DBLibs.GetDataBy_DataAdapter(sql, _cnn);
            }
            else
            {
                var lstRoles = roleManager.GetListRoleByUnitId(SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject, SysBaseInfor.GetCurrentUnitId().ToInt32());
                ViewBag.SelectLstRoles = new SelectList(lstRoles, "ID", "Name", "RoleType", 0);
            }
            return(View());
        }
        public ActionResult GetUserAccessRight(string userId, int?isPopup)
        {
            try
            {
                if (!String.IsNullOrEmpty(userId))
                {
                    var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    var user        = userManager.FindById(userId);
                    if (user != null)
                    {
                        var roleForUserName = user.UserName + "_" + SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject;
                        var roleManager     = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();
                        var roleForUser     = roleManager.FindByName(roleForUserName);
                        if (roleForUser == null)
                        {
                            roleForUser          = new ApplicationRole(roleForUserName);
                            roleForUser.RoleType = 3;
                            roleForUser.UnitId   = SysBaseInfor.GetCurrentUnitId().ToInt32();
                            var roleResult = roleManager.Create(roleForUser);
                            if (roleResult.Succeeded)
                            {
                                userManager.AddToRole(user.Id, roleForUserName);
                            }
                        }

                        if (!string.IsNullOrEmpty(roleForUser.Id))
                        {
                            var roleId = roleForUser.Id;
                            ViewBag.NhomNguoiDungKey  = roleId;
                            ViewBag.NhomNguoiDungName = roleForUserName.Replace("_" + SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject, "");
                            ViewBag.RoleType          = roleForUser.RoleType;
                            var model = CreateTreeData();
                            SYS_MENU_ROLE_CTRL smrCtrl = new SYS_MENU_ROLE_CTRL();
                            var nhomNguoiDungLstRoles  = smrCtrl.GetListItemsHaveWhere(String.Format("ID_ROLE = '{0}'", roleId));
                            foreach (SYS_MENU_ROLE tmpSmr in nhomNguoiDungLstRoles)
                            {
                                JsTreeModel tmpNode = FindNodeInTree(model, tmpSmr.ID_SYS_MENU);

                                if (tmpNode != null && (tmpNode.children == null || tmpNode.children.Count == 0))
                                {
                                    tmpNode.data = new
                                    {
                                        quyenXem     = (tmpSmr.ACCESS_RIGHT[0] == '1') ? true : false,
                                        quyenThemMoi = (tmpSmr.ACCESS_RIGHT[1] == '1') ? true : false,
                                        quyenSua     = (tmpSmr.ACCESS_RIGHT[2] == '1') ? true : false,
                                        quyenXoa     = (tmpSmr.ACCESS_RIGHT[3] == '1') ? true : false,
                                        quyenChuyen  = (tmpSmr.ACCESS_RIGHT[4] == '1') ? true : false,
                                        quyenDuyet   = (tmpSmr.ACCESS_RIGHT[5] == '1') ? true : false,
                                        quyenXuatBan = (tmpSmr.ACCESS_RIGHT[6] == '1') ? true : false
                                    };
                                    tmpNode.state = new { opened = true, @checked = true };
                                }
                            }
                            if (isPopup > 0)
                            {
                                return(PartialView("~/Views/SysMenuManage/_ModalTreeRightSelect.cshtml", model));
                            }
                            else
                            {
                                return(PartialView("~/Views/SysMenuManage/_TreeRightSelect.cshtml", model));
                            }
                        }
                    }
                }
                return(PartialView(blankViewUrl));
            }
            catch (Exception ex)
            {
                return(PartialView(blankViewUrl));
            }
        }
Example #23
0
        public JsonResult Save(
            int id                   = 0,
            int status               = 0,
            string _title            = "",
            string _slug             = "",
            string _thumbnail        = "",
            string _sapo             = "",
            string _content          = "",
            string _related          = "",
            string _cates            = "",
            string _cates_slug       = "",
            string _tags             = "",
            string _tags_slug        = "",
            string _meta_keywords    = "",
            string _meta_description = "")
        {
            var stt = false;
            var msg = "";

            #region Phân tích request/submit form (nếu có)
            if (_title == null || _title.Trim() == "")
            {
                msg = "Tên gian hàng không được để trống";
            }
            if (_slug == null || _slug.Trim() == "")
            {
                msg = "Slug không được để trống";
            }
            else
            {
                if (id < 1)
                {
                    #region Thêm bài viết
                    var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM News WHERE slug = N'{_slug.Replace("'", "''").Trim()}' OR title = N'{_title.Replace("'", "''").Trim()}'", _cnn);
                    if (exited != null && int.Parse(exited.ToString()) > 0)
                    {
                        return(Json(new
                        {
                            status = false,
                            message = "Đã có bài viết có cùng tiêu đề hoặc url!"
                        }));
                    }
                    var newid = DBLibs.ExecuteScalar($@"
                    INSERT INTO dbo.News
                    (
                        Slug ,
                        UnitId ,
                        Title ,
                        Thumbnail ,
                        Summary ,
                        FullContent ,
                        related_news ,
                        Cates ,
                        Tags ,
                        Status ,
                        CreatedAt ,
                        CreatedBy ,
                        PublishAt,
                        meta_keywords ,
                        meta_descriptions
                    )
                    VALUES
                    (
                        '{_slug.Replace("'", "''").Trim()}' , -- Slug - varchar(250)
                        {SysBaseInfor.GetCurrentUnitId()} , -- UnitId - int
                        N'{_title.Replace("'", "''").Trim()}' , -- Title - nvarchar(200)
                        N'{_thumbnail.Replace("'", "''").Trim()}' , -- Thumbnail - nvarchar(500)
                        N'{_sapo.Replace("'", "''").Trim()}' , -- Summary - nvarchar(1000)
                        N'{_content.Replace("'", "''").Trim()}' , -- FullContent - ntext
                        N'{_related.Replace("'", "''").Trim()}' , -- related_news - nvarchar(45)
                        N'{_cates.Replace("'", "''").Trim()}' , -- Cates - nvarchar(1000)
                        N'{_tags.Replace("'", "''").Trim()}' , -- Tags - nvarchar(1000)
                        {status} , -- Status - tinyint
                        {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- CreatedAt - int
                        {(status == 1 ? CLibs.DatetimeToTimestampOrgin(DateTime.Now) : 0)} , -- PublishAt - int
                        {SysBaseInfor.GetIdNguoiDung()} , -- CreatedBy - int
                        N'{_meta_keywords.Replace("'", "''").Trim()}' , -- meta_keywords - nvarchar(50)
                        N'{_meta_description.Replace("'", "''").Trim()}'  -- meta_descriptions - nvarchar(550)
                    )  SELECT SCOPE_IDENTITY() ", _cnn);
                    int.TryParse(newid == null ? "0" : newid.ToString(), out id);
                    if (newid != null)
                    {
                        stt = true;
                    }
                    else
                    {
                        msg = "Không thêm dữ liệu vào được!";
                    }
                    #endregion
                }
                else
                {
                    #region Update bài viết
                    var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM News WHERE id <> {id} AND (slug = N'{_slug.Replace("'", "''").Trim()}' OR title = N'{_title.Replace("'", "''").Trim()}')", _cnn);
                    if (exited != null && int.Parse(exited.ToString()) > 0)
                    {
                        return(Json(new
                        {
                            status = false,
                            message = "Đã có bài viết có cùng tiêu đề hoặc url!"
                        }));
                    }
                    var eff = DBLibs.ExecuteNonQuery($@"
                    UPDATE News 
                    SET 
                        Slug = '{_slug.Replace("'", "''").Trim()}' , -- Slug - varchar(250)
                        Title = N'{_title.Replace("'", "''").Trim()}' , -- Title - nvarchar(200)
                        Thumbnail = N'{_thumbnail.Replace("'", "''").Trim()}' , -- Thumbnail - nvarchar(500)
                        Summary = N'{_sapo.Replace("'", "''").Trim()}' , -- Summary - nvarchar(1000)
                        FullContent = N'{_content.Replace("'", "''").Trim()}' , -- FullContent - ntext
                        related_news = N'{_related.Replace("'", "''").Trim()}' , -- related_news - nvarchar(45)
                        Cates = N'{_cates.Replace("'", "''").Trim()}' , -- Cates - nvarchar(1000)
                        Tags = N'{_tags.Replace("'", "''").Trim()}' , -- Tags - nvarchar(1000)
                        Status = {status} , -- Status - tinyint
                        UpdatedAt = {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- UpdatedAt - int
                        PublishAt = {(status == 1 ? CLibs.DatetimeToTimestampOrgin(DateTime.Now) : 0)} , -- PublishAt - int
                        UpdatedBy = {SysBaseInfor.GetIdNguoiDung()} , -- UpdatedBy - int
                        meta_keywords = N'{_meta_keywords.Replace("'", "''").Trim()}' , -- meta_keywords - nvarchar(50)
                        meta_descriptions = N'{_meta_description.Replace("'", "''").Trim()}'  -- meta_descriptions - nvarchar(550)
                    WHERE
                        id = {id}", _cnn);
                    if (eff > 0)
                    {
                        stt = true;
                    }
                    else
                    {
                        msg = "Không cập nhật dữ liệu được!";
                    }
                    #endregion
                }

                #region Cache lại ảnh trong bài viết
                var h = new WebLibs.HttpRequest();
                foreach (Match m in Regex.Matches(_content, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                {
                    string src = m.Groups[1].Value.Trim();
                    if (src.StartsWith("/UserData/"))
                    {
                        continue;
                    }

                    if (!src.ToLower().StartsWith(Request.Url.Host.ToLower()))
                    {
                        var path     = Server.MapPath("~") + $"UserData/{SysBaseInfor.GetIdNguoiDung()}/{id}/";
                        var fullpath = path + CLibs.GenPassCode(false, 12);
                        fullpath += (src.Contains(".jpg") || src.Contains(".jpeg") || src.Contains(".gif") || src.Contains(".png") ? src.Substring(src.LastIndexOf('.')).Trim() : ".jpg");
                        if (!System.IO.Directory.Exists(path))
                        {
                            System.IO.Directory.CreateDirectory(path);
                        }
                        h.DownloadFileFullToDisk(src.Replace("&amp;", "&"), fullpath);
                        var dest = fullpath.Replace(Server.MapPath("~"), "/");
                        _content = _content.Replace(src, dest);
                    }
                }
                foreach (Match m in Regex.Matches(_content, "<img.+?rel=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                {
                    string src = m.Groups[1].Value.Trim();
                    if (src.StartsWith("/UserData/"))
                    {
                        continue;
                    }

                    if (!src.ToLower().StartsWith(Request.Url.Host.ToLower()))
                    {
                        var path     = Server.MapPath("~") + $"UserData/{SysBaseInfor.GetIdNguoiDung()}/{id}/";
                        var fullpath = path + CLibs.GenPassCode(false, 12);
                        fullpath += (src.Contains(".jpg") || src.Contains(".jpeg") || src.Contains(".gif") || src.Contains(".png") ? src.Substring(src.LastIndexOf('.')).Trim() : ".jpg");
                        if (!System.IO.Directory.Exists(path))
                        {
                            System.IO.Directory.CreateDirectory(path);
                        }
                        h.DownloadFileFullToDisk(src.Replace("&amp;", "&"), fullpath);
                        var dest = fullpath.Replace(Server.MapPath("~"), "/");
                        _content = _content.Replace(src, dest);
                    }
                }
                foreach (Match m in Regex.Matches(_content, "<img.+?data-original=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))
                {
                    string src = m.Groups[1].Value.Trim();
                    if (src.StartsWith("/UserData/"))
                    {
                        continue;
                    }

                    if (!src.ToLower().StartsWith(Request.Url.Host.ToLower()))
                    {
                        var path     = Server.MapPath("~") + $"UserData/{SysBaseInfor.GetIdNguoiDung()}/{id}/";
                        var fullpath = path + CLibs.GenPassCode(false, 12);
                        fullpath += (src.Contains(".jpg") || src.Contains(".jpeg") || src.Contains(".gif") || src.Contains(".png") ? src.Substring(src.LastIndexOf('.')).Trim() : ".jpg");
                        if (!System.IO.Directory.Exists(path))
                        {
                            System.IO.Directory.CreateDirectory(path);
                        }
                        h.DownloadFileFullToDisk(src.Replace("&amp;", "&"), fullpath);
                        var dest = fullpath.Replace(Server.MapPath("~"), "/");
                        _content = _content.Replace(src, dest);
                    }
                }
                DBLibs.ExecuteNonQuery($"UPDATE News SET FullContent = N'{_content.Replace("'", "''").Trim()}' WHERE id = {id}", _cnn);
                #endregion

                #region Update/Insert tags
                var tags       = _tags.Split(',');
                var tags_slug  = _tags_slug.Split(',');
                var cates      = (_cates == "0" ? "" : _cates).Split(',');
                var cates_slug = (_cates_slug == "0" ? "" : _cates_slug).Split(',');
                for (int i = 0; i < tags.Length; i++)
                {
                    if (tags_slug[i].Trim(" -".ToCharArray()).ToLower() == "")
                    {
                        continue;
                    }
                    DBLibs.ExecuteNonQuery($@"
                    BEGIN TRAN
                       UPDATE Tags WITH (SERIALIZABLE) SET [used] = ([used] + 1) WHERE slug = '{tags_slug[i].Trim(" -".ToCharArray()).ToLower()}'

                       IF @@rowcount = 0
                       BEGIN
                          INSERT INTO Tags ([name], [slug], created_at) VALUES (N'{tags[i].Trim(" -".ToCharArray()).ToLower()}', '{tags_slug[i].Trim(" -".ToCharArray()).ToLower()}', {CLibs.DatetimeToTimestampOrgin(DateTime.Now)})
                       END
                    COMMIT TRAN
                    ", _cnn);
                }

                for (int i = 0; i < cates.Length; i++)
                {
                    if (cates_slug[i].Trim(" -".ToCharArray()).ToLower() == "")
                    {
                        continue;
                    }
                    DBLibs.ExecuteNonQuery($@"
                    BEGIN TRAN
                       UPDATE Tags WITH (SERIALIZABLE) SET [used] = ([used] + 1) WHERE slug = '{cates_slug[i].Trim(" -".ToCharArray()).ToLower()}'

                       IF @@rowcount = 0
                       BEGIN
                          INSERT INTO Tags ([name], [slug], created_at) VALUES (N'{cates[i].Trim(" -".ToCharArray()).ToLower()}', '{cates_slug[i].Trim(" -".ToCharArray()).ToLower()}', {CLibs.DatetimeToTimestampOrgin(DateTime.Now)})
                       END
                    COMMIT TRAN
                    ", _cnn);
                }
                #endregion
            }
            #endregion

            return(Json(new
            {
                status = stt,
                message = msg
            }));
        }
Example #24
0
        public JsonResult Save(
            int id                = 0,
            int _coquan           = 0,
            int _status           = 1,
            int _loaivb           = 0,
            int _linhvuc          = 0,
            int _tinhtrang        = 0,
            string _trichyeu      = "",
            string _summary       = "",
            string _trichyeu_slug = "",
            string _sovb          = "",
            string _kyhieu        = "",
            string _ngaybanhanh   = "")
        {
            var stt    = false;
            var msg    = "";
            var new_id = 0;

            #region Phân tích request/submit form (nếu có)
            if (_trichyeu == null || _trichyeu.Trim() == "" || _trichyeu_slug == null || _trichyeu_slug.Trim() == "")
            {
                msg = "Nội dung trích yếu cho văn bản không được để trống";
            }
            else
            {
                if (_ngaybanhanh == "")
                {
                    _ngaybanhanh = DateTime.Now.ToString("dd/MM/yyyy");
                }
                var tmp = DateTime.Now;
                if (!DateTime.TryParseExact(_ngaybanhanh, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp))
                {
                    _ngaybanhanh = DateTime.Now.ToString("dd/MM/yyyy");
                }
                if (id < 1)
                {
                    #region Thêm thông tin văn bản
                    //var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM News WHERE slug = N'{_slug.Replace("'", "''").Trim()}' OR title = N'{_title.Replace("'", "''").Trim()}'", _cnn);
                    //if (exited != null && int.Parse(exited.ToString()) > 0)
                    //{
                    //    return Json(new
                    //    {
                    //        status = false,
                    //        message = "Đã có văn bản có cùng nội dung trích yếu hoặc url!"
                    //    });
                    //}
                    var newid = DBLibs.ExecuteScalar($@"
                    INSERT INTO dbo.News
                    (
                        Slug ,
                        UnitId ,
                        Title ,
                        Summary ,
                        Cates ,
                        Type ,
                        Status ,
                        CreatedAt ,
                        CreatedBy ,
                        PublishAt ,

                        vb_coquan ,
                        vb_loaivb ,
                        vb_linhvuc ,
                        vb_tinhtrang ,
                        vb_sovb ,
                        vb_kyhieu ,
                        vb_ngaybanhanh 
                    )
                    VALUES
                    (
                        '{_trichyeu_slug.Replace("'", "''").Trim()}' , -- Slug - varchar(250)
                        {SysBaseInfor.GetCurrentUnitId()} , -- UnitId - int
                        N'{_trichyeu.Replace("'", "''").Trim()}' , -- Title - nvarchar(200)
                        N'{_summary.Replace("'", "''").Trim()}' , -- Summary - nvarchar(1000)
                        N'Văn bản' , -- Cates - nvarchar(1000)
                        1 , -- Type - tinyint
                        1 , -- Status - tinyint
                        {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- CreatedAt - int
                        {SysBaseInfor.GetIdNguoiDung()} , -- CreatedBy - int
                        {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- PublishAt - int

                        {_coquan} , -- vb_coquan - int
                        {_loaivb} , -- vb_loaivb - int
                        {_linhvuc} , -- vb_linhvuc - int
                        {_tinhtrang} , -- vb_tinhtrang - int
                        N'{_sovb.Replace("'", "''").Trim()}' , -- vb_sovb - nvarchar(200)
                        N'{_kyhieu.Replace("'", "''").Trim()}' , -- vb_kyhieu - nvarchar(200)
                        {CLibs.DatetimeToTimestampOrgin(DateTime.ParseExact(_ngaybanhanh, "dd/MM/yyyy", CultureInfo.InvariantCulture))}  -- vb_ngaybanhanh - int
                    )  SELECT SCOPE_IDENTITY() ", _cnn);
                    int.TryParse(newid == null ? "0" : newid.ToString(), out id);
                    if (newid != null)
                    {
                        stt = true; new_id = id;
                    }
                    else
                    {
                        msg = "Không thêm dữ liệu vào được!";
                    }
                    #endregion
                }
                else
                {
                    #region Update thông tin văn bản
                    //var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM News WHERE id <> {id} AND (slug = N'{_slug.Replace("'", "''").Trim()}' OR title = N'{_title.Replace("'", "''").Trim()}')", _cnn);
                    //if (exited != null && int.Parse(exited.ToString()) > 0)
                    //{
                    //    return Json(new
                    //    {
                    //        status = false,
                    //        message = "Đã có bài viết có cùng tiêu đề hoặc url!"
                    //    });
                    //}
                    var eff = DBLibs.ExecuteNonQuery($@"
                    UPDATE News 
                    SET 
                        Slug = '{_trichyeu_slug.Replace("'", "''").Trim()}' , -- Slug - varchar(250)
                        Title = N'{_trichyeu.Replace("'", "''").Trim()}' , -- Title - nvarchar(200)
                        Summary = N'{_summary.Replace("'", "''").Trim()}' , -- Summary - nvarchar(1000)
                        Status = {_status} , -- Status - tinyint
                        UpdatedAt = {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- UpdatedAt - int
                        PublishAt = {CLibs.DatetimeToTimestampOrgin(DateTime.Now)} , -- PublishAt - int
                        UpdatedBy = {SysBaseInfor.GetIdNguoiDung()} , -- UpdatedBy - int

                        vb_coquan = {_coquan} , -- vb_coquan - int
                        vb_loaivb = {_loaivb} , -- vb_loaivb - int
                        vb_linhvuc = {_linhvuc} , -- vb_linhvuc - int
                        vb_tinhtrang = {_tinhtrang} , -- vb_tinhtrang - int
                        vb_sovb = N'{_sovb.Replace("'", "''").Trim()}' , -- vb_sovb - nvarchar(200)
                        vb_kyhieu = N'{_kyhieu.Replace("'", "''").Trim()}' , -- vb_kyhieu - nvarchar(200)
                        vb_ngaybanhanh = {CLibs.DatetimeToTimestampOrgin(DateTime.ParseExact(_ngaybanhanh, "dd/MM/yyyy", CultureInfo.InvariantCulture))}  -- vb_ngaybanhanh - int
                    WHERE
                        id = {id}", _cnn);
                    if (eff > 0)
                    {
                        stt = true;
                    }
                    else
                    {
                        msg = "Không cập nhật dữ liệu được!";
                    }
                    #endregion
                }
            }
            #endregion

            return(Json(new
            {
                status = stt,
                newid = new_id,
                message = msg
            }));
        }
Example #25
0
        public string UploadImageToServer(string url, int newsId, string mediaUrl)
        {
            try
            {
                string fileExtension = Path.GetExtension(url);
                var    uri           = new Uri(url);

                if (Array.IndexOf(listDocExtension, fileExtension) > -1)
                {
                    var strDateTime      = DateTime.Now.ToString("dd-MM-yyyy");
                    var userDocumentPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, strDateTime, SysBaseInfor.GetCurrentUserId()));
                    if (!Directory.Exists(userDocumentPath))
                    {
                        Directory.CreateDirectory(userDocumentPath);
                    }
                    var fileName = Guid.NewGuid().ToString() + fileExtension;
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
                        webClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
                        webClient.DownloadFile(uri, Path.Combine(userDocumentPath, fileName));
                    }
                    var urlDocument = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, strDateTime, SysBaseInfor.GetCurrentUserId(), fileName);
                    return(mediaUrl + urlDocument);
                }
                else
                {
                    var strDateTime         = DateTime.Now.ToString("dd-MM-yyyy");
                    var userPictureNewsPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, strDateTime, SysBaseInfor.GetCurrentUserId()));
                    if (!Directory.Exists(userPictureNewsPath))
                    {
                        Directory.CreateDirectory(userPictureNewsPath);
                    }
                    var fileName = Path.Combine(userPictureNewsPath, Guid.NewGuid().ToString());

                    using (WebClient webClient = new WebClient())
                    {
                        webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
                        webClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
                        webClient.DownloadFile(uri, Path.Combine(userPictureNewsPath, fileName));
                    }

                    var fileStream = new FileStream(fileName, FileMode.Open);

                    string imageType;
                    var    isImage = fileStream.IsImage(out imageType);
                    fileStream.Close();
                    fileStream.Dispose();
                    if (isImage && !string.IsNullOrEmpty(imageType))
                    {
                        var    fName    = newsId + "_" + Guid.NewGuid() + "." + imageType;
                        var    urlImage = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, strDateTime, SysBaseInfor.GetCurrentUserId(), fName);
                        string path     = Path.Combine(userPictureNewsPath, fName);
                        System.IO.File.Move(fileName, path);
                        return(mediaUrl + urlImage);
                    }
                    System.IO.File.Delete(fileName);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Example #26
0
        public ActionResult ShowDetailUnitWorkCalendar(int workCalendarId, int?TypeSelect)
        {
            try
            {
                UnitWorkCalendarDAL WorkCalendarCtrl = new UnitWorkCalendarDAL();
                var vnFormat         = new CultureInfo("VI-vi");
                var listDayForSelect = new List <SelectListItem>();

                if (TypeSelect > 0)
                {
                    DateTime startOfWeek = DateTime.Today.AddDays(-1 * (int)(DateTime.Today.DayOfWeek) + 1);
                    DateTime endOfWeek   = startOfWeek.AddDays(5);

                    for (int tmpI = (int)DateTime.Today.DayOfWeek; tmpI < 7; tmpI++)
                    {
                        var tmpDow = DateTime.Today.AddDays(tmpI - (int)DateTime.Today.DayOfWeek);
                        listDayForSelect.Add(new SelectListItem()
                        {
                            Text = vnFormat.DateTimeFormat.GetDayName(tmpDow.DayOfWeek) + " " + tmpDow.ToString("dd/MM/yyyy"), Value = tmpDow.ToString()
                        });
                    }
                }
                else
                {
                    listDayForSelect.Add(new SelectListItem()
                    {
                        Text = vnFormat.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek) + " " + DateTime.Now.ToString("dd/MM/yyyy"), Value = DateTime.Now.ToString("MM/dd/yyyy")
                    });
                }

                ViewBag.ListDayForSelect = new SelectList(listDayForSelect, "Value", "Text");

                var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();
                ViewBag.ListGroupRoles = new SelectList(roleManager.GetListRoleByUnitIdAndType(SysBaseInfor.GetCurrentUnitCode() + SysBaseInfor.SignProject, SysBaseInfor.GetCurrentUnitId().ToInt32(), 2), "Id", "Name");

                var result = new UnitWorkCalendar();

                if (workCalendarId > 0)
                {
                    result = WorkCalendarCtrl.GetItemByID("Id", workCalendarId);
                }

                return(PartialView("~/Views/UnitWorkCalendar/_DetailUnitWorkCalendar.cshtml", result));
            }
            catch (Exception ex)
            {
                return(PartialView(blankViewUrl));
            }
        }
 public JsonResult GetListImageByDirectory(string dirSelect, int?page)
 {
     try
     {
         var lstImg = new List <GalereyaImage>();
         if (page != null && page.GetValueOrDefault() > 0)
         {
             var           currentPage = page.GetValueOrDefault();
             var           uriImage    = string.Format("/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), dirSelect);
             DirectoryInfo currentDir  = new DirectoryInfo(userPicturePath + "/" + dirSelect + "/");
             lstImg = currentDir.GetFiles().OrderBy(fi => fi.CreationTime).Skip(currentPage * pageSize).Take(pageSize).Select(fi => new GalereyaImage
             {
                 lowsrc      = Url.Content(uriImage + Path.GetFileName(fi.Name)),
                 fullsrc     = Url.Content(uriImage + Path.GetFileName(fi.Name)),
                 description = "Ngày tải: " + fi.CreationTime.ToString("dd/MM/yyyy"),
                 category    = dirSelect
             }).ToList();
         }
         return(Json(lstImg));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message));
     }
 }
        public async Task <ActionResult> DetailsUser(string userId)
        {
            if (userId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();

            var lstRoles = new List <ApplicationRole>();

            lstRoles = roleManager.GetListRoleByUnitIdAndType(SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject, SysBaseInfor.GetCurrentUnitId().ToInt32(), 2);
            var user = await userManager.FindByIdAsync(userId);

            var tmpLstUserRole = new List <string>();

            foreach (var item in user.Roles)
            {
                tmpLstUserRole.Add(item.RoleId);
            }
            ViewBag.SelectLstRoles = new MultiSelectList(lstRoles, "ID", "Name", tmpLstUserRole);
            return(PartialView(user));
        }
        public void CheckDefaultDirectory()
        {
            userPicturePath          = Server.MapPath(string.Format("~/UserImages/{0}/{1}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId()));
            userPictureNewPath       = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), SysBaseDirectory.pictureNews));
            userPictureThumbnailPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), SysBaseDirectory.pictureThumbnail));
            userPictureUploadedPath  = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), SysBaseDirectory.pictureUploaded));
            //userpictureOtherPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/", SysBaseInfor.GetCurrentUnitId(), SysBaseInfor.GetCurrentUserId(), SysBaseDirectory.pictureOther));

            if (!Directory.Exists(userPicturePath))
            {
                Directory.CreateDirectory(userPicturePath);
            }
            if (!Directory.Exists(userPictureNewPath))
            {
                Directory.CreateDirectory(userPictureNewPath);
            }
            if (!Directory.Exists(userPictureThumbnailPath))
            {
                Directory.CreateDirectory(userPictureThumbnailPath);
            }
            if (!Directory.Exists(userPictureUploadedPath))
            {
                Directory.CreateDirectory(userPictureUploadedPath);
            }
        }
        //[ProjectCustomFilter(UserPermissions.QuyenXem)]
        public ActionResult Index()
        {
            var roleManager = HttpContext.GetOwinContext().Get <ApplicationRoleManager>();
            var lstAllRoles = new List <ApplicationRole>();

            lstAllRoles = roleManager.GetListRoleByUnitIdAndType(SysBaseInfor.GetCurrentUnitCode().ToLower() + SysBaseInfor.SignProject, SysBaseInfor.GetCurrentUnitId().ToInt32(), 2);
            ViewBag.SelectLstAllRoles = new MultiSelectList(lstAllRoles, "ID", "Name");
            return(View());
        }