Exemple #1
0
        /// <summary>
        /// Add new blog
        /// </summary>
        /// <param name="item">Blog item</param>
        /// <returns>Saved blog with new ID</returns>
        public Models.Blog Add(BlogItem item)
        {
            // has to be on primary blog and be an admin
            // or blog allows create new on self registration
            if (!(Blog.CurrentInstance.IsPrimary && (Security.IsAdministrator || BlogSettings.Instance.CreateBlogOnSelfRegistration)))
            {
                throw new UnauthorizedAccessException();
            }

            string message;

            if (!BlogGenerator.ValidateProperties(item.Name, item.UserName, item.Email, out message))
            {
                throw new ApplicationException(message);
            }

            var coreBlog = BlogGenerator.CreateNewBlog(item.Name, item.UserName, item.Email, item.Password, out message);

            if (coreBlog == null || !string.IsNullOrWhiteSpace(message))
            {
                throw new ApplicationException("Failed to create the new blog.");
            }

            return(ToJson(coreBlog));
        }
        public void Put(int id, [FromBody] BlogItem value)
        {
            var blogItem = this.blogContext
                           .BlogItems.Where(x => x.BlogItemId == id)
                           .Include(p => p.BlogPosts)
                           .FirstOrDefault();

            blogItem.Url    = value.Url;
            blogItem.Rating = value.Rating;

            if (value.BlogPosts != null)
            {
                foreach (var p in value.BlogPosts)
                {
                    var blogPost = blogItem.BlogPosts.Where(x => x.BlogPostId == p.BlogPostId).FirstOrDefault();
                    if (blogPost != null)
                    {
                        blogPost.Content = p.Content;
                        blogPost.Title   = p.Title;
                    }
                    ;
                }
            }

            this.blogContext.BlogItems.Update(blogItem);
            this.blogContext.SaveChanges();
            //throw new NotImplementedException();
        }
Exemple #3
0
        public BlogItem Get(int id)
        {
            BlogDB.PostEntry     postEntry   = BlogDB.Get(id);
            AuthorDB.AuthorEntry authorEntry = AuthorDB.Get(postEntry.AuthorId);

            BlogItem item = new BlogItem
            {
                Id          = postEntry.Id,
                Title       = postEntry.Title,
                Text        = postEntry.Text,
                CreatedDate = postEntry.CreatedDate,
                AuthorName  = authorEntry.Name
            };

            item.SelfLink   = typeof(BlogItem).CreateUri(new { Id = postEntry.Id });
            item.UpLink     = typeof(BlogList).CreateUri();
            item.AuthorLink = typeof(Author).CreateUri(new { Id = authorEntry.Id });

            if (postEntry.ImageId != null)
            {
                item.ImageLink = typeof(Image).CreateUri(new { Id = postEntry.ImageId });
            }

            return(item);
        }
Exemple #4
0
        public async Task Create(string name)
        {
            await Context.Message.DeleteAsync();

            var blogs = DataStorage.RestoreObject <List <BlogItem> >(blogFile) ?? new List <BlogItem>();

            if (blogs.FirstOrDefault(k => k.Name == name) == null)
            {
                var newBlog = new BlogItem
                {
                    BlogId      = Guid.NewGuid(),
                    Author      = Context.User.Id,
                    Name        = name,
                    Subscribers = new List <ulong>()
                };

                blogs.Add(newBlog);

                DataStorage.StoreObject(blogs, blogFile, Formatting.Indented);

                var embed = EmbedHandler.CreateEmbed("Blog", $"Your blog {name} was created.", EmbedHandler.EmbedMessageType.Success);
                await Context.Channel.SendMessageAsync("", false, embed);
            }
            else
            {
                var embed = EmbedHandler.CreateEmbed("Blog :x:", $"There is already a Blog with the name {name}", EmbedHandler.EmbedMessageType.Error);
                await Context.Channel.SendMessageAsync("", false, embed);
            }
        }
Exemple #5
0
        public async Task <IActionResult> Index([FromRoute] int page = 0)
        {
            int    PostsPerPage = 2;
            string blogId       = null;

            if (RouteData.Values.ContainsKey("tenant") && RouteData.Values["tenant"] is BlogItem)
            {
                BlogItem item = RouteData.Values["tenant"] as BlogItem;

                blogId                  = item.Id;
                ViewData["Title"]       = item.Title;
                ViewData["Description"] = item.Description;
                PostsPerPage            = item.PostsPerPage;
            }
            else
            {
                ViewData["Title"]       = _manifest.Name;
                ViewData["Description"] = _manifest.Description;
                PostsPerPage            = _settings.Value.PostsPerPage;
            }

            ViewData["prev"] = $"/{page + 1}/";
            ViewData["next"] = $"/{(page <= 1 ? null : page - 1 + "/")}";

            var posts = await _blog.GetPostsAsync(blogId, PostsPerPage, PostsPerPage *page);

            return(View("~/Views/Blog/Index.cshtml", posts));
        }
        public async Task <IActionResult> Index(int?id, string lang)
        {
            var model = new BlogAllViewModel();

            Utils.CheckOrRefreshUiStrings(lang);
            ViewBag.Title      = Utils.GetUiString("title.blog");
            ViewBag.ActiveLink = 1;

            using (var db = new MysqlDbContext(this.ConnectionString))
            {
                // Get Posts from DB
                var posts = await db.Posts.ToListAsync();

                var blogItems = new List <BlogItem>();

                // Get related mediafiles
                foreach (var b in posts)
                {
                    var blogItem = new BlogItem();

                    blogItem.Post       = b;
                    blogItem.TitleImage = await db.Media.FirstOrDefaultAsync(m => m.Id == b.TitleImage);

                    // TODO: add galleries below!

                    blogItems.Add(blogItem);
                }

                blogItems.OrderBy(d => d.Post.Date).ToList();
                model.FeaturedPost = blogItems.FirstOrDefault();
                model.BlogItems    = blogItems;
            }

            return(this.View(model));
        }
Exemple #7
0
        private BlogItem CreateBlogItem(Item item)
        {
            if (item != null && item.IsDerived(FrasersContent.Templates.Blog.ID))
            {
                var    thumbnailField = ((Data.Fields.ImageField)item.Fields[FrasersContent.Templates.Blog.Fields.Thumbnail]);
                string altText        = thumbnailField.Alt;
                var    blogItem       = new BlogItem
                {
                    Item    = item,
                    Id      = IdHelper.NormalizeGuid(item.ID),
                    Title   = item.Fields[FrasersContent.Templates.Blog.Fields.Title].Value,
                    Summary = item.Fields[FrasersContent.Templates.Blog.Fields.Summary].Value,
                    Url     = item.Url(),
                    Alt     = string.IsNullOrEmpty(altText) ? item.Fields[FrasersContent.Templates.Blog.Fields.Title].Value : altText
                };
                if (item.FieldHasValue(FrasersContent.Templates.SchedulableSetting.Fields.PostDate))
                {
                    blogItem.PostDate = DateUtil.ToServerTime(item.GetDateTime(FrasersContent.Templates.SchedulableSetting.Fields.PostDate));
                }
                if (item.FieldHasValue(FrasersContent.Templates.SchedulableSetting.Fields.ExpiryDate))
                {
                    blogItem.ExpiryDate = DateUtil.ToServerTime(item.GetDateTime(FrasersContent.Templates.SchedulableSetting.Fields.ExpiryDate));
                }
                return(blogItem);
            }

            return(null);
        }
Exemple #8
0
        private IActionResult ZenFeed(BlogItem blog, string host, PostItem[] posts)
        {
            XNamespace contentNamespace = "http://purl.org/rss/1.0/modules/content/";
            XNamespace dcNamespace      = "http://purl.org/dc/elements/1.1/";
            XNamespace mediaNamespace   = "http://search.yahoo.com/mrss/";
            XNamespace atomNamespace    = "http://www.w3.org/2005/Atom";
            XNamespace georssNamespace  = "http://www.georss.org/georss";

            var feedUri = new Uri(host);

            var itemElements = posts
                               .Select(post =>
            {
                var render = post.Content.MdToZen(feedUri);

                return(new XElement(
                           "item",
                           new XElement("guid", feedUri + $"posts/{post.Slug}", new XAttribute("isPermaLink", false)),
                           new XElement("title", post.Title),
                           new XElement("link", feedUri + $"posts/{post.Slug}"),
                           new XElement("pubDate", post.Published),
                           new XElement("author", post.Author.DisplayName),
                           new XElement("title", post.Title),
                           post.Categories?.Split(",").Select(x => new XElement("category", x)),
                           new XElement("description", post.Description),
                           new XElement(contentNamespace + "encoded", render.content),
                           new XElement(
                               "enclosure",
                               new XAttribute("url", feedUri + post.Cover)),
                           render.images.Select(x => new XElement(
                                                    "enclosure",
                                                    new XAttribute("url", feedUri + x.Url)))
                           ));
            });

            var rssDocument = new XDocument(
                new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement(
                    "rss",
                    new XAttribute("version", "2.0"),
                    new XAttribute(XNamespace.Xmlns + "content", contentNamespace),
                    new XAttribute(XNamespace.Xmlns + "dc", dcNamespace),
                    new XAttribute(XNamespace.Xmlns + "media", mediaNamespace),
                    new XAttribute(XNamespace.Xmlns + "atom", atomNamespace),
                    new XAttribute(XNamespace.Xmlns + "georss", georssNamespace),
                    new XElement(
                        "channel",
                        new XElement("title", blog.Title),
                        new XElement("link", feedUri),
                        new XElement("description", blog.Description),
                        new XElement("language", "ru"),
                        itemElements)));

            return(new ContentResult
            {
                Content = rssDocument.ToString(),
                ContentType = "text/xml",
                StatusCode = 200
            });
        }
Exemple #9
0
        public async Task <IActionResult> Edit(int id, [Bind("BlogItemID,ConvID,Subject,Message")] BlogItem blogItem)
        {
            using (ApplicationDbContextcs db = new ApplicationDbContextcs())
            {
                if (id != blogItem.BlogItemID)
                {
                    return(NotFound());
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        db.Update(blogItem);
                        await db.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!BlogItemExists(blogItem.BlogItemID))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                    string url = @"../../ConvBlogItems/Conversation/" + blogItem.ConvID;
                    return(Redirect(url));
                }
                ViewData["ConvID"] = blogItem.ConvID;
                return(View(blogItem));
            }
        }
Exemple #10
0
        public async Task <IActionResult> OnPostAsync()
        {
            Blog = await _db.CustomFields.GetBlogSettings();

            var author = await _db.Authors.GetItem(a => a.AppUserName == User.Identity.Name);

            IsAdmin = author.IsAdmin;

            var page = int.Parse(Request.Form["page"]);
            var term = Request.Form["search"];


            Pager = new Pager(page, Blog.ItemsPerPage);

            if (IsAdmin)
            {
                Posts = await _db.BlogPosts.Search(Pager, term);
            }
            else
            {
                Posts = await _db.BlogPosts.Search(Pager, term, author.Id);
            }

            return(Page());
        }
Exemple #11
0
        public async Task Create(string name)
        {
            await Context.Message.DeleteAsync();

            var dataStorage = InversionOfControl.Container.GetInstance <JsonDataStorage>();
            var blogs       = dataStorage.RestoreObject <List <BlogItem> >(blogFile) ?? new List <BlogItem>();

            if (blogs.FirstOrDefault(k => k.Name == name) == null)
            {
                var newBlog = new BlogItem
                {
                    BlogId      = Guid.NewGuid(),
                    Author      = Context.User.Id,
                    Name        = name,
                    Subscribers = new List <ulong>()
                };

                blogs.Add(newBlog);

                dataStorage.StoreObject(blogs, blogFile, Formatting.Indented);

                var embed = EmbedHandler.CreateEmbed($"Stworzyłem Twojego bloga o nazwie {name}!", EmbedHandler.EmbedMessageType.Success);
                await Context.Channel.SendMessageAsync("", false, embed);
            }
            else
            {
                var embed = EmbedHandler.CreateEmbed($"Już istnieje blog z tą nazwą: {name}", EmbedHandler.EmbedMessageType.Error);
                await Context.Channel.SendMessageAsync("", false, embed);
            }
        }
Exemple #12
0
        public IActionResult Comment(CommentViewModel model)
        {
            if (!IsUserLoggedIn())
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.PleaseLoginToComment);
            }

            BlogItem blogItem = _blogProvider.GetBlog(model.BlogId);

            if (blogItem == null)
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.InvalidBlog);
            }


            if (ModelState.IsValid)
            {
                UserSession user    = GetUserSession();
                string      comment = WebUtility.HtmlEncode(model.Comment).Replace("\r\n", "<br />");
                _blogProvider.AddComment(blogItem, null, user.UserID, user.UserName, comment);
                return(Redirect(GetBlogItemUrl(blogItem)));
            }

            BlogPostViewModel blogModel = GetBlogPostViewModel(blogItem);

            blogModel.Breadcrumbs.Add(new BreadcrumbItem(Languages.LanguageStrings.Blog, $"/{Name}/{nameof(Index)}", false));
            blogModel.Breadcrumbs.Add(new BreadcrumbItem(blogItem.Title, blogModel.Url, false));
            model.Comment = String.Empty;

            return(View("ViewBlog", blogModel));
        }
        public async Task <IActionResult> Index(string lang)
        {
            var model = new HomeViewModel();

            Utils.CheckOrRefreshUiStrings(lang);
            ViewBag.Title = Utils.GetUiString("title.home");

            using (var db = new MysqlDbContext(this.ConnectionString))
            {
                model.CoreData = await db.CoreData.FirstOrDefaultAsync();

                var latestPosts = db.Posts.Where(p => p.IsPublished).Take(3);

                var blogItems = new List <BlogItem>();

                // Get related mediafiles
                foreach (var b in latestPosts)
                {
                    var blogItem = new BlogItem();

                    blogItem.Post       = b;
                    blogItem.TitleImage = await db.Media.FirstOrDefaultAsync(m => m.Id == b.TitleImage);

                    // TODO: add galleries below!

                    blogItems.Add(blogItem);
                }

                model.LatestPosts = blogItems;
            }

            return(this.View(model));
        }
        private async Task SeedGeneratedBlogItemsModels()
        {
            if (!_context.BlogItems.Any())
            {
                if (_context.Users.Any())
                {
                    var user = _context.Users.FirstOrDefault();

                    for (int i = 0; i < NumberGenerator.RandomNumber(6, 12); i++)
                    {
                        var newBlogItem = new BlogItem
                        {
                            AuthorId    = user.Id,
                            CreatedOn   = DateTime.Now.AddDays(NumberGenerator.RandomNumber(1, 10)),
                            Summary     = StringGenerator.RandomStringWithSpaces(40, 200),
                            Title       = StringGenerator.RandomStringWithSpaces(10, 60),
                            Description = StringGenerator.RandomStringWithSpaces(200, 2000),
                        };

                        _context.BlogItems.Add(newBlogItem);
                    }
                    await _context.SaveChangesAsync();
                }
            }
        }
        public async Task <IActionResult> Post(int id, string lang)
        {
            var model = new BlogPostViewModel();

            Utils.CheckOrRefreshUiStrings(lang);
            ViewBag.Title      = Utils.GetUiString("title.blog");
            ViewBag.ActiveLink = 1;

            var postItem = new BlogItem();

            using (var db = new MysqlDbContext(this.ConnectionString))
            {
                var post = await db.Posts.SingleOrDefaultAsync(b => b.Id == id);

                var titleImage = await db.Media.SingleOrDefaultAsync(i => i.Id == post.TitleImage);

                // TODO: add gallery
                postItem.Post       = post;
                postItem.TitleImage = titleImage;

                ViewBag.Title = $"{post.Title} | {Utils.GetUiString("title.blog")} ";
            }

            model.Post = postItem;

            return(this.View(model));
        }
        public async Task <ActionResult <BlogItem> > Post(BlogItem model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid data"));
                }

                await _data.CustomFields.SaveBlogSettings(model);

                var updated = await _data.CustomFields.GetBlogSettings();

                // set language culture here
                Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(updated.Culture)),
                    new CookieOptions {
                    Expires = DateTimeOffset.UtcNow.AddYears(1)
                }
                    );
                return(Created($"/api/settings", updated));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
        public bool UpdateBlogItemById(BlogItem b)
        {
            try
            {
                MySqlConnection cnn    = ReturnMYSQLConnection();
                var             query  = "UPDATE BlogItem SET Title=@Title, Message=@Message, CreatedDate=@CreatedDate, Published=@Published, Thumbnail=@Thumbnail WHERE ID = @Id";
                MySqlCommand    newCmd = CreateMYSQLCommandText(query, cnn);

                newCmd.Parameters.AddWithValue("@Id", b.RetrieveId());
                newCmd.Parameters.AddWithValue("@Title", b.RetrieveTitle());
                newCmd.Parameters.AddWithValue("@Message", b.RetrieveMessage());
                newCmd.Parameters.AddWithValue("@CreatedDate", b.CreatedDate);
                newCmd.Parameters.AddWithValue("@Published", b.Publised);
                newCmd.Parameters.AddWithValue("@Thumbnail", b.Thumbnail);

                newCmd.ExecuteNonQuery();
                cnn.Close();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(false);
        }
Exemple #18
0
 public IndexModel(IDataService db, IStorageService storage, INotificationService ns)
 {
     _db      = db;
     _storage = storage;
     _ns      = ns;
     BlogItem = new BlogItem();
 }
Exemple #19
0
        public List <BlogItem> RetrieveAllBlogItems()
        {
            var listOfItems = new List <BlogItem>();

            try
            {
                MySqlConnection cnn   = ReturnMYSQLConnection();
                var             query = "SELECT * FROM BlogItem";
                MySqlCommand    cmd   = CreateMYSQLCommandText(query, cnn);

                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var    itemId      = Convert.ToInt32(dr["ID"]);
                    var    title       = dr["Title"].ToString();
                    string message     = dr["Message"].ToString();
                    var    createddate = Convert.ToDateTime(dr["CreatedDate"]);
                    int    published   = Convert.ToInt32(dr["Published"]);

                    BlogItem b = new BlogItem(itemId, title, message);
                    b.CreatedDate = createddate;
                    b.Publised    = published;

                    listOfItems.Add(b);
                }

                cnn.Close();
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e.Message);
            }

            return(listOfItems);
        }
Exemple #20
0
        public void EditBlog(int id)
        {
            BlogItem blogItem;

            if (id == -1)
            {
                blogItem = new BlogItem(MainV.Config);
                Log.Write($"Created new blog");
            }
            else
            {
                blogItem = Blogs.Where(x => x.Id == id).FirstOrDefault();
                Log.Write($"Edit blog item {blogItem.Id}");
            }

            EditBlogItemViewModel editBlogItemVM = new EditBlogItemViewModel(MainV.MainVM, blogItem);

            if (editBlogItemVM.ShowBlogItem())
            {
                if (id == -1)
                {
                    Blogs.Add(blogItem);
                }

                SaveBlogs();
            }
        }
Exemple #21
0
        //Read the Feed and put it in a model
        private void ProcessDocuments(SyndicationFeed documents)
        {
            string message = string.Format("Found {0} Documents within the " + BlogName + " Feed",
                                           documents.Items.Count());

            Sitecore.Diagnostics.Log.Error(message, "RssFeedImport");

            //start iterating through the feed
            foreach (var doc in documents.Items)
            {
                bool ismatch = false;

                bool blogfound = BlogExistsNoIndex(doc.Id);
                ismatch = blogfound == true;
                // }

                if (!ismatch)
                {
                    var pubsmodel = new BlogItem()
                    {
                        BlogTitle       = doc.Title.Text,
                        BlogAbstract    = doc.Summary.Text,
                        BlogSourceUrl   = doc.Id,
                        BlogDisplayDate = doc.PublishDate.ToString(),
                        BlogID          = doc.Id
                    };

                    ProcessNewBlogItem(pubsmodel);
                }
            }
        }
Exemple #22
0
 public ActionResult Create([Bind(Include = "ID,Photo,Header,Description,CreateDate,Photo,AuthorName")] BlogItem blogItem, HttpPostedFileBase Image, DateTime?mainDate)
 {
     if (ModelState.IsValid)
     {
         if (mainDate == null)
         {
             blogItem.CreateDate = DateTime.Now;
         }
         else
         {
             blogItem.CreateDate = (DateTime)mainDate;
         }
         if (Image != null)
         {
             WebImage img      = new WebImage(Image.InputStream);
             FileInfo imgInfo  = new FileInfo(Image.FileName);
             string   FileName = Guid.NewGuid().ToString() + imgInfo.Extension;
             img.Save("~/Public/uploads/BlogPhoto/" + FileName);
             blogItem.Photo = "/Public/uploads/BlogPhoto/" + FileName;
         }
         db.BlogItem.Add(blogItem);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(blogItem));
 }
Exemple #23
0
        public ActionResult Edit([Bind(Include = "ID,Photo,Header,Description,CreateDate,AuthorName,Photo")] BlogItem blogItem, DateTime?mainDate, HttpPostedFileBase Image, int id)
        {
            if (ModelState.IsValid)
            {
                if (mainDate == null)
                {
                    blogItem.CreateDate = DateTime.Now;
                }
                else
                {
                    blogItem.CreateDate = (DateTime)mainDate;
                }
                BlogItem selectedBlog = db.BlogItem.SingleOrDefault(nvb => nvb.ID == id);
                if (Image != null)
                {
                    if (System.IO.File.Exists(Server.MapPath(selectedBlog.Photo)))
                    {
                        System.IO.File.Delete(Server.MapPath(selectedBlog.Photo));
                    }

                    WebImage img      = new WebImage(Image.InputStream);
                    FileInfo imgInfo  = new FileInfo(Image.FileName);
                    string   FileName = Guid.NewGuid().ToString() + imgInfo.Extension;
                    img.Save("~/Public/uploads/" + FileName);
                    selectedBlog.Photo = "/Public/uploads/" + FileName;
                }
                selectedBlog.Description = blogItem.Description;
                selectedBlog.CreateDate  = blogItem.CreateDate;
                selectedBlog.Header      = blogItem.Header;
                selectedBlog.AuthorName  = blogItem.AuthorName;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(blogItem));
        }
Exemple #24
0
        public BlogItem RetrieveBlogItemById(int id)
        {
            var b = new BlogItem(-1, null, null);

            try
            {
                MySqlConnection cnn   = ReturnMYSQLConnection();
                string          query = "SELECT * FROM BlogItem WHERE ID=@ID";
                MySqlCommand    cmd   = CreateMYSQLCommandText(query, cnn);
                cmd.Parameters.AddWithValue("@ID", id);
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var    itemId      = Convert.ToInt32(dr["ID"]);
                    var    title       = dr["Title"].ToString();
                    string message     = dr["Message"].ToString();
                    var    createddate = Convert.ToDateTime(dr["CreatedDate"]);
                    int    published   = Convert.ToInt32(dr["Published"]);

                    b             = new BlogItem(itemId, title, message);
                    b.CreatedDate = createddate;
                    b.Publised    = published;
                }

                cnn.Close();
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e.Message);
            }
            return(b);
        }
Exemple #25
0
        public ActionResult <BlogItem> PostBlogItem(BlogItem item)
        {
            _blogService.AddBlog(item);

            return(CreatedAtAction(nameof(GetBlogItem), new BlogItem {
                Id = item.Id
            }, item));
        }
        public IActionResult Post(int blogToSee)
        {
            BlogItem          b          = blogRepo.RetrieveBlogItemById(blogToSee);
            var               mapperBlog = mapper.BlogToBlogItemViewModel();
            BlogItemViewModel bmodel     = mapperBlog.Map <BlogItemViewModel>(b);

            return(View("Singleblog", bmodel));
        }
Exemple #27
0
        public ActionResult DeleteConfirmed(int id)
        {
            BlogItem blogItem = db.BlogItem.Find(id);

            db.BlogItem.Remove(blogItem);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #28
0
        async Task SetModel()
        {
            var author = await _db.Authors.GetItem(a => a.AppUserName == User.Identity.Name);

            IsAdmin       = author.IsAdmin;
            Notifications = await _ns.GetNotifications(author.Id);

            BlogItem = await _db.CustomFields.GetBlogSettings();
        }
Exemple #29
0
        public Task <IList <BlogItem> > LoadItemsAsync(BlogGroup group)
        {
            return(Task.Run(async() =>
            {
                var feed = await GetFeed(group.RssUri);

                IList <BlogItem> items = new List <BlogItem>();

                foreach (var item in feed.Items)
                {
                    try
                    {
                        var blogItem = new BlogItem {
                            Group = group
                        };
                        var uri = string.Empty;

                        if (item.Links.Count > 0)
                        {
                            var link =
                                item.Links.FirstOrDefault(
                                    l => l.RelationshipType.Equals("alternate", StringComparison.OrdinalIgnoreCase)) ??
                                item.Links[0];
                            uri = link.Uri.AbsoluteUri;
                        }

                        blogItem.Id = uri;

                        blogItem.PageUri = new Uri(uri, UriKind.Absolute);
                        blogItem.Title = item.Title != null ? item.Title.Text : "(no title)";

                        blogItem.PostDate = item.PublishDate.LocalDateTime;

                        var content = "(no content)";

                        if (item.Content != null)
                        {
                            content = BlogUtility.ParseHtml(((TextSyndicationContent)item.Content).Text);
                        }
                        else if (item.Summary != null)
                        {
                            content = BlogUtility.ParseHtml(item.Summary.Text);
                        }

                        blogItem.Description = content;

                        items.Add(blogItem);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

                return items;
            }));
        }
Exemple #30
0
 public int AddBlogItem(BlogItem blogItem)
 {
     return(_dataAccessor.Execute(INSERT_ITEM, new {
         blogItem.Id,
         blogItem.CreatedByUser,
         blogItem.BlogId,
         blogItem.Text
     }));
 }
Exemple #31
0
		public BlogItem CreateStateless(Blog blog)
		{
			using (IStatelessSession session = sessManager.OpenStatelessSession())
			{
				BlogItem item = new BlogItem();

				item.ParentBlog = blog;
				item.ItemDate = DateTime.Now;
				item.Text = "x";
				item.Title = "splinter cell is cool!";

				session.Insert(item);

				return item;
			}
		}
		public virtual BlogItem CreateWithException(Blog blog)
		{
			using (ISession session = sessManager.OpenSession())
			{
				NUnit.Framework.Assert.IsNotNull(session.Transaction);

				var item = new BlogItem();

				item.ParentBlog = blog;
				item.ItemDate = DateTime.Now;
				item.Text = "x";
				item.Title = "splinter cell is cool!";

				throw new NotSupportedException("I dont feel like supporting this");
			}
		}
		public override void OnSetUp()
		{
			this.container.Register(Component.For<NHibernateGenericDao>()
										.ImplementedBy<NHibernateGenericDao>());
			this.sessionManager = this.container.Resolve<ISessionManager>();
			this.nhGenericDao = this.container.Resolve<NHibernateGenericDao>();
			this.nhGenericDao2 = new NHibernateGenericDao(this.sessionManager, "sessionFactory1");
			using (var session = sessionManager.OpenSession())
			{
				var blog1 = new Blog { Name = "myblog1" };
				var blog1Item = new BlogItem
									{
										ItemDate = DateTime.Now,
										ParentBlog = blog1,
										Text = "Hello",
										Title = "mytitle1"
									};
				blog1.Items.Add(blog1Item);

				var blog2 = new Blog { Name = "myblog2" };
				var blog2Item = new BlogItem
									{
										ItemDate = DateTime.Now,
										ParentBlog = blog1,
										Text = "Hello",
										Title = "mytitle2"
									};
				blog2.Items.Add(blog2Item);

				var blog3 = new Blog { Name = "myblog3" };
				var blog3Item = new BlogItem
				{
					ItemDate = DateTime.Now,
					ParentBlog = blog1,
					Text = "Hello3",
					Title = "mytitle3"
				};
				blog3.Items.Add(blog3Item);
				session.Save(blog1);
				session.Save(blog1Item);
				session.Save(blog2);
				session.Save(blog2Item);
				session.Save(blog3);
				session.Save(blog3Item);
			}

		}
		public virtual BlogItem Create(Blog blog)
		{
			using (ISession session = sessManager.OpenSession())
			{
				NUnit.Framework.Assert.IsNotNull(session.Transaction);

				var item = new BlogItem();

				item.ParentBlog = blog;
				item.ItemDate = DateTime.Now;
				item.Text = "x";
				item.Title = "splinter cell is cool!";

				session.Save(item);

				return item;
			}
		}
        public override void AddBlog(BlogItem item)
        {
            // create the post from the item
            Blog_Posts post = new Blog_Posts();
            post.Title = item.Title;
            post.Body = item.Body;
            post.Published = item.Published;
            post.AllowComments = item.AllowComments;
            post.Syndicate = item.Syndicate;
            post.User_ID = item.PosterID;
            post.TitleUrl = (item.TitleUrl != null) ? item.TitleUrl.ToString() : null;
            post.Source = item.Source;
            post.SourceUrl = (item.SourceUrl != null) ? item.SourceUrl.ToString() : null;
            post.Created = item.Created;
            post.Issued = item.Issued;
            post.Modified = item.Modified;

            // insert the post into the database
            post.Insert();
        }
Exemple #36
0
        /// <summary>
        /// Широковещательная рассылка всем заинтересованным пользователям извещения о новом посте
        /// </summary>
        /// <param name="item">Публикуемая запись</param>
        private static void BroadcastNewPost(BlogItem item)
        {
            //Получение экземпляра Хаба
            var context = GlobalHost.ConnectionManager.GetHubContext<BlogHub>();

            context.Clients[item.User.Id.ToString()].newPost(new
                                                                 {
                                                                     DateTime = DateTime.Now,
                                                                     Message = item.Message
                                                                 });

            _logger.Trace("Broadcast message from [{0}:{1}] : {2}", item.User.Name, item.User.Id, item.Message);
        }
Exemple #37
0
        public HttpResponseMessage Post(BlogItem item)
        {
            //определение имени публикующего
            var userName = User.Identity.Name;

            // востановление объекта пользователя
            var user = _userRepository.All.Single(x => x.Name == userName);
            item.User = user;
            item.DateTime = DateTime.Now;
            //Добавление новой записи в блог пользователя
            user.BlogItems.Add(item);
            _userRepository.Save();

            // Извещение всех подписчиков блога о новом сообщении
            // Если бы сообщения были большими... или напимер сложносотавными (текст с картинками)
            // то отправляли бы ссылку(адрес) для запроса нового сообщения через GET-метод контроллера
            BroadcastNewPost(item);

            // Возврат статуса 201
            return new HttpResponseMessage(HttpStatusCode.Created);
        }