public ActionResult GetArticleById(string articleID) { try { if (!FeatureListModel.Instance.CheckFeatureForEnabled(Features.GetAtricleById)) throw new Exception("Просмотр статей отключен"); var maybeId = articleID.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); int currentId; int.TryParse(maybeId, out currentId); var helper = new IocHelper(); CommonHelper.Instance.CurrentArticle = helper.ArticleService.GetArticleById(currentId); var dto = new ArticleDto(CommonHelper.Instance.CurrentArticle); var groups = helper.GroupService.GetAllGroups(c => c.GroupName, 0, 999).ToList(); if (IocHelper.CurrentToggle == "xml") { dto.Group = groups.FirstOrDefault(c => c.Groups.FirstOrDefault(x => x == dto.ArticleName) != null) .MaybeAs<ArticleGroup>() .Bind(c => c.GroupName) .GetOrDefault(null); } return Json(dto, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public FileResult ExprortFromDb() { try { if (IocHelper.CurrentToggle != "db") { throw new Exception("Экспорт возможен только из БД"); } var helper = new IocHelper(); using (var memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var demoFile = archive.CreateEntry("db_export.xml", CompressionLevel.Optimal); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(helper.ArticleService.ExportFromDb()); } } memoryStream.Seek(0, SeekOrigin.Begin); return File(memoryStream.ToArray(), "application/zip", "db_export.zip"); } } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult GetGroups() { try { var helper = new IocHelper(); var res = helper.ArticleService.GetAllArticles(c => c.ArticleName); var groups = helper.GroupService.GetAllGroups(c => c.GroupId); var lst = new List<ForGroupPanel>(); if (IocHelper.CurrentToggle == "xml") { var groupView = GroupHelper.Instance.GetXmlGroups(groups, res ?? new List<Article>()); lst = groupView.GroupViewItems.Select(c => new ForGroupPanel(c)).ToList(); } else { var groupView = GroupHelper.Instance.GetDbGroups(groups); lst = groupView.GroupViewItems.Select(c => new ForGroupPanel(c)).OrderBy(c=>c.Name).ToList(); } return Json(lst, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
private ArticleGroup GetGroup(string group) { var helper = new IocHelper(); return @group != null ? helper.GroupService.GetGroupsByParams(c => c.GroupName == @group, c => c.GroupId, 0, 1).FirstOrDefault() : helper.GroupService.GetGroupsByParams(c => c.GroupName == "Без группы", c => c.GroupId, 0, 1).FirstOrDefault(); }
public void ConnectToGroup(string groupName) { if (HttpContext.Current.Cache[groupName] != null) { var res = HttpContext.Current.Cache[groupName] as List<dynamic>; if (res == null) { var comments = HttpContext.Current.Cache[groupName] as List<Comment>; if (comments != null) { res = comments .Select(comment => new { message = comment.CommentText, id = comment.CommentId.ToString(), name = comment.UserName, date = comment.AddedDate.ToString("F", CultureInfo.CreateSpecificCulture("en-US")) }) .Cast<dynamic>().ToList(); } } Clients.Caller.connectToGroup(res); } else { var helper = new IocHelper(); var comments = helper.CommentService.GetByGroup(groupName); var lst = comments .Select(comment => new { message = comment.CommentText, id = comment.CommentId.ToString(), name = comment.UserName, date = comment.AddedDate.ToString("F", CultureInfo.CreateSpecificCulture("en-US")) }) .Cast<dynamic>().ToList(); HttpContext.Current.Cache.Add(groupName, lst, null, DateTime.MaxValue, new TimeSpan(0, 0, 0, 30), CacheItemPriority.Default, (key, value, reason) => CacheCallBack(key)); Clients.Caller.connectToGroup(lst); } }
private ArticleGroup GetGroup(string group) { var helper = new IocHelper(); return(@group != null ? helper.GroupService.GetGroupsByParams(c => c.GroupName == @group, c => c.GroupId, 0, 1).FirstOrDefault() : helper.GroupService.GetGroupsByParams(c => c.GroupName == "Без группы", c => c.GroupId, 0, 1).FirstOrDefault()); }
public ActionResult UpdatePlan(Plan plan) { try { var helper = new IocHelper(); helper.PlanService.UpdatePlan(plan); return Json(plan, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ArticleGroup InitGroup(ArticleGroup group, IEnumerable<Article> articles) { bool flag = false; if (articles == null || !articles.Any()) { var helper = new IocHelper(); articles = helper.ArticleService.GetArticlesByParams(c => group.Groups.Contains(c.ArticleName), c => c.ArticleId); flag = true; } @group.Articles = flag ? articles.ToList() : articles.Where(c => @group.Groups.Contains(c.ArticleName)).ToList(); return @group; }
public ActionResult Registration(RegistrationModel model) { var errorList = new List<string>(); if (model.Password != model.ConfirmPassword) { errorList.Add("Пароли не совпадают"); } var helper = new IocHelper(); var existingUser = helper.UserService.GetUserByParams(model.FirstName, model.LastName, model.Email, model.Login); if (existingUser.Any()) { errorList.Add("Пользователь с похожими данными уже существует"); } if (errorList.Count > 0) { CommonHelper.Instance.TempFiles = null; foreach (var item in errorList) { ModelState.AddModelError("", item); } return View(model); } var user = new User { Credential = new Credential { Login = model.Login, Password = model.Password }, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Avatar = CommonHelper.Instance.TempFiles.Count > 0 ? CommonHelper.Instance.TempFiles.First().ImageData : null }; CommonHelper.Instance.TempFiles = null; if (!ModelState.IsValid) { CommonHelper.Instance.TempFiles = null; return View(model); } else { helper.UserService.AddUser(user); } return View("Login", user); }
public ArticleGroup InitGroup(ArticleGroup group, IEnumerable <Article> articles) { bool flag = false; if (articles == null || !articles.Any()) { var helper = new IocHelper(); articles = helper.ArticleService.GetArticlesByParams(c => group.Groups.Contains(c.ArticleName), c => c.ArticleId); flag = true; } @group.Articles = flag ? articles.ToList() : articles.Where(c => @group.Groups.Contains(c.ArticleName)).ToList(); return(@group); }
public void InitGroups(ArticleDto article) { if (IocHelper.CurrentToggle == "xml") { var @group = GetGroup(article.Group); if (@group.Groups == null) { @group.Groups = new List <string>(); } @group.Groups.Add(article.ArticleName); var helper = new IocHelper(); helper.GroupService.UpdateGroup(@group); } }
public void InitGroups(ArticleDto article) { if (IocHelper.CurrentToggle == "xml") { var @group = GetGroup(article.Group); if (@group.Groups == null) { @group.Groups = new List<string>(); } @group.Groups.Add(article.ArticleName); var helper = new IocHelper(); helper.GroupService.UpdateGroup(@group); } }
public ActionResult DeletePlan(int id) { try { var plan = new Plan{PlanId = id}; var helper = new IocHelper(); helper.PlanService.DeletePlan(plan); return Json(true, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult SavePlan(Plan plan) { try { plan.AddedDate = DateTime.Now; plan.IsDone = false; var helper = new IocHelper(); helper.PlanService.SavePlan(plan); return Json(plan, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public string GetInfo() { double size = 0; if (Directory.Exists(IocHelper.GetCurrentDirectory() + BaseXml.FOLDER)) { var infos = new DirectoryInfo(IocHelper.GetCurrentDirectory() + BaseXml.FOLDER); size = infos.EnumerateFiles() .Where(info => info.Extension == ".xml") .Aggregate <FileInfo, double>(0, (current, info) => (current + info.Length / (1024.0 * 1024.0))); } var articleDb = new ArticleDBRepository(); var dbSize = articleDb.GetSize(); var result = string.Format("Размеры данных:<br>XML: {0:0.00} MB, DB:{1}", size, dbSize); return(result); }
public ActionResult GetAllPlans(string skip,string take,string order) { try { int pSkip, pTake; int.TryParse(skip, out pSkip); int.TryParse(take, out pTake); pTake = pTake > 0 ? pTake : 999; var helper = new IocHelper(); var res = helper.PlanService.GetAllPlans(c => c.PlanName, pSkip, pTake); var totalCount = helper.PlanService.TotalCount; var plan = new {Plans = res, TotalCount = totalCount}; return Json(plan, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult DeleteArticelById(string id) { try { int ids; int.TryParse(id, out ids); var article = new Article { ArticleId = ids }; var helper = new IocHelper(); var current = article.Clone(); helper.ArticleService.DeleteArticle(article); return Json(current); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public async Task<FileContentResult> GetImageByArticleIdAndImageId(string articleID, string imageID, string size = null) { int articleIdCurrent, imageIdCurrent; var maybeArticleId = articleID.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); var maybeImageId = imageID.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); var maybeSize = size.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); int.TryParse(maybeArticleId, out articleIdCurrent); int.TryParse(maybeImageId, out imageIdCurrent); var helper = new IocHelper(); if (CommonHelper.Instance.CurrentArticle.ArticleId != articleIdCurrent) { CommonHelper.Instance.CurrentArticle = helper.ArticleService.GetArticleById(articleIdCurrent); } var images = CommonHelper.Instance.CurrentArticle.Images.Select(x => new ImageResult { ImageData = x.Data, Id = x.ImageId }); var result = images.FirstOrDefault(c => c.Id == imageIdCurrent); var reworkedImage = CommonHelper.Instance.DefineSizeOfImage(maybeSize, result); return await Task.Factory.StartNew(() => File(reworkedImage.MaybeAs<ImageResult>().Bind(c => c.ImageData).GetOrDefault(null), "image/gif")); }
public IDto GetEntity(string type, string id) { var maybeType = type.MaybeAs <string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); var maybeId = id.MaybeAs <string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); int currentId; int.TryParse(maybeId, out currentId); var helper = new IocHelper(); switch (maybeType) { default: case "article": var article = helper.ArticleService.GetArticleById(currentId); if (article == null) { throw new Exception("Статьи с данным идентификатором не сущесвует"); } return(new ArticleDto(article)); //case "image": // return IocHelper.; case "plan": var plan = helper.PlanService.GetPlanById(currentId); if (plan == null) { throw new Exception("Плана с данным идентификатором не сущесвует"); } return(new PlanDto(plan)); case "group": var group = helper.GroupService.GetGroupById(currentId); if (group == null) { throw new Exception("Группы с данным идентификатором не сущесвует"); } return(new GroupDtoView(group)); } }
public ActionResult GetPanel() { try { var helper = new IocHelper(); var res = helper.ArticleService.GetAllArticles(c => c.ArticleName); var list = new List<ForPanel>(); if (res != null) { list = res.Select(article => new ForPanel { Id = article.ArticleId, Name = article.ArticleName, Rate = article.Rate }).OrderBy(c => c.Name).ToList(); } return Json(list, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult GetFullStat() { try { var helper = new IocHelper(); if (listTranViewsModels.Count == 0) { listTranViewsModels = helper.ArticleService.GetAllArticles(c => c.ArticleId).Select(c => new StatViewModel { Name = c.ArticleName, LetterCount = helper.ArticleHelperService.GetCountOfLetters(c) }).ToList(); } var totalEntityes = (double)helper.TransactionService.TotalCount; var counts = helper.TransactionService.GetTrancCount(); var readable = (counts.Item1 / totalEntityes) * 100; var updatable = (counts.Item3 / totalEntityes) * 100; var writable = (counts.Item2 / totalEntityes) * 100; var wrapper = new StatViewModelWrapper { TranViewModels = listTranViewsModels, TotalCount = listTranViewsModels.Sum(c => c.LetterCount), ReadablePercent = readable, UpdatablePercent = updatable, WritablePercent = writable, }; return Json(wrapper, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult GetStat(int? articleId) { try { var maybeId = articleId.MaybeAs<int>().Bind(c => c).GetOrDefault(-1); var helper = new IocHelper(); var res = helper.ArticleService.GetArticleById(maybeId); if (res != null) { var countOfLetters = helper.ArticleHelperService.GetCountOfLetters(res); var countOfWords = helper.ArticleHelperService.GetCountOfWords(res); var countOfSentenses = helper.ArticleHelperService.GetCountOfSentences(res); var result = new { CountOfLetters = countOfLetters, CountOfWords = countOfWords, countOfSentenses = countOfSentenses, ArticleName = res.ArticleName }; return Json(result, JsonRequestBehavior.AllowGet); } throw new Exception("Статьи с данным идентификатором не существует"); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult SaveNewGroup(string group) { try { var helper = new IocHelper(); var res = IocHelper.CurrentToggle == "xml" ? helper.GroupService.GetGroupsByParams(c => c.GroupName == group, c => c.GroupId, 0, 1).FirstOrDefault() : helper.GroupService.GetAllGroups(c => c.GroupId).FirstOrDefault(c => c.GroupName == group); if (res != null) { throw new Exception(string.Format("Группа \"{0}\" уже существует", group)); } var groupArticle = new ArticleGroup { GroupName = group, Groups = new List<string>() }; helper.GroupService.SaveGroup(groupArticle); return Json(true); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public void Send(dynamic message, string groupName) { // Call the broadcastMessage method to update clients. message.date = DateTime.Now.ToString("F", CultureInfo.CreateSpecificCulture("en-US")); message.id = Guid.NewGuid().ToString(); Clients.Group(groupName).sendMessage(message); if (HttpContext.Current.Cache[groupName] == null) { var now = DateTime.Now; var lst = new List<dynamic>(); lst.Add(message); HttpContext.Current.Cache.Add(groupName, lst, null, DateTime.MaxValue, new TimeSpan(0, 0, 0, 30), CacheItemPriority.Default, (key, value, reason) => CacheCallBack(key)); } else { var currentComment = new Comment { CommentId = Guid.Parse((string)message.id), GroupName = groupName, CommentText = message.message, UserName = message.name, AddedDate = DateTime.ParseExact((string)message.date, "F", CultureInfo.CreateSpecificCulture("en-US")) }; var helper = new IocHelper(); helper.CommentService.Save(currentComment); (HttpContext.Current.Cache[groupName] as List<dynamic>).Add(message); } }
public ActionResult ToggleSource(string source) { try { var helper = new IocHelper(); if (source == "db") { helper.ToggleToDb(true); } else { helper.ToggleToXml(true); } return Json(IocHelper.CurrentToggle); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult UpdateArticle(ArticleDto dto) { try { var article = dto.Convert(); GroupHelper.Instance.InitGroups(dto); var helper = new IocHelper(); helper.ArticleService.UpdateArticle(article); return Json(true); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult UpdateuserData(User user) { try { var helper = new IocHelper(); var current = CommonHelper.Instance.CurrentUser; helper.UserService.ValidateUserData(current, user); current.Email = user.Email; current.FirstName = user.FirstName; current.LastName = user.LastName; helper.UserService.UpdateUser(current); return Json(true, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult SaveAvatar() { try { var file = CommonHelper.Instance.TempFiles.LastOrDefault(); if (file != null) { var user = CommonHelper.Instance.CurrentUser; user.Avatar = file.ImageData; var helper = new IocHelper(); helper.UserService.UpdateUser(user); CommonHelper.Instance.TempFiles = new List<ImageResult>(); return Json(true, JsonRequestBehavior.AllowGet); } else { throw new Exception("Аватар не был изменен"); } } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult UpdateArticleRate(int? articleId,int? rate) { try { var helper = new IocHelper(); var art = helper.ArticleService.GetArticleById(articleId ?? 0); art.Rate = rate ?? 0; helper.ArticleService.UpdateArticle(art); return Json(true, JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public IDto GetEntity(string type, string id) { var maybeType = type.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); var maybeId = id.MaybeAs<string>().Bind(c => c.Split('-').Skip(1).Take(1).Last()).GetOrDefault(""); int currentId; int.TryParse(maybeId, out currentId); var helper = new IocHelper(); switch (maybeType) { default: case "article": var article = helper.ArticleService.GetArticleById(currentId); if (article == null) { throw new Exception("Статьи с данным идентификатором не сущесвует"); } return new ArticleDto(article); //case "image": // return IocHelper.; case "plan": var plan = helper.PlanService.GetPlanById(currentId); if (plan == null) { throw new Exception("Плана с данным идентификатором не сущесвует"); } return new PlanDto(plan); case "group": var group = helper.GroupService.GetGroupById(currentId); if (group == null) { throw new Exception("Группы с данным идентификатором не сущесвует"); } return new GroupDtoView(group); } }
public ActionResult Login(User user) { var helper = new IocHelper(); var currentUser = helper.UserService.GetUserByCredential(user.Credential.Password, user.Credential.Login); if (currentUser == null) { ModelState.AddModelError("", "Пользователь не найден"); return View(user); } else { FormsAuthentication.SetAuthCookie(currentUser.Credential.Login + "[!!!]" + currentUser.UserRole.RoleName(), false); CommonHelper.Instance.CurrentUser = currentUser; return new RedirectResult("../entity/type-article/id-1"); } }
public ActionResult Import(HttpPostedFileBase[] files) { try { var buffer = new byte[files.First().ContentLength]; if (!files.First().ContentType.Contains("xml")) { throw new Exception("Не верный тип файла " + files.First().ContentType); } files.First().InputStream.Read(buffer, 0, files.First().ContentLength); var isDb = IocHelper.CurrentToggle == "db"; var helper = new IocHelper(); var unmatched = helper.ArticleService.Import(isDb, buffer); var stringBuilder = new StringBuilder(); if (unmatched.Count == 0) { stringBuilder.Append("Импорт прошел успешно"); } else { foreach (var res in unmatched) { stringBuilder.Append(string.Format("{0}.<br>", res)); } } return Json(stringBuilder.ToString(), JsonRequestBehavior.AllowGet); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public ActionResult SendEmail() { try { if (!FeatureListModel.Instance.CheckFeatureForEnabled(Features.SwitchEmail)) throw new Exception("Отправка Email оключена"); var helper = new IocHelper(); //helper.ToggleToXml(true); var listOfLinks = helper.ArticleService.GetAllArticles(c => c.ArticleId).OrderBy(c => c.ArticleName) .Select((c, index) => string.Format("{0}) Название: <span style='font-weight:900;color:black'>{1}</span>(<a href='{2}'>{2}</a>)", index + 1, c.ArticleName, c.Link)); var str = string.Join("<br/>", listOfLinks); EmailService.Instance.SendMail(CommonHelper.Instance.CurrentUser.Email, "Список ссылок на статьи", str); //helper.ToggleToDb(true); return Json(CommonHelper.Instance.CurrentUser.Email); } catch (Exception e) { throw new HttpException(500, e.Message); } }
public Article Convert() { int articleId; var article = new Article { ArticleId = this.ArticleId.MaybeAs<string>().Bind(c => string.IsNullOrEmpty(c) ? 0 : int.Parse(c)).GetOrDefault(0), AuthorName = this.AuthorName, InitialText = this.Content, ArticleName = this.ArticleName, Link = this.Link, ArticleGroup = this.Group == null ? null : new ArticleGroup { GroupName = this.Group} }; if (this.ImageIds != null) { var results = CommonHelper.Instance.TempFiles.Where(c => ImageIds.Contains(c.GuidId.ToString())); article.Images = new List<Image>(); article.Images.AddRange(results.Select(c => new Image() { Data = c.ImageData, Name = c.Name, })); if (article.ArticleId != 0) { var helper = new IocHelper(); var expArticle = helper.ArticleService.GetArticleById(article.ArticleId); article.Images.AddRange(expArticle.Images); } } return article; }
private void CacheCallBack(string key) { //var currentLst = value as List<dynamic>; //var lstForSave = currentLst // .Select(c => new Comment { CommentId = Guid.Parse((string)c.id), GroupName = key, CommentText = c.message, UserName = c.name, AddedDate = DateTime.ParseExact((string)c.date, "F", CultureInfo.CreateSpecificCulture("en-US")) }); //IocHelper.CommentService.SaveAll(lstForSave); if (HttpContext.Current != null) { var helper = new IocHelper(); var res = helper.CommentService.GetByGroup(key); HttpContext.Current.Cache.Add(key, res, null, DateTime.MaxValue, new TimeSpan(0, 0, 5, 30), CacheItemPriority.Default, (currentKey, value, reason) => CacheCallBack(currentKey)); } }