public ActionResult SaveUnit(string ChkActive, Units objUnit)
        {
            try
            {
                UnitsDAL objCtrl = new UnitsDAL();

                objUnit.Active = !string.IsNullOrEmpty(ChkActive);

                if (objUnit.Id > 0)
                {
                    objUnit.UpdatedAt = DateTime.Now;
                    objUnit.UpdatedBy = SysBaseInfor.GetCurrentUserId();
                    objCtrl.UpdateItem(objUnit);
                }
                else
                {
                    objUnit.CreatedAt = DateTime.Now;
                    objUnit.CreatedBy = SysBaseInfor.GetCurrentUserId();
                    objCtrl.CreateItem(objUnit);
                    string adminName = "admin@" + objUnit.Code;
                    string adminPass = "******";
                    string roleName  = "UnitsAdmin";
                    InitializeIdentity(HttpContext.GetOwinContext(), adminName, adminPass, roleName, 1, 0, objUnit.Code, objUnit.Id);
                }

                return(PartialView(urlView + "_DetailUnit.cshtml", objUnit));
            }
            catch (Exception ex)
            {
                return(PartialView(urlView + "_DetailUnit.cshtml", new Modules()));
            }
        }
 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" }));
     }
 }
Esempio n. 3
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 ActionResult GetListDirectoryLibrary()
        {
            var userLibrary = Server.MapPath(string.Format("~/UserImages/{0}/", SysBaseInfor.GetCurrentUserId()));
            var directories = Directory.GetDirectories(userLibrary);

            return(View());
        }
Esempio n. 5
0
 public JsonResult PublishWorkCalendar(int workCalendarId, int?TypeSelect)
 {
     try
     {
         UnitWorkCalendarDAL objCtrl = new UnitWorkCalendarDAL();
         UnitWorkCalendar    obj     = objCtrl.GetItemByID("Id", workCalendarId);
         if (obj.Id > 0)
         {
             obj.PublishedBy = SysBaseInfor.GetCurrentUserId();
             obj.PublishedAt = DateTime.Now;
             if (TypeSelect > 0)
             {
                 obj.Status = 0;
             }
             else
             {
                 obj.Status = 1;
             }
             objCtrl.UpdateItem(obj);
         }
         return(Json(new { Msg = "Success" }));
     }
     catch (Exception ex)
     {
         return(Json(new { Msg = "Fail" }));
     }
 }
Esempio n. 6
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 }));
     }
 }
Esempio n. 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 }));
            }
        }
        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"));
            }
        }
Esempio n. 9
0
        public ActionResult DeleteNew(int idNews)
        {
            try
            {
                NewsDAL objCtrl = new NewsDAL();
                var     result  = objCtrl.GetItemByID("Id", idNews);
                if (isChief)
                {
                    if (result.Status != 3)
                    {
                        if (result.CreatedBy == SysBaseInfor.GetCurrentUserId())
                        {
                            objCtrl.DeleteItemByValues("Id", idNews);
                            return(Content("Success"));
                        }
                        else
                        {
                            if (result.Status != 0 || result.Status != 4)
                            {
                                objCtrl.DeleteItemByValues("Id", idNews);
                                return(Content("Success"));
                            }
                        }
                    }
                }
                else
                {
                    if (result.CreatedBy == SysBaseInfor.GetCurrentUserId() && (result.Status == 0 || result.Status == 4))
                    {
                        objCtrl.DeleteItemByValues("Id", idNews);
                        return(Content("Success"));
                    }
                }

                return(Content("Không thể xóa"));
            }
            catch (Exception ex)
            {
                return(Content(ex.Message));
            }
        }
 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));
     }
 }
        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);
            }
        }
 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));
     }
 }
 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));
     }
 }
Esempio n. 14
0
 public PartialViewResult GetListFileAttachment(string inDir)
 {
     if (!string.IsNullOrEmpty(inDir))
     {
         var RootDir  = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, inDir, SysBaseInfor.GetCurrentUserId()));
         var uriImage = string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, inDir, SysBaseInfor.GetCurrentUserId());
         var files    = Directory.GetFiles(RootDir).Select(x => new FileUploadView
         {
             Url  = Url.Content(uriImage + Path.GetFileName(x)),
             Name = Path.GetFileName(x)
         });
         return(PartialView("~/Views/NewsManage/UploadPartial/_ListFileShow.cshtml", files));
     }
     return(PartialView(blankViewUrl));
 }
Esempio n. 15
0
        public ActionResult UploadDropZone()
        {
            string fName    = "";
            string urlImage = "";

            try
            {
                var userPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureThumbnail, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId()));
                if (!Directory.Exists(userPath))
                {
                    Directory.CreateDirectory(userPath);
                }
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file    = Request.Files[fileName];
                    string             imgType = "";
                    var isImages = file.InputStream.IsImage(out imgType);
                    if (isImages && !string.IsNullOrEmpty(imgType))
                    {
                        fName = Guid.NewGuid().ToString() + "." + imgType;
                        if (file != null && file.ContentLength > 0)
                        {
                            string path = Path.Combine(userPath, fName);
                            file.SaveAs(path);
                            urlImage = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureThumbnail, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId(), fName);
                            return(Json(new { urlImage = urlImage }));
                        }
                    }
                }
                return(Json("Error"));
            }
            catch (Exception ex)
            {
                return(Json("Error"));
            }
        }
Esempio n. 16
0
        public JsonResult UploadFileCkeditor(int key, HttpPostedFileWrapper upload)
        {
            try
            {
                var userPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId()));
                if (!Directory.Exists(userPath))
                {
                    Directory.CreateDirectory(userPath);
                }

                if (upload != null)
                {
                    string fileName = Guid.NewGuid().ToString() + "_" + upload.FileName;
                    if (Array.IndexOf(listDocExtension, Path.GetExtension(fileName)) > -1)
                    {
                        string path = Path.Combine(userPath, fileName);
                        upload.SaveAs(path);
                        var uriFile = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.newsAttachment, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId(), fileName);
                        return(Json(uriFile));
                    }
                    return(Json("Chỉ được tải lên file word,excel,pdf hoặc file nén zip,rar"));
                }
                ;
                return(Json("Không tìm thấy file!"));
            }
            catch (Exception ex)
            {
                return(Json("Có lỗi xảy ra!"));
            }
        }
Esempio n. 17
0
 public JsonResult UploadImageCkeditor(int key, HttpPostedFileWrapper upload)
 {
     try
     {
         var userPath = Server.MapPath(string.Format("~/UserImages/{0}/{1}/{2}/{3}/", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId()));
         if (!Directory.Exists(userPath))
         {
             Directory.CreateDirectory(userPath);
         }
         if (upload != null)
         {
             string imgType  = "";
             var    isImages = upload.InputStream.IsImage(out imgType);
             if (isImages && !string.IsNullOrEmpty(imgType))
             {
                 string ImageName = Guid.NewGuid().ToString() + "." + imgType;
                 string path      = Path.Combine(userPath, ImageName);
                 upload.SaveAs(path);
                 var uriImage = string.Format("/UserImages/{0}/{1}/{2}/{3}/{4}", SysBaseInfor.GetCurrentUnitId(), SysBaseDirectory.pictureNews, DateTime.Now.ToString("dd-MM-yyyy"), SysBaseInfor.GetCurrentUserId(), ImageName);
                 return(Json(uriImage));
             }
             return(Json("Chỉ được tải lên file hình ảnh!"));
         }
         ;
         return(Json("Không tìm thấy file!"));
     }
     catch (Exception ex)
     {
         return(Json("Có lỗi xảy ra. Xin vui lòng thử lại!"));
     }
 }
 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"));
     }
 }
Esempio n. 19
0
        public JsonResult Save(
            int id            = 0, int _status         = 0, int _show_athome = 0, int _price         = 0, int _price_src = 0, int _chapter = 0, int _page = 0, int _view_temp = 0,
            string _title     = "", string _author     = "", string _slug    = "", string _sapo      = "", string _content = "",
            string _cates     = "", string _cates_slug = "", string _tags    = "", string _tags_slug = "", string _related = "", string _meta_keywords = "", string _meta_description = "",
            int _cate_id      = 0,
            string _thumbnail = "", string _preview_urls = "", string _loai_file = "", int _type = 0, int _top_level = 0, int _order = 0, int _hot_kind = 0, int _luot_mua = 0
            )
        {
            var stt = false;
            var msg = "";

            #region Phân tích request/submit form (nếu có)
            if (_title == null || _title.Trim() == "")
            {
                msg = "Tên không được để trống";
            }
            if (_slug == null || _slug.Trim() == "")
            {
                msg = "Slug không được để trống";
            }
            else
            {
                #region Update/Insert tags
                var tags      = _tags.Trim().Split(',');
                var tags_slug = new string[tags.Length];// _tags.ToLower().Trim().Split(',');
                for (int i = 0; i < tags.Length; i++)
                {
                    tags_slug[i] = PLibs.GenerateSlug(tags[i].ToLower());
                }

                var cates = (_cates.Trim() == "0" || _cates.Trim() == "" ? "" : _cates.Trim()).Split(',');
                //var cates_slug = (_cates_slug.Trim() == "0" || _cates_slug.Trim() == "" ? "" : _cates_slug.ToLower().Trim()).Split(',');
                var cates_slug = new string[cates.Length];// _tags.ToLower().Trim().Split(',');
                for (int i = 0; i < cates.Length; i++)
                {
                    cates_slug[i] = PLibs.GenerateSlug(cates[i].ToLower());
                }

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

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

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

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

                //#region Tính toán lại cateid
                //if (_cate_id == 0 && _cates_slug.Length > 0)
                //{
                //    var sql = $@"SELECT id FROM Tags WHERE slug = '{cates_slug[0].Trim()}'";
                //    var tmp = DBLibs.ExecuteScalar(sql, _cnn);
                //    if (tmp != null)
                //        int.TryParse(tmp.ToString(), out _cate_id);
                //}
                //#endregion

                if (id < 1)
                {
                    #region Thêm tài liệu
                    var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM TaiLieu 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ó tài liệu có cùng tiêu đề hoặc url!"
                        }));
                    }
                    var sql   = $@"
                    INSERT INTO dbo.TaiLieu
                    (
	                    Slug ,			    UnitId ,			    TacGia ,			Title ,
	                    Thumbnail ,		    Summary ,				FullContent ,		Tags ,				Price ,
	                    Price_Src ,		    Price_Sale_Percent ,	[Status] ,          CreatedAt ,			UpdatedAt ,
                        CreatedBy ,			UpdatedBy ,             show_athome ,	    SoChapter ,		    SoPage ,
                        meta_keywords ,	    meta_descriptions ,     view_temp
                    ) VALUES (
                        '{_slug.Replace("'", "''")}' , -- Slug - varchar(250)
	                    {SysBaseInfor.GetCurrentUnitId()} , -- UnitId - int
	                    N'{_author.Replace("'", "''")}' , -- TacGia - nvarchar(500)
	                    N'{_title.Replace("'", "''")}' , -- Title - nvarchar(200)
	                    N'' , -- Thumbnail - nvarchar(500)
	                    N'{_sapo.Replace("'", "''")}' , -- Summary - nvarchar(1000)
	                    N'{_content.Replace("'", "''")}' , -- FullContent - ntext
	                    N'{_tags.Replace("'", "''")}' , -- Tags - nvarchar(1000)
	                    {_price} , -- Price - bigint
	                    {_price_src} , -- Price_Src - bigint
	                    {(_price == 0 ? 0 : (_price_src * 100 / _price))} , -- Price_Sale_Percent - tinyint
	                    {_status} , -- Status - tinyint
	                    GETDATE() , -- CreatedAt - datetime
	                    GETDATE() , -- UpdatedAt - datetime
	                    N'{(string.IsNullOrEmpty(SysBaseInfor.GetCurrentUserId()) ? "0" : SysBaseInfor.GetCurrentUserId())}' , -- CreatedBy - nvarchar(128)
	                    N'{(string.IsNullOrEmpty(SysBaseInfor.GetCurrentUserId()) ? "0" : SysBaseInfor.GetCurrentUserId())}' , -- UpdatedBy - nvarchar(128)
	                    {(_show_athome > 0 ? 1 : 0)} , -- show_athome - bit
	                    {_chapter} , -- SoChapter - smallint
	                    {_page} , -- SoPage - smallint
	                    N'{_meta_keywords.Replace("'", "''")}' , -- meta_keywords - nvarchar(250)
	                    N'{_meta_description.Replace("'", "''")}' , -- meta_descriptions - nvarchar(250)
	                    {_view_temp} -- view_temp - int
                    )  SELECT SCOPE_IDENTITY() ";
                    var newid = DBLibs.ExecuteScalar(sql, _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 tài liệu
                    var exited = DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM TaiLieu 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ó tài liệu có cùng tiêu đề hoặc url!"
                        }));
                    }
                    var sql = $@"
                    UPDATE TaiLieu 
                    SET 
                        Slug = '{_slug.Replace("'", "''")}' , -- Slug - varchar(250)
	                    --CategoryID = {_cate_id} , -- CategoryID - int
	                    TacGia = N'{_author.Trim().Replace("'", "''")}' , -- TacGia - nvarchar(500)
	                    Title = N'{_title.Trim().Replace("'", "''")}' , -- Title - nvarchar(200)
	                    Thumbnail = N'{_thumbnail.Trim().Replace("'", "''")}' , -- Thumbnail - nvarchar(500)
	                    Summary = N'{_sapo.Trim().Replace("'", "''")}' , -- Summary - nvarchar(1000)
	                    FullContent = N'{_content.Trim().Replace("'", "''")}' , -- FullContent - ntext
	                    Tags = N'{_tags.Trim().Replace("'", "''")}' , -- Tags - nvarchar(1000)
	                    Price = {_price} , -- Price - bigint
	                    Price_Src = {_price_src} , -- Price_Src - bigint
	                    Price_Sale_Percent = {(_price == 0 ? 0 : (_price_src * 100 / _price))} , -- Price_Sale_Percent - tinyint
	                    PreviewLinks = N'{_preview_urls.Trim().Replace("'", "''")}' , -- PreviewLinks - nvarchar(max)
	                    Type = {_type} , -- Type - tinyint
	                    Status = {_status} , -- Status - tinyint
	                    UpdatedAt = GETDATE() , -- UpdatedAt - datetime
	                    UpdatedBy = N'{(string.IsNullOrEmpty(SysBaseInfor.GetCurrentUserId()) ? "0" : SysBaseInfor.GetCurrentUserId())}' , -- UpdatedBy - nvarchar(128)
	                    show_athome = {(_show_athome > 0 ? 1 : 0)} , -- show_athome - bit
	                    TopLevel = {_top_level} , -- TopLevel - tinyint
	                    --Order = {_order} , -- Order - int
	                    HotKind = {_hot_kind} , -- HotKind - tinyint
	                    SoChapter = {_chapter} , -- SoChapter - smallint
	                    SoPage = {_page} , -- SoPage - smallint
	                    LuotMua = {_luot_mua} , -- LuotMua - int
	                    LoaiFile = '{_loai_file.Replace("'", "''")}' , -- LoaiFile - varchar(4)
	                    meta_keywords = N'{_meta_keywords.Replace("'", "''")}' , -- meta_keywords - nvarchar(250)
	                    meta_descriptions = N'{_meta_description.Replace("'", "''")}' , -- meta_descriptions - nvarchar(250)
	                    view_temp = {_view_temp} -- view_temp - int
                    WHERE
                        id = {id}";

                    var eff = DBLibs.ExecuteNonQuery(sql, _cnn);
                    if (eff > 0)
                    {
                        stt = true;
                    }
                    else
                    {
                        msg = "Không cập nhật dữ liệu được!";
                    }
                    #endregion
                }
            }
            #endregion

            return(Json(new
            {
                newid = id,
                status = stt,
                message = msg
            }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 20
0
        public ActionResult Index()
        {
            var countNews = DBLibs.ExecuteScalar($"SELECT COUNT(*) AS count FROM  dbo.News Where CreatedBy = '{SysBaseInfor.GetCurrentUserId()}' OR UpdatedBy = '{SysBaseInfor.GetCurrentUserId()}' ", _cnn);

            ViewBag.countNews = countNews;
            var sql    = $@"SELECT TOP 1000 [Id]
                 ,[Name]
                 ,[UnitId]
                 ,[RoleType]
                 ,[Discriminator]
                  FROM [dbo].[AspNetRoles]";
            var dtRole = DBLibs.GetDataBy_DataAdapter(sql, _cnn);

            ViewBag.ListRole = dtRole;
            return(View());
        }
Esempio n. 21
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);
            }
        }
Esempio n. 22
0
        public JsonResult Delete(int id)
        {
            var stt = false;
            var msg = "";

            #region Kiểm tra quyền được xóa (chỉ admin & người tạo mới xóa được)
            if (
                SysBaseInfor.GetCurrentUserName().StartsWith("admin@") ||
                int.Parse(DBLibs.ExecuteScalar($"SELECT COUNT(*) FROM TaiLieu WHERE id = {id} AND CreatedBy = '{SysBaseInfor.GetCurrentUserId()}'", _cnn).ToString()) > 0)
            {
                #region Xóa các file ảnh
                try
                {
                    var path_imgs = Server.MapPath("~") + $"UserData/{SysBaseInfor.GetIdNguoiDung()}/{id}/";
                    var di        = new DirectoryInfo(path_imgs);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo dir in di.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }
                catch { }
                #endregion

                #region Xóa các file tài liệu
                try
                {
                    var path_docs = Server.MapPath("~") + $"TaiLieu/{id}/";
                    var di        = new DirectoryInfo(path_docs);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo dir in di.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }
                catch { }
                #endregion

                var eff = DBLibs.ExecuteNonQuery($"DELETE TaiLieu WHERE id = {id}", _cnn);
                if (eff < 1)
                {
                    msg = "Lỗi không xác định, không xóa được tài liệu";
                }
                else
                {
                    stt = true;
                }
            }
            else
            {
                msg = "Không có quyền xóa tài liệu";
            }
            #endregion

            return(Json(new
            {
                status = stt,
                message = msg
            }, JsonRequestBehavior.AllowGet));
        }