예제 #1
0
        public ActionResult Add(string Title, string PicUrl)
        {
            AjaxResponse<ArticleDisPhoto> obj = new AjaxResponse<ArticleDisPhoto>();

            if (string.IsNullOrEmpty(Title))
            {
                obj.ErrorMessage = "展图名称不能为空";
                return Json(obj);
            }
            if (string.IsNullOrEmpty(PicUrl))
            {
                obj.ErrorMessage = "展图路径不能为空";
                return Json(obj);
            }
            if (Title.Length > 15)
            {
                obj.ErrorMessage = "展图名称不能超过15个字";
                return Json(obj);
            }

            ArticleDisPhoto ArticleDisPhoto = new ArticleDisPhoto { Title = Title, PicUrl = PicUrl, Status = StatusEnum.Normal };

            obj.IsSuccess = ArticleDisPhotoService.AddModel(ArticleDisPhoto);
            return Json(obj);
        }
예제 #2
0
        public ActionResult Add(string Name, int LinkType, int Sort, string WebUrl)
        {
            AjaxResponse<FriendLink> obj = new AjaxResponse<FriendLink>();

            if (string.IsNullOrEmpty(Name))
            {
                obj.ErrorMessage = "标题不能为空";
                return Json(obj);
            }

            if (Name.Length > 15)
            {
                obj.ErrorMessage = "标题不能超过15个字";
                return Json(obj);
            }

            //保证Name唯一,先查询一下是不是有这个Name
            var temp = FriendLinkService.PageLoad(a => a.LinkName == Name).FirstOrDefault();
            if (temp != null)
            {
                obj.ErrorMessage = "该标题已经存在!";
                return Json(obj);
            }

            FriendLink FriendLink = new FriendLink { LinkName = Name, LinkType = (LinkTypeEnum)LinkType, Sort = Sort, WebUrl = WebUrl, Status = StatusEnum.Normal };

            obj.IsSuccess = FriendLinkService.AddModel(FriendLink);
            return Json(obj);
        }
예제 #3
0
        public ActionResult Add(string Name, int? Pid = 0)
        {
            AjaxResponse<ArticleType> obj = new AjaxResponse<ArticleType>();

            if (string.IsNullOrEmpty(Name))
            {
                obj.ErrorMessage = "分类名称不能为空";
                return Json(obj);
            }

            if (Name.Length > 20)
            {
                obj.ErrorMessage = "分类名称不能超过20个字";
                return Json(obj);
            }

            #region 先注释掉,不同分类下其实是有子分类名字一样的
            ////保证Name唯一,先查询一下是不是有这个Name
            //var temp = ArticleTypeService.PageLoad(a => a.Name == Name).FirstOrDefault();
            //if (temp != null)
            //{
            //    obj.ErrorMessage = "该分类已经存在!";
            //    return Json(obj);
            //} 
            #endregion

            ArticleType articleType = new ArticleType { Name = Name, Pid = Pid == 0 ? null : Pid, Status = StatusEnum.Normal };

            obj.IsSuccess = ArticleTypeService.AddModel(articleType);
            return Json(obj);
        }
예제 #4
0
        public ActionResult Add(string Name)
        {
            AjaxResponse<ArticleTag> obj = new AjaxResponse<ArticleTag>();

            if (string.IsNullOrEmpty(Name))
            {
                obj.ErrorMessage = "分类名称不能为空";
                return Json(obj);
            }

            if (Name.Length > 15)
            {
                obj.ErrorMessage = "分类名称不能超过15个字";
                return Json(obj);
            }

            //保证Name唯一,先查询一下是不是有这个Name
            var temp = ArticleTagService.PageLoad(a => a.Name == Name).FirstOrDefault();
            if (temp != null)
            {
                obj.ErrorMessage = "该分类已经存在!";
                return Json(obj);
            }

            ArticleTag ArticleTag = new ArticleTag { Name = Name, Status = StatusEnum.Normal };

            obj.IsSuccess = ArticleTagService.AddModel(ArticleTag);
            return Json(obj);
        }
예제 #5
0
        public ActionResult Add(string SeoKeywords, string Sedescription)
        {
            AjaxResponse<SeoTKD> obj = new AjaxResponse<SeoTKD>();

            if (string.IsNullOrEmpty(SeoKeywords))
            {
                obj.ErrorMessage = "关键字不能为空";
                return Json(obj);
            }

            if (SeoKeywords.Length > 149)
            {
                obj.ErrorMessage = "关键字不能超过149个字";
                return Json(obj);
            }

            if (string.IsNullOrEmpty(Sedescription))
            {
                obj.ErrorMessage = "描述不能为空";
                return Json(obj);
            }

            if (Sedescription.Length > 249)
            {
                obj.ErrorMessage = "描述不能超过249个字";
                return Json(obj);
            }

            SeoTKD SeoTKD = new SeoTKD { SeoKeywords = SeoKeywords, Sedescription = Sedescription, Status = StatusEnum.Normal };

            obj.IsSuccess = SeoTKDService.AddModel(SeoTKD);
            return Json(obj);
        }
예제 #6
0
        public JsonResult EditUploadJS(int uploadId)
        {
            var ajaxResponse = new AjaxResponse { Success = false, Message = "There was a problem loading the upload." };
            ExtractViewModel model = new ExtractViewModel();

            try
            {
                var extract = ExtractViewModel.GetExtract(_unitOfWork, uploadId);

                if (extract == null)
                {
                    return (Json(ajaxResponse));
                }

                model.ExtractId = uploadId;
                model.Name = extract.Name;
                model.NameSave = extract.Name;

                ajaxResponse.Success = true;
                ajaxResponse.TheData = model;
            }
            catch (Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
            }

            return (Json(ajaxResponse));
        }
예제 #7
0
        public override void ExecuteResult(ControllerContext context)
        {
            AjaxResponse response = new AjaxResponse();

            response.Result = this.Result;

            if (!string.IsNullOrEmpty(this.ErrorMessage))
            {
                response.Success = false;
                response.ErrorMessage = this.ErrorMessage;
            }
            else
            {
                if (!string.IsNullOrEmpty(this.Script))
                {
                    response.Script = string.Concat("<string>", this.Script);
                }

                if (this.ExtraParamsResponse.Count > 0)
                {
                    response.ExtraParamsResponse = this.ExtraParamsResponse.ToJson();
                }
            }

            response.Return();
        }
예제 #8
0
        public JsonResult Add(string Title = "", string Say = "", int HitCount = 9, int Status = 0, string DisplayPic = "")
        {
            AjaxResponse<object> obj = new AjaxResponse<object>();

            #region 一系列验证
            if (!string.IsNullOrEmpty(Title))
            {
                if (Title.Length > 25)
                {
                    obj.ErrorMessage = "标题25个字以内!";
                    return Json(obj);
                }
            }

            if (string.IsNullOrEmpty(Say))
            {
                obj.ErrorMessage = "内容不能为空!";
                return Json(obj);
            }

            if (Say.Length > 500)
            {
                obj.ErrorMessage = "内容500个字以内!";
                return Json(obj);
            }
            #endregion

            //如果没有上传默认展图,就随机展示一个默认展图
            if (string.IsNullOrEmpty(DisplayPic))
            {
                IList<ArticleDisPhoto> disPics = ArticleDisPhotoService.PageLoad(p => p.Status != StatusEnum.Delete).ToList();
                int count = disPics.Count;
                if (count > 0)
                {
                    Random random = new Random();
                    int index = random.Next(disPics.Count);
                    DisplayPic = disPics[index].PicUrl;
                }
                else//实在没有的话就给一个默认值
                {
                    DisplayPic = LoT.Common.ConfigHelper.GetValueForConfigAppKey("ArticleTypeDisPlayPic");
                }
            }

            Talking talking = new Talking()
            {
                Title = string.IsNullOrEmpty(Title) ? "" : Title,
                Say = Say,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                HitCount = HitCount,
                Status = (ArticleStatusEnum)Status,
                DisplayPic = DisplayPic
            };

            obj.IsSuccess = TalkingService.AddModel(talking);

            return Json(obj);
        }
예제 #9
0
 protected override void copyThis(ref AjaxResponse destObj) {
   base.copyThis(ref destObj);
   var dst = destObj as BioResponse;
   if (dst != null) {
     dst.TransactionID = this.TransactionID;
     dst.BioParams = (this.BioParams != null) ? (Params)this.BioParams.Clone() : null;
     dst.GCfg = (this.GCfg != null) ? (GlobalCfgPack)this.GCfg.Clone() : null;
     dst.RmtStatePacket = (this.RmtStatePacket != null) ? (RemoteProcessStatePack)this.RmtStatePacket.Clone() : null;
     dst.TxtContent = this.TxtContent;
   }
 }
예제 #10
0
 /// <summary>
 /// 批量删除文章Tag
 /// </summary>
 /// <param name="ids">ID集合信息(逗号分隔)</param>
 /// <returns></returns>
 public JsonResult DeletList(string ids = "")
 {
     IList<int> idList = ids.Trim(',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => Convert.ToInt32(s)).ToList();
     int i = ArticleTagService.UpdateModel(at => idList.Contains(at.Id), at => at.Status = StatusEnum.Delete);
     AjaxResponse<ArticleTag> obj = new AjaxResponse<ArticleTag>();
     if (i > 0)
     {
         obj.IsSuccess = true;
         obj.OtherData = "成功删除" + i + "条记录";
     }
     else
     {
         obj.ErrorMessage = "操作失败!";
     }
     return Json(obj);
 }
예제 #11
0
        public JsonResult Update(string TopTitle, string BottomTitle, string BackImg, int Id = 0)
        {
            AjaxResponse<ImgFlash> obj = new AjaxResponse<ImgFlash>();

            if (string.IsNullOrEmpty(TopTitle))
            {
                obj.ErrorMessage = "上标题不能为空";
                return Json(obj);
            }

            if (TopTitle.Length > 100)
            {
                obj.ErrorMessage = "上标题不能超过100个字";
                return Json(obj);
            }

            if (string.IsNullOrEmpty(BottomTitle))
            {
                obj.ErrorMessage = "下标题不能为空";
                return Json(obj);
            }

            if (BottomTitle.Length > 100)
            {
                obj.ErrorMessage = "下标题不能超过100个字";
                return Json(obj);
            }

            if (string.IsNullOrEmpty(BackImg))
            {
                obj.ErrorMessage = "背景图为空的话会很丑的!";
                return Json(obj);
            }

            ImgFlash ImgFlash = new ImgFlash { Id = Id, TopTitle = TopTitle, BottomTitle = BottomTitle, BackImg = BackImg, Status = LoT.Enums.StatusEnum.Normal };

            if (Id > 0)
            {
                obj.IsSuccess = ImgFlashService.UpdateModel(ImgFlash);
            }
            else
            {
                obj.IsSuccess = ImgFlashService.AddModel(ImgFlash);
            }

            return Json(obj);
        }
        public AjaxResponse DoCreateThread(int categoryId, string name, string description)
        {
            var resp = new AjaxResponse
            {
                rs2 = categoryId.ToString()
            };

            List <Thread> threads;
            var           category = ForumDataProvider.GetCategoryByID(TenantProvider.CurrentTenantID, categoryId, out threads);

            if (category == null || !ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null))
            {
                resp.rs1 = "0";
                resp.rs3 = "<div>" + ForumResource.ErrorAccessDenied + "</div>";
                return(resp);
            }

            if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(name.Trim()))
            {
                resp.rs1 = "0";
                resp.rs3 = "<div>" + ForumResource.ErrorEmptyName + "</div>";
                return(resp);
            }

            var thread = new Thread()
            {
                Title       = name.Trim(),
                Description = description ?? "",
                SortOrder   = 100,
                CategoryID  = category.ID
            };

            try
            {
                thread.ID = ForumDataProvider.CreateThread(TenantProvider.CurrentTenantID, thread.CategoryID, thread.Title,
                                                           thread.Description, thread.SortOrder);
                threads.Add(thread);
                resp.rs1 = "1";
                resp.rs3 = RenderForumCategory(category, threads);
            }
            catch
            {
                resp.rs1 = "0";
                resp.rs3 = "<div>" + ForumResource.ErrorEditThreadCategory + "</div>";
            }
            return(resp);
        }
        public async Task <ActionResult> BatchOperation(string operation, params Guid?[] ids)
        {
            var ajaxResponse = new AjaxResponse();

            if (ids.Length > 0)
            {
                try
                {
                    var models = await db.Settings_SmsTemplates.Where(p => ids.Contains(p.Id)).ToListAsync();

                    if (models.Count == 0)
                    {
                        ajaxResponse.Success = false;
                        ajaxResponse.Message = "没有找到匹配的项,项已被删除或不存在!";
                        return(Json(ajaxResponse));
                    }
                    switch (operation.ToUpper())
                    {
                    case "DELETE":
                        #region  除
                    {
                        db.Settings_SmsTemplates.RemoveRange(models);
                        await db.SaveChangesAsync();

                        ajaxResponse.Success = true;
                        ajaxResponse.Message = string.Format("已成功操作{0}项!", models.Count);
                        break;
                    }

                        #endregion
                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = ex.Message;
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "请至少选择一项!";
            }
            return(Json(ajaxResponse));
        }
예제 #14
0
        public AjaxResponse DoStickyTopic(int idTopic, Guid settingsID)
        {
            _forumManager = Community.Forum.ForumManager.Settings.ForumManager;
            var resp = new AjaxResponse {
                rs2 = idTopic.ToString()
            };

            var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic);

            if (topic == null)
            {
                resp.rs1 = "0";
                resp.rs3 = ForumUCResource.ErrorAccessDenied;
                return(resp);
            }

            if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TopicSticky, topic))
            {
                resp.rs1 = "0";
                resp.rs3 = ForumUCResource.ErrorAccessDenied;
                return(resp);
            }

            topic.Sticky = !topic.Sticky;
            try
            {
                ForumDataProvider.UpdateTopic(TenantProvider.CurrentTenantID, topic.ID, topic.Title, topic.Sticky, topic.Closed);

                resp.rs1 = "1";
                if (topic.Sticky)
                {
                    resp.rs3 = ForumUCResource.SuccessfullyStickyTopicMessage;
                    resp.rs4 = ForumUCResource.ClearStickyTopicButton;
                }
                else
                {
                    resp.rs3 = ForumUCResource.SuccessfullyClearStickyTopicMessage;
                    resp.rs4 = ForumUCResource.StickyTopicButton;
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs3 = HttpUtility.HtmlEncode(e.Message);
            }
            return(resp);
        }
예제 #15
0
        public async Task <AjaxResponse> SaveSysDictTypeModel(SysDictTypeInput model)
        {
            Guid?resId;

            //验证重复
            if (CheckDictCode(model))
            {
                return(new AjaxResponse {
                    Success = false, Error = new ErrorInfo("您设置的字典类型值" + model.DictType + "重复!")
                });
                //throw new UserFriendlyException("字典类型值重复", "您设置的字典类型值" + model.DictType + "重复!");
            }

            //新增或修改
            if (model.Id == null)
            {
                SysDictType modelInput = model.MapTo <SysDictType>();
                resId = await _sysDicTypetRepository.InsertAndGetIdAsync(modelInput);
            }
            else
            {
                //获取需要更新的数据
                SysDictType data = _sysDicTypetRepository.Get((Guid)model.Id);

                //映射需要修改的数据对象
                SysDictType m = ObjectMapper.Map(model, data);
                //提交修改
                await _sysDicTypetRepository.UpdateAsync(m);

                resId = model.Id;
            }

            //保存字典编码
            if (model.SysDictInputList != null)
            {
                AjaxResponse res = await _sysDictAppService.SaveSysDictModel(model.SysDictInputList);

                if (!res.Success)
                {
                    return(res);
                }
            }
            return(new AjaxResponse {
                Success = true, Result = new { id = resId }
            });
        }
예제 #16
0
        public IActionResult Create(CategoryCreateSubmitModel submitModel)
        {
            var ajaxResponse = new AjaxResponse();

            var categoryId = _categoryService.Add(submitModel);

            if (!_categoryService.IsError)
            {
                ajaxResponse.IsSuccess = true;
                ajaxResponse.Data      = new
                {
                    CategoryId = categoryId
                };
            }

            return(Json(ajaxResponse));
        }
예제 #17
0
        private async Task <AjaxResponse> ModifyTaskEntity(TaskOptions taskOptions, JobAction action)
        {
            AjaxResponse result = new AjaxResponse();

            switch (action)
            {
            case JobAction.除:
                await _task.Delete(taskOptions.Id);

                break;

            case JobAction.修改:
                await _task.Edit(taskOptions);

                //生成任务并添加新配置
                await AddSchedulerJob(taskOptions);

                break;

            case JobAction.暂停:
            case JobAction.开启:
            case JobAction.停止:
            case JobAction.立即执行:
                TaskOptions options = await _task.GetTaskById(taskOptions.Id);

                if (action == JobAction.暂停)
                {
                    options.Status = (int)TriggerState.Paused;
                }
                else if (action == JobAction.停止)
                {
                    options.Status = (int)action;
                }
                else
                {
                    options.Status = (int)TriggerState.Normal;
                }

                await _task.Edit(options);

                break;
            }
            //生成配置文件
            _ = _log.WriteLog($"[{action}]任务:{taskOptions.GroupName}--[taskOptions.TaskName],操作对象:{JsonConvert.SerializeObject(taskOptions)}");
            return(result);
        }
예제 #18
0
        public AjaxResponse UpdateComment(string commentID, string text, string pid)
        {
            text = HtmlUtility.GetFull(text);
            var resp    = new AjaxResponse();
            var comment = _serviceHelper.GetCommentById(commentID);

            if (comment != null)
            {
                if (BookmarkingPermissionsCheck.PermissionCheckEditComment(comment))
                {
                    _serviceHelper.UpdateComment(commentID, text);
                    resp.rs1 = commentID;
                    resp.rs2 = text + CodeHighlighter.GetJavaScriptLiveHighlight(true);
                }
            }
            return(resp);
        }
예제 #19
0
        public ActionResult DoDecorate(int id)
        {
            AjaxResponse r = new AjaxResponse();

            try
            {
                if (String.IsNullOrEmpty(Request["bg"]))
                {
                    throw new ArgumentNullException("Background color is not specified");
                }
                //var p = _productRepository.GetById(id);
                //if (p == null)
                //{
                //    throw new ArgumentNullException("Product does not exist. ID: " + id);
                //}
                var pd = _productRepository.GetDetailsById(id);
                if (pd == null)
                {
                    throw new ArgumentNullException("Details does not exist for Product ID: " + id);
                }

                var decorator = new ProductDecoratorColor();
                decorator.BackgroundColor = HttpUtility.HtmlEncode(Request["bg"].Trim());
                decorator.Color           = "#000";
                decorator.Remarks         = "";
                decorator.ProductId       = pd.ProductId;
                decorator.SizeName        = pd.ParameterValue;

                pd.DataJson = Newtonsoft.Json.JsonConvert.SerializeObject(decorator);
                _productRepository.Update(pd);
                _productRepository.SubmitChanges();

                r.Status  = true;
                r.Message = "Product details are decorated";
            }
            catch (Exception ex)
            {
                r.Message = "Error decorating product";
                if (Request.IsLocal)
                {
                    r.Message = string.Concat(r.Message, Environment.NewLine, ex.ToString());
                }
            }

            return(Json(r));
        }
예제 #20
0
        /// <summary>
        /// 批量恢复默认展图
        /// </summary>
        /// <param name="ids">ID集合信息(逗号分隔)</param>
        /// <returns></returns>
        public JsonResult RecoverList(string ids = "")
        {
            IList <int> idList = ids.Trim(',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => Convert.ToInt32(s)).ToList();
            int         i      = ArticleDisPhotoService.UpdateModel(at => idList.Contains(at.Id), at => at.Status = StatusEnum.Normal);
            AjaxResponse <ArticleDisPhoto> obj = new AjaxResponse <ArticleDisPhoto>();

            if (i > 0)
            {
                obj.IsSuccess = true;
                obj.OtherData = "成功恢复" + i + "条记录";
            }
            else
            {
                obj.ErrorMessage = "操作失败!";
            }
            return(Json(obj));
        }
예제 #21
0
 void UserRegister()
 {
     if (Request.Headers["ajax"] == "true")
     {
         AjaxResponse AjaxResponse = new AjaxResponse();
         var user = new Entities.User();
         TryUpdateModel(user, new FormValueProvider(ModelBindingExecutionContext));
         user.UserPassword = Request["Password"];
         if (ModelState.IsValid && UsersLogic.Register(user))
         {
             AjaxResponse.redirectURL = "/index";
         } else {
             AjaxResponse.error = ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage;
         }
         AjaxResponse.Send();
     }
 }
예제 #22
0
        public AjaxResponse <PagedResultDto <LMovieDto> > QueryHotMovies(string keywords = "", int pageIndex = 1, int pageSize = 16)
        {
            AjaxResponse <PagedResultDto <LMovieDto> > res = new AjaxResponse <PagedResultDto <LMovieDto> >();

            try
            {
                var result = _movieService.Search(keywords, LMovieSearchOrderBy.CreationTimeDesc, pageIndex, pageSize);

                res.Result = result;
            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Error   = new ErrorInfo(ex.Message);
            }
            return(res);
        }
예제 #23
0
        public static string DeletePermissionItem(string itemID)
        {
            AjaxResponse response = new AjaxResponse();

            try
            {
                Roles.DeleteRole(itemID);
                response.IsSuccess = true;
                response.Message   = "OK";
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = (ex.Message + ex.StackTrace).EncodeJsString();
            }
            return(JsonConvert.SerializeObject(response));
        }
        public AjaxResponse SubscribeObject(Guid itemId, Guid subItemID, Guid subscriptionTypeID, string objID, bool subscribe)
        {
            var resp = new AjaxResponse {
                rs2 = itemId.ToString(), rs3 = subItemID.ToString(), rs4 = subscriptionTypeID.ToString()
            };

            try
            {
                ISubscriptionManager subscriptionManager = null;
                var item = WebItemManager.Instance[itemId];
                var productSubscriptionManager = item.Context.SubscriptionManager as IProductSubscriptionManager;

                if (productSubscriptionManager.GroupByType == GroupByType.Groups || productSubscriptionManager.GroupByType == GroupByType.Simple)
                {
                    subscriptionManager = productSubscriptionManager;
                }

                else if (productSubscriptionManager.GroupByType == GroupByType.Modules)
                {
                    subscriptionManager = WebItemManager.Instance[subItemID].Context.SubscriptionManager;
                }

                if (subscriptionManager != null)
                {
                    var types = subscriptionManager.GetSubscriptionTypes();
                    var type  = types.Find(t => t.ID.Equals(subscriptionTypeID));

                    resp.rs5 = objID;
                    if (subscribe)
                    {
                        subscriptionManager.SubscriptionProvider.Subscribe(type.NotifyAction, objID, GetCurrentRecipient());
                    }
                    else
                    {
                        subscriptionManager.SubscriptionProvider.UnSubscribe(type.NotifyAction, objID, GetCurrentRecipient());
                    }
                }
                resp.rs1 = "1";
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs6 = "<div class='errorBox'>" + HttpUtility.HtmlEncode(e.Message) + "</div>";
            }
            return(resp);
        }
        public static string DownloadAttachment()
        {
            if (!IsUmbracoAuthenticated)
            {
                return(null);
            }
            var request = FromBody <RequestAttachment>();
            var result  = LogEmail.Download(request);
            // Als je hier komt dan is er iets verkeerd gegaan
            var response = new AjaxResponse()
            {
                Message = result,
                Success = false,
            };

            return(Helper.ToJSON(response));
        }
예제 #26
0
        public ActionResult Delete(Guid?id)
        {
            var response = new AjaxResponse {
                Success = true, Message = "删除成功!"
            };
            var site_News = db.Site_News.Include(p => p.Articles).FirstOrDefault(p => p.Id == id);

            if (site_News.Articles.Any())
            {
                db.Site_NewsArticles.RemoveRange(site_News.Articles);
                db.SaveChanges();
            }
            db.Site_News.Remove(site_News);
            db.SaveChanges();
            MediaApi.DeleteForeverMedia(AccessToken, site_News.MediaId);
            return(Json(response));
        }
예제 #27
0
        public JsonResult LoadDocument(string fullName)
        {
            if (!string.IsNullOrEmpty(fullName))
            {
                var result = new ViewDocumentResponse
                {
                    pageCss = new string[] {},
                    lic     = true,
                    url     = fullName,
                    path    = fullName,
                    name    = fullName
                };


                var docInfo = _htmlHandler.GetDocumentInfo(new GroupDocs.Viewer.Domain.Options.DocumentInfoOptions(fullName));

                result.documentDescription =
                    new FileDataJsonSerializer(docInfo.Pages, new FileDataOptions()).Serialize(false);
                result.docType  = docInfo.DocumentType;
                result.fileType = docInfo.FileType;

                var htmlOptions = new HtmlOptions {
                    IsResourcesEmbedded = true
                };

                var htmlPages = _htmlHandler.GetPages(fullName, htmlOptions);
                result.pageHtml = htmlPages.Select(_ => _.HtmlContent).ToArray();

                //NOTE: Fix for incomplete cells document
                for (int i = 0; i < result.pageHtml.Length; i++)
                {
                    var html          = result.pageHtml[i];
                    var indexOfScript = html.IndexOf("script");
                    if (indexOfScript > 0)
                    {
                        result.pageHtml[i] = html.Substring(0, indexOfScript);
                    }
                }

                AjaxResponse ajaxResponse = AjaxResponse.Successful(string.Empty, result);

                return(Json(ajaxResponse));
            }
            return(null);
        }
예제 #28
0
        public AjaxResponse Preview(string text, Guid settingsID)
        {
            _settings = ForumManager.GetSettings(settingsID);
            UserInfo      currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            StringBuilder sb          = new StringBuilder();

            sb.Append("<div class=\"tintLight borderBase clearFix\" style=\"padding:10px 0px; border-top:none; border-left:none; border-right:none;\">");
            sb.Append("<table cellpadding=\"0\" cellspacing=\"0\" style='width:100%;'>");
            sb.Append("<tr valign=\"top\">");

            sb.Append("<td align=\"center\" style='width:180px; padding:0px 5px;'>");

            sb.Append("<div class=\"forum_postBoxUserSection\" style=\"overflow: hidden; width:150px;\">");
            sb.Append("<a class=\"linkHeader\"  href=\"" + CommonLinkUtility.GetUserProfile(currentUser.ID, _settings.ProductID) + "\">" + currentUser.DisplayUserName() + "</a>");

            sb.Append("<div style=\"margin:5px 0px;\" class=\"textMediumDescribe\">");
            sb.Append(HttpUtility.HtmlEncode(currentUser.Title));
            sb.Append("</div>");

            sb.Append("<a href=" + CommonLinkUtility.GetUserProfile(currentUser.ID, _settings.ProductID) + ">");
            sb.Append(_settings.ForumManager.GetHTMLImgUserAvatar(currentUser.ID));
            sb.Append("</a>");
            sb.Append("</div>");
            sb.Append("</td>");

            //post
            sb.Append("<td>");
            sb.Append("<div style='margin-bottom:5px; padding:0px 5px;'>");
            sb.Append(DateTimeService.DateTime2StringPostStyle(DateTimeService.CurrentDate()));
            sb.Append("</div>");

            var previewID = Guid.NewGuid().ToString();

            sb.Append("<div id=\"forum_message_" + previewID + "\" class=\"forum_mesBox\" style=\"width:550px;\">");
            sb.Append(text);
            sb.Append("</div>");

            sb.Append("</td></tr></table>");
            sb.Append("</div>");

            AjaxResponse resp = new AjaxResponse();

            resp.rs1 = sb.ToString();
            return(resp);
        }
예제 #29
0
        public JsonResult ShipmentCreateUpdate(Shipment shipment)
        {
            AjaxResponse returnResponse = new AjaxResponse();

            Shipment found_shipment = context.Shipments.Where(x => x.ShipmentId == shipment.ShipmentId).FirstOrDefault();

            //Createe
            if (found_shipment != null)
            {
                found_shipment.ShipmentId            = shipment.ShipmentId;
                found_shipment.ShipmentNo            = shipment.ShipmentNo;
                found_shipment.ShipmentStatus        = shipment.ShipmentStatus;
                found_shipment.ShipmentCurrentCityId = shipment.ShipmentCurrentCityId;
                found_shipment.ShippingMethod        = shipment.ShippingMethod;
                found_shipment.SenderCountryId       = shipment.SenderCountryId;
                found_shipment.SenderCityId          = shipment.SenderCityId;
                found_shipment.DestinationCountryId  = shipment.DestinationCountryId;
                found_shipment.DestinationCityId     = shipment.DestinationCityId;
                found_shipment.ShipmentRouteId       = shipment.ShipmentRouteId;
                found_shipment.ShipmentRouteIndex    = shipment.ShipmentRouteIndex;
            }
            //UPdate
            else
            {
                found_shipment = new Shipment();

                found_shipment.ShipmentId            = Guid.NewGuid();
                found_shipment.ShipmentNo            = GetRandomString(10);
                found_shipment.ShipmentStatus        = ShipmentStatus.New;
                found_shipment.ShipmentCurrentCityId = shipment.SenderCityId;
                found_shipment.ShippingMethod        = shipment.ShippingMethod;
                found_shipment.SenderCountryId       = shipment.SenderCountryId;
                found_shipment.SenderCityId          = shipment.SenderCityId;
                found_shipment.DestinationCountryId  = shipment.DestinationCountryId;
                found_shipment.DestinationCityId     = shipment.DestinationCityId;
                found_shipment.ShipmentRouteId       = shipment.ShipmentRouteId;
                found_shipment.ShipmentRouteIndex    = 0;

                context.Shipments.Add(found_shipment);
            }

            context.SaveChanges();

            return(Json(returnResponse));
        }
예제 #30
0
        public AjaxResponse GetSuggest(Guid settingsID, string text, string varName)
        {
            AjaxResponse resp = new AjaxResponse();

            string startSymbols = text;
            int    ind          = startSymbols.LastIndexOf(",");

            if (ind != -1)
            {
                startSymbols = startSymbols.Substring(ind + 1);
            }

            startSymbols = startSymbols.Trim();

            var tags = new List <Tag>();

            if (!String.IsNullOrEmpty(startSymbols))
            {
                tags = ForumDataProvider.SearchTags(TenantProvider.CurrentTenantID, startSymbols);
            }

            int    counter = 0;
            string resNames = "", resHelps = "";

            foreach (var tag in tags)
            {
                if (counter > 10)
                {
                    break;
                }

                resNames += tag.Name + "$";
                resHelps += tag.ID + "$";
                counter++;
            }

            resNames = resNames.TrimEnd('$');
            resHelps = resHelps.TrimEnd('$');
            resp.rs1 = resNames;
            resp.rs2 = resHelps;
            resp.rs3 = text;
            resp.rs4 = varName;

            return(resp);
        }
        public AjaxResponse SaveThread(int id, int categoryID, string name, string description)
        {
            var resp = new AjaxResponse
            {
                rs2 = categoryID.ToString()
            };

            if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(name.Trim()))
            {
                resp.rs1 = "0";
                resp.rs3 = "<div>" + Resources.ForumResource.ErrorEmptyName + "</div>";
                return(resp);
            }

            try
            {
                var thread = ForumDataProvider.GetThreadByID(TenantProvider.CurrentTenantID, id);

                if (thread == null || !ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null))
                {
                    resp.rs1 = "0";
                    resp.rs3 = "<div>" + Resources.ForumResource.ErrorAccessDenied + "</div>";
                    return(resp);
                }

                thread.Title       = name.Trim();
                thread.Description = description ?? "";
                thread.CategoryID  = categoryID;

                ForumDataProvider.UpdateThread(TenantProvider.CurrentTenantID, thread.ID, thread.CategoryID,
                                               thread.Title, thread.Description, thread.SortOrder);

                List <Thread> threads;
                var           category = ForumDataProvider.GetCategoryByID(TenantProvider.CurrentTenantID, thread.CategoryID, out threads);

                resp.rs1 = "1";
                resp.rs3 = RenderForumCategory(category, threads);
            }
            catch
            {
                resp.rs1 = "0";
                resp.rs3 = "<div>" + Resources.ForumResource.ErrorAccessDenied + "</div>";
            }
            return(resp);
        }
예제 #32
0
        public object SaveLanguageTimeSettings(string lng, string timeZoneID)
        {
            var resp = new AjaxResponse();

            try
            {
                SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

                var tenant  = CoreContext.TenantManager.GetCurrentTenant();
                var culture = CultureInfo.GetCultureInfo(lng);

                var changelng = false;
                if (SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, culture.Name, StringComparison.InvariantCultureIgnoreCase)) != null)
                {
                    if (!String.Equals(tenant.Language, culture.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        tenant.Language = culture.Name;
                        changelng       = true;
                    }
                }

                var oldTimeZone = tenant.TimeZone;
                tenant.TimeZone = new List <TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones()).Find(tz => String.Equals(tz.Id, timeZoneID));

                CoreContext.TenantManager.SaveTenant(tenant);

                if (!tenant.TimeZone.Id.Equals(oldTimeZone.Id) || changelng)
                {
                    AdminLog.PostAction("Settings: saved language and time zone settings with parameters language={0},time={1}", lng, timeZoneID);
                }

                if (changelng)
                {
                    return(new { Status = 1, Message = String.Empty });
                }
                else
                {
                    return(new { Status = 2, Message = Resources.Resource.SuccessfullySaveSettingsMessage });
                }
            }
            catch (Exception e)
            {
                return(new { Status = 0, Message = e.Message.HtmlEncode() });
            }
        }
        private async Task <LicenseValidationResult> ValidateLicense(
            string licenseCode)
        {
            AspNetZeroLicenseChecker zeroLicenseChecker = this;
            LicenseValidationResult  result;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("https://www.aspnetzero.com/");
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                LicenseCheckInfo licenseInfo = new LicenseCheckInfo()
                {
                    LicenseCode         = licenseCode,
                    UniqueComputerId    = zeroLicenseChecker._uniqueComputerId,
                    ComputerName        = AspNetZeroLicenseChecker.GetComputerName(),
                    ControlCode         = Guid.NewGuid().ToString(),
                    DateOfClient        = DateTime.Now,
                    ProjectAssemblyName = zeroLicenseChecker.GetAssemblyName(),
                    LicenseController   = zeroLicenseChecker.GetLicenseController()
                };
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("LicenseManagement/CheckLicense", (HttpContent) new StringContent(licenseInfo.ToJsonString(false, false), Encoding.UTF8, "application/json"));

                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    throw new AbpException("Failed on license check");
                }
                AjaxResponse <LicenseValidationResult> ajaxResponse = JsonConvert.DeserializeObject <AjaxResponse <LicenseValidationResult> >(await httpResponseMessage.Content.ReadAsStringAsync());
                if (ajaxResponse.Success && ajaxResponse.Result != null)
                {
                    if (zeroLicenseChecker.GetHashedValue(licenseInfo.ControlCode) != ajaxResponse.Result.ControlCode)
                    {
                        throw new AspNetZeroLicenseException("Failed on license check");
                    }
                    result      = ajaxResponse.Result;
                    licenseInfo = (LicenseCheckInfo)null;
                }
                else
                {
                    ErrorInfo error = ajaxResponse.Error;
                    throw new AbpException(error == null || error.Message == null ? "Failed on license check" : error.Message);
                }
            }
            return(result);
        }
예제 #34
0
        public AjaxResponse DoCloseTopic(int idTopic, Guid settingsID)
        {
            _forumManager = ForumManager.GetForumManager(settingsID);
            var resp = new AjaxResponse {
                rs2 = idTopic.ToString()
            };

            var topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic);

            if (topic == null)
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return(resp);
            }

            if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TopicClose, topic))
            {
                resp.rs1 = "0";
                resp.rs3 = Resources.ForumUCResource.ErrorAccessDenied;
                return(resp);
            }

            topic.Closed = !topic.Closed;
            try
            {
                ForumDataProvider.UpdateTopic(TenantProvider.CurrentTenantID, topic.ID, topic.Title, topic.Sticky, topic.Closed);

                resp.rs1 = "1";
                resp.rs3 = topic.Closed ? Resources.ForumUCResource.SuccessfullyCloseTopicMessage : Resources.ForumUCResource.SuccessfullyOpenTopicMessage;

                var settings = ForumManager.GetSettings(settingsID);
                if (settings != null && settings.ActivityPublisher != null)
                {
                    settings.ActivityPublisher.TopicClose(topic);
                }
            }
            catch (Exception e)
            {
                resp.rs1 = "0";
                resp.rs3 = HttpUtility.HtmlEncode(e.Message);
            }

            return(resp);
        }
예제 #35
0
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                var filePath = Path.Combine(Path.GetTempPath(), fileName);
                var store2   = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp       = new StorePermission(PermissionState.Unrestricted)
                {
                    Flags = StorePermissionFlags.AllFlags
                };
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = fileName.EndsWith(".pfx")
                                            ? new X509Certificate2(filePath, password)
                {
                    FriendlyName = fileName
                }
                                            : new X509Certificate2(new X509Certificate(filePath));

                store2.Add(cert);
                store2.Close();

                if (CoreContext.Configuration.Standalone)
                {
                    UploadStandAloneCertificate(store2, cert);
                }
                else
                {
                    UploadSaaSCertificate(store2, cert);
                }

                response.status  = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status  = "error";
                response.message = e.Message;
            }

            return(response);
        }
예제 #36
0
        private static bool handleResponseContentRequest(IRestResponse restResponse)
        {
            AjaxResponse ajaxResponse = JsonConvert.DeserializeObject <AjaxResponse>(restResponse.Content);

            if (ajaxResponse != null)
            {
                if (ajaxResponse.Success)
                {
                    try
                    {
                        string newResponseContent = handleResponseContentSuccess(ajaxResponse);
                        restResponse.Content = newResponseContent;
                        return(true);
                    }
                    catch (Exception ex) {
                        GetEventBus().Trigger <HttpResponseErrorEventData>(new HttpResponseErrorEventData
                        {
                            Message = ajaxResponse.Error.Message,
                            Details = ajaxResponse.Error.Details
                        });
                        IocManager.Resolve <ILogger>();
                        throw new HttpRequestException(restResponse, "后台请求发生错误", ex);
                    }
                }
                else
                {
                    GetEventBus().Trigger <HttpResponseErrorEventData>(new HttpResponseErrorEventData
                    {
                        Message = ajaxResponse.Error.Message,
                        Details = ajaxResponse.Error.Details
                    });

                    throw new HttpRequestException(restResponse, ajaxResponse.Error.Message);
                }
            }
            else
            {
                GetEventBus().Trigger <HttpResponseErrorEventData>(new HttpResponseErrorEventData
                {
                    Message = "None response content",
                    Details = "response content is empty"
                });
                throw new HttpRequestException(restResponse, "无内容返回");
            }
        }
예제 #37
0
        public ActionResult Edit(string email, string name, string oldPassword = "", string newPassword = "", bool Deactivated = false)
        {
            var response = new AjaxResponse {
                Success = false
            };
            var currentUser    = (User)Session["User"];
            var user           = DbHelper.GetUser(currentUser.Id);
            var newMd5Password = Md5.CalculateMd5(newPassword);
            var validation     = new Validation();

            if (user == null)
            {
                response.Message = "You have to be logged in to change user information";
                return(Json(response));
            }

            if (!validation.ValidateEmail(email))
            {
                response.Message = "You must provide a valid email";
                return(Json(response));
            }

            user.Email = string.IsNullOrEmpty(email) ? user.Email : email;
            user.Name  = string.IsNullOrEmpty(name) ? user.Name : name;

            if (!string.IsNullOrEmpty(newPassword))
            {
                if (Md5.CalculateMd5(oldPassword) == user.Password)
                {
                    user.Password = newMd5Password;
                }
                else
                {
                    response.Message = "The old password is not correct";
                    return(Json(response));
                }
            }

            DbHelper.SaveUser(user);
            response.Success = true;
            response.Message = "User updated succesfully";
            response.Data    = GetSession(refresh: true);

            return(Json(response));
        }
        public ActionResult Upload(Guid?Id, string message = null)
        {
            var ajaxMessage = new AjaxResponse {
                Success = true, Message = "上传成功!"
            };
            var resoureType = db.Site_ResourceTypes.Find(Id);

            if (resoureType == null)
            {
                ajaxMessage.Success = false;
                ajaxMessage.Message = "目录不存在或已删除!";
                return(Json(ajaxMessage));
            }
            foreach (var fileKey in Request.Files.AllKeys)
            {
                var file = Request.Files[fileKey];
                try
                {
                    var uploadFileBytes = new byte[file.ContentLength];
                    try
                    {
                        file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                    }
                    catch (Exception ex)
                    {
                        ajaxMessage.Success = false;
                        ajaxMessage.Message = "文件写入错误!";
                        Logger.Log(Magicodes.Logger.LoggerLevels.Error, ex.ToString());
                        return(Json(ajaxMessage));
                    }
                    if (file != null)
                    {
                        SiteResourceHelper.Upload(resoureType, Path.GetFileName(file.FileName), uploadFileBytes, db,
                                                  out ajaxMessage);
                    }
                }
                catch (Exception ex)
                {
                    ajaxMessage.Success = false;
                    ajaxMessage.Message = ex.Message;
                    Logger.Log(Magicodes.Logger.LoggerLevels.Error, ex.ToString());
                }
            }
            return(Json(ajaxMessage));
        }
예제 #39
0
        private AjaxResponse StopDriving(DrivingShift shift)
        {
            AjaxResponse        ar     = new AjaxResponse();
            Tuple <int, string> result = _drivingShiftAppService.StopDriving(shift);

            if (result.Item1 == -1)
            {
                ar.Success = false;
                ar.Result  = result.Item2;
            }
            else
            {
                ar.Success = true;
                ar.Result  = result.Item1;
            }

            return(ar);
        }
예제 #40
0
        private AjaxResponse InsertGeoPoint(List <GeoData> geoData)
        {
            AjaxResponse        ar     = new AjaxResponse();
            Tuple <int, string> result = _drivingShiftAppService.InsertGeoData(geoData);

            if (result.Item1 > 0)
            {
                ar.Success = true;
                ar.Result  = result.Item1;
            }
            else
            {
                ar.Success = false;
                ar.Result  = result.Item2;
            }

            return(ar);
        }
예제 #41
0
        private AjaxResponse GetVehicleHubo(int vehicleId)
        {
            AjaxResponse             ar     = new AjaxResponse();
            Tuple <int, string, int> result = _drivingShiftAppService.GetVehicleHubo(vehicleId);

            if (result.Item3 == -1)
            {
                ar.Success = false;
                ar.Result  = result.Item2;
            }
            else
            {
                ar.Success = true;
                ar.Result  = result.Item1;
            }

            return(ar);
        }
예제 #42
0
        private AjaxResponse GetDrivingShifts(int shiftId)
        {
            AjaxResponse ar = new AjaxResponse();
            Tuple <List <DrivingShiftDto>, string, int> result = _drivingShiftAppService.GetDrivingShifts(shiftId);

            if (result.Item3 == -1)
            {
                ar.Success = false;
                ar.Result  = result.Item2;
            }
            else
            {
                ar.Success = true;
                ar.Result  = result.Item1;
            }

            return(ar);
        }
예제 #43
0
        public ActionResult Edit(string email, string name, string oldPassword = "", string newPassword = "", bool Deactivated = false)
        {
            var response = new AjaxResponse();
            var currentUser = Main.Session.GetCurrentUser();
            var newMd5Password = Md5.CalculateMd5(newPassword);
            var validation = new Validation();
            var player = DbHelper.GetPlayerByEmail(email);

            if (currentUser == null)
            {
                response.Message = "You have to be logged in to change user information";
                return Json(response);
            }

            if (!validation.ValidateEmail(email))
            {
                response.Message = "You must provide a valid email";
                return Json(response);
            }

            currentUser.Email = string.IsNullOrEmpty(email) ? currentUser.Email : email;
            currentUser.Name = string.IsNullOrEmpty(name) ? currentUser.Name : name;
            player.Email = currentUser.Email;
            player.Name = currentUser.Name;

            if (!string.IsNullOrEmpty(newPassword))
            {
                if (Md5.CalculateMd5(oldPassword) == currentUser.Password)
                {
                    currentUser.Password = newMd5Password;
                }
                else
                {
                    response.Message = "The old password is not correct";
                    return Json(response);
                }
            }

            DbHelper.SaveUser(currentUser);
            DbHelper.SavePlayer(player);
            response.Message = "User updated succesfully";

            return Json(response);
        }
예제 #44
0
 void UserLogin()
 {
     if (Request.Headers["ajax"] == "true"){
         AjaxResponse AjaxResponse = new AjaxResponse();
         if (UsersLogic.Login(Request["emailtxt"], Request["passwordtxt"]))
         {
             if (!string.IsNullOrEmpty(Request["ret"]))
             {
                 AjaxResponse.redirectURL = Request["ret"];
             }
             else
             {
                 AjaxResponse.redirectURL = "/Account/Myaccount";
             }
         } else {
             AjaxResponse.error = ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage;
         }
         AjaxResponse.Send();
     }
 }
예제 #45
0
        public ActionResult Add(string Map, string AContext)
        {
            AjaxResponse<Advertisement> obj = new AjaxResponse<Advertisement>();

            if (string.IsNullOrEmpty(Map))
            {
                obj.ErrorMessage = "位置不能为空";
                return Json(obj);
            }

            if (Map.Length > 49)
            {
                obj.ErrorMessage = "位置不能超过49个字";
                return Json(obj);
            }

            if (string.IsNullOrEmpty(AContext))
            {
                obj.ErrorMessage = "描述不能为空";
                return Json(obj);
            }

            if (AContext.Length > 500)
            {
                obj.ErrorMessage = "描述不能超过500个字";
                return Json(obj);
            }

            AContext = HttpUtility.UrlDecode(AContext);
            //必须保证存在数据库里面的文字是安全的
            AContext = HttpUtility.HtmlEncode(AContext);

            Advertisement Advertisement = new Advertisement { Map = Map, AContext = AContext, Status = StatusEnum.Normal };

            obj.IsSuccess = AdvertisementService.AddModel(Advertisement);
            return Json(obj);
        }
예제 #46
0
        public JsonResult DeleteUploadJS(ExtractViewModel extract)
        {
            var ajaxResponse = new AjaxResponse { Success = false, Message = string.Format("There was a problem deleting upload, ID: {0}", extract.ExtractId) };

            if (extract.ExtractId == 0)     //shouldn't happen
            {
                return Json(ajaxResponse);
            }

            try
            {
                var existingExCount = _unitOfWork.Audits.GetAll().Where(a => a.ExtractId == extract.ExtractId).Count();

                if (existingExCount > 0)    //can't delete, its is in use
                {
                    ajaxResponse.Message = "Cannot delete an upload used in an audit";
                    return Json(ajaxResponse);
                }

                int result = ExtractViewModel.DeleteExtract(_unitOfWork, (int)extract.ExtractId);

                if (result < 1)
                {
                    return Json(ajaxResponse);
                }

                ajaxResponse.Message = "Success";
                ajaxResponse.Success = true;
            }
            catch (Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
            }

            return Json(ajaxResponse);
        }
예제 #47
0
        public JsonResult SaveUploadJS(ExtractViewModel extract)
        {
            var ajaxResponse = new AjaxResponse { Success = false, Message = "An error occurred while saving the upload." };

            //should have already been caught by client, but check again
            if (!ModelState.IsValid)
            {
                ajaxResponse.Message = "Please complete all required form fields.";
                return Json(ajaxResponse);
            }

            try
            {
                extract.TheUnitOfWork = _unitOfWork;

                if (!extract.IsUniqueYN())   //Uniqueness of extract
                {
                    ajaxResponse.Message = "The upload name already exists.";
                    return Json(ajaxResponse);
                }

                int id = extract.UpdateAndSave();

                ajaxResponse.Message = "Success";
                ajaxResponse.Success = true;
            }
            catch (Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
            }

            return Json(ajaxResponse);
        }
예제 #48
0
 private static void _processResponseError(Exception e, AjaxRequest request) {
   var response = new AjaxResponse {
     Ex = EBioException.CreateIfNotEBio(e),
     Success = false
   };
   if (request.Callback != null)
     request.Callback(null, new AjaxResponseEventArgs { Request = request, Response = response });
 }
예제 #49
0
    public static void GetFileFromSrv(AjaxRequest request, String appendUrlParams) {
      Action<Exception> doOnErr = e => {
        var response = new AjaxResponse {
          Ex = EBioException.CreateIfNotEBio(e),
          Success = false
        };
        if (request.Callback != null)
          request.Callback(null, new AjaxResponseEventArgs { Request = request, Response = response });
      };
      try {
        var cli = new WebClient();
        cli.OpenReadCompleted += (sender, e) => {
          if (e.Error == null) {
            if (request.Callback != null) {
              var response = new AjaxResponse {
                Success = true
              };
              var a = new AjaxResponseEventArgs {
                Request = request,
                Response = response, 
                Stream = new MemoryStream()
              };
              e.Result.CopyTo(a.Stream);
              e.Result.Close();
              request.Callback(sender, a);
            }


          } else {
            doOnErr(e.Error);
          }
        };
        var paramsToPost = PrepareRequestParams(request);
        var urlParams = String.IsNullOrEmpty(appendUrlParams) ? String.Empty : "&" + appendUrlParams;
        var uri = new Uri(request.URL + "?" + paramsToPost + urlParams, UriKind.Relative);
        cli.OpenReadAsync(uri);
      } catch (Exception ex) {
        doOnErr(ex);
      }
    }
예제 #50
0
 /// <summary>
 /// Строит строку запроса URL
 /// </summary>
 /// <param name="requestException"></param>
 /// <param name="responseText"></param>
 /// <param name="converters"></param>
 /// <returns></returns>
 public static AjaxResponse CreResponseObject(EBioException requestException, String responseText, JsonConverter[] converters) {
   AjaxResponse response;
   if (requestException == null) {
     try {
       response = AjaxResponse.Decode(responseText, converters);
       response.ResponseText = responseText;
     } catch (Exception e) {
       response = new AjaxResponse {
         Ex = new EBioException("Ошибка при восстановлении объекта Response. Сообщение: " + e.Message + "\nResponseText: " + responseText, e),
         ResponseText = responseText,
         Success = false
       };
     }
   } else {
     response = new AjaxResponse {
       Ex = requestException,
       ResponseText = responseText,
       //request = pRequest,
       Success = false
     };
   }
   return response;
 }
예제 #51
0
        /// <summary>
        /// 文章Tag查询
        /// </summary>
        /// <param name="page">当前页(1开始)</param>
        /// <param name="rows">显示条数</param>
        /// <param name="Name">分类名称(最多15个字)</param>
        /// <param name="Pid">所属分类</param>
        /// <returns></returns>
        public JsonResult Query(int page = 1, int rows = 20, string Name = "", int Status = -1)
        {
            int total = 0;
            Expression<Func<ArticleTag, bool>> whereLambada = at => (string.IsNullOrEmpty(Name) || at.Name.Contains(Name)) && (Status == -1 || at.Status == (Status == 99 ? StatusEnum.Delete : StatusEnum.Normal));

            IQueryable<ArticleTag> articleList = ArticleTagService.PageLoad(whereLambada, a => new { a.Id }, false, page, rows, out total);

            var obj = new AjaxResponse<ListData<ArticleTag>>();
            obj.IsSuccess = true;
            obj.Data = new ListData<ArticleTag>();
            obj.Data.rows = articleList;
            obj.Data.total = total;
            return Json(obj);
        }
예제 #52
0
        /// <summary>
        /// 文章类型查询
        /// </summary>
        /// <param name="page">当前页(1开始)</param>
        /// <param name="rows">显示条数</param>
        /// <param name="Name">分类名称(最多15个字)</param>
        /// <param name="Pid">所属分类</param>
        /// <returns></returns>
        public JsonResult Query(int page = 1, int rows = 20, string Name = "", int Pid = 0)
        {
            int total = 0;
            Expression<Func<ArticleType, bool>> whereLambada = at => (string.IsNullOrEmpty(Name) || at.Name.Contains(Name)) && (Pid == 0 || Pid == null || at.Pid == Pid);

            IQueryable<ArticleType> articleList = ArticleTypeService.PageLoad(whereLambada, a => new { a.Id }, false, page, rows, out total);

            var obj = new AjaxResponse<ListData<ArticleType>>();
            obj.IsSuccess = true;
            obj.Data = new ListData<ArticleType>();
            obj.Data.rows = articleList;
            obj.Data.total = total;
            return Json(obj);
        }
예제 #53
0
        public JsonResult Update(string Name, int? Pid, int Status, int Id = 0)
        {
            AjaxResponse<ArticleType> obj = new AjaxResponse<ArticleType>();

            if (string.IsNullOrEmpty(Name))
            {
                obj.ErrorMessage = "分类名称不能为空";
                return Json(obj);
            }

            if (Name.Length > 20)
            {
                obj.ErrorMessage = "分类名称不能超过20个字";
                return Json(obj);
            }

            if (Id == Pid)
            {
                obj.ErrorMessage = "分类并没有变化";
                return Json(obj);
            }

            #region 注释
            //查询过这个实体,你再这样放一个new的实体进去跟踪.他会有2个相同ID的对象,然后就报异常了
            //最简单的方法,你已经查了,那么用你查出来的实体来存储更新后的数据,这样id一致而且还省下资源
            ArticleType articleType = ArticleTypeService.FindModel(Id);
            if (articleType == null)
            {
                obj.ErrorMessage = "请不要猥琐!该分类不存在";
                return Json(obj);
            }
            #endregion

            articleType.Id = Id;
            articleType.Name = Name;
            articleType.Pid = Pid == 0 ? null : Pid;
            articleType.Status = Status != 99 ? StatusEnum.Normal : StatusEnum.Delete;

            obj.IsSuccess = ArticleTypeService.UpdateModel(articleType);
            return Json(obj);
        }
예제 #54
0
        public JsonResult GetUploadNameJS(int uploadId)
        {
            var ajaxResponse = new AjaxResponse { Success = false, Message = "An error occurred while getting the upload name." };

            try
            {
                string uploadName;

                var upload = ExtractViewModel.GetExtract(_unitOfWork, uploadId);

                if (upload != null)
                {
                    uploadName = upload.Name;
                }
                else
                {
                    uploadName = "unknown";
                }

                ajaxResponse.Success = true;
                ajaxResponse.TheData = uploadName;
            }
            catch(Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
            }

            return (Json(ajaxResponse));
        }
예제 #55
0
        public JsonResult SaveAndUploadDataJS()
        {
            var ajaxResponse = new AjaxResponse { Success = false, Message = "An error occurred while saving the upload." };

            //added additional try/catches for debugging a problem

            try
            {
                //should have already been caught by client, but check again
                if (!ModelState.IsValid)
                {
                    ajaxResponse.Message = "Please complete all required form fields.";
                    return Json(ajaxResponse);
                }
            }
            catch(Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
                ajaxResponse.Message = "There was a problem validating your input, please try again.";
                return Json(ajaxResponse);
            }

            //validation
            HttpPostedFileBase hpf;
            try
            {
                if (Request.Files.Count != 1)
                {
                    ajaxResponse.Message = "More than one upload file was specified.";
                    return Json(ajaxResponse);
                }

                hpf = Request.Files[0] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                {
                    ajaxResponse.Message = "The specified upload file is empty.";
                    return Json(ajaxResponse);
                }

                int maxFileBytes = Properties.Settings.Default.MaxUploadSize;
                if (hpf.ContentLength > maxFileBytes)
                {
                    ajaxResponse.Message = string.Format("The upload file should not exceed {0} bytes.", maxFileBytes);
                    return Json(ajaxResponse);
                }

                if (!Request.Files[0].FileName.ToLower().EndsWith(".csv"))
                {
                    ajaxResponse.Message = "The upload file must be a CSV file.";
                    return Json(ajaxResponse);
                }
            }
            catch(Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
                ajaxResponse.Message = "There was a problem validating the specified file.";
                return Json(ajaxResponse);
            }

            //int extractId = Convert.ToInt32(Request.Form["extractIdJS"]);
            string extractName;
            string internalUserId;
            ExtractViewModel extract;
            ajaxResponse.Success = false;

            try
            {
                extractName = Request.Form["extractNameJS"];
                internalUserId = Utility.GetAspNetUserName(this);
                extract = ExtractViewModel.NewExtract(_unitOfWork, extractName, internalUserId);

                if (!extract.IsUniqueYN())   //Uniqueness of extract
                {
                    ajaxResponse.Message = "The upload name already exists.";
                    return Json(ajaxResponse);
                }
            }
            catch(Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
                ajaxResponse.Message = "There was a problem uniqueness of upload file.";
                return Json(ajaxResponse);
            }

            try
            {
                extract.ExtractId = extract.AddAndSave();

                if (extract.ExtractId == 0)
                {
                    return Json(ajaxResponse);
                }

                ajaxResponse.Id = extract.ExtractId;
            }
            catch (Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
                ajaxResponse.Message = "There was a problem saving the main upload record.";
                return Json(ajaxResponse);
            }

            //proceed with upload
            try
            {
                extract.UploadExtract(hpf.InputStream);

                ajaxResponse.Message = "Success";
                ajaxResponse.Success = true;
            }
            catch(Exception ex)
            {
                ErrorTools.HandleError(ex, ErrorLevel.NonFatal);    //just log, no redirect
                ajaxResponse.Message = "An error occurred while uploading the data.";
            }

            return Json(ajaxResponse);
        }
예제 #56
0
        /// <summary>
        /// Advertisement查询
        /// </summary>
        /// <param name="page">当前页(1开始)</param>
        /// <param name="rows">显示条数</param>
        /// <returns></returns>
        public JsonResult Query(int page = 1, int rows = 20)
        {
            int total = 0;

            IQueryable<Advertisement> advertisementList = AdvertisementService.PageLoad(a => true, a => new { a.Id }, false, page, rows, out total);

            var obj = new AjaxResponse<ListData<Advertisement>>();
            obj.IsSuccess = true;
            obj.Data = new ListData<Advertisement>();
            obj.Data.rows = advertisementList;
            obj.Data.total = total;
            return Json(obj);
        }
예제 #57
0
 void UserLogin()
 {
     if (Request.Headers["ajax"] == "true")
     {
         AjaxResponse AjaxResponse = new AjaxResponse();
         if (UsersLogic.Login(Request["emailtxt"], Request["passwordtxt"]))
         {
             AjaxResponse.redirectURL = "/checkout";
         }
         else
         {
             AjaxResponse.error = ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage;
         }
         AjaxResponse.Send();
     }
 }
예제 #58
0
        public JsonResult Update(string Name, int Status, int Id = 0)
        {
            AjaxResponse<ArticleTag> obj = new AjaxResponse<ArticleTag>();

            if (string.IsNullOrEmpty(Name))
            {
                obj.ErrorMessage = "分类名称不能为空";
                return Json(obj);
            }

            if (Name.Length > 15)
            {
                obj.ErrorMessage = "分类名称不能超过15个字";
                return Json(obj);
            }

            ArticleTag ArticleTag = new ArticleTag { Id = Id, Name = Name, Status = Status != 99 ? StatusEnum.Normal : StatusEnum.Delete };

            obj.IsSuccess = ArticleTagService.UpdateModel(ArticleTag);

            return Json(obj);
        }
예제 #59
0
        public JsonResult Update(string SeoKeywords, string Sedescription, int Status, int Id = 0)
        {
            AjaxResponse<SeoTKD> obj = new AjaxResponse<SeoTKD>();

            if (string.IsNullOrEmpty(SeoKeywords))
            {
                obj.ErrorMessage = "关键字不能为空";
                return Json(obj);
            }

            if (SeoKeywords.Length > 149)
            {
                obj.ErrorMessage = "关键字不能超过149个字";
                return Json(obj);
            }

            if (string.IsNullOrEmpty(Sedescription))
            {
                obj.ErrorMessage = "描述不能为空";
                return Json(obj);
            }

            if (Sedescription.Length > 249)
            {
                obj.ErrorMessage = "描述不能超过249个字";
                return Json(obj);
            }

            SeoTKD SeoTKD = new SeoTKD { Id = Id, SeoKeywords = SeoKeywords, Sedescription = Sedescription, Status = Status != 99 ? StatusEnum.Normal : StatusEnum.Delete };

            obj.IsSuccess = SeoTKDService.UpdateModel(SeoTKD);

            return Json(obj);
        }
예제 #60
0
        public JsonResult GetChildType(int Pid = 0)
        {
            var obj = new AjaxResponse<IQueryable<Temp>>();

            if (Pid == 0)//没有获取到数据
            {
                obj.ErrorMessage = "请选择父分类";
                return Json(obj);
            }

            obj.IsSuccess = true;
            obj.Data = ArticleTypeService.PageLoad(at => at.Pid == Pid && at.Status != StatusEnum.Delete).Select(at => new Temp { Id = at.Id, Name = at.Name });
            return Json(obj);
        }