+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / Creating News Items - Native API

Creating News Items - Native API

11 posts, 0 answered
  1. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    14 Sep 2012
    Link to this post

    Hi,

    I have created a user control to allow people to post news items from the front end of the website without being authenticated by following the documentation here http://www.sitefinity.com/documentation/documentationarticles/developers-guide/sitefinity-essentials/modules/news/creating-news-items. When a news item is created I assign a "staff-notice-board" category to the news item.

    This all appears to work correctly as when you look in "Content > News" I can see the news items and all the information is correct including the category.

    When I add a news list to a page and try to filter by "staff-notice-board" it doesn't return any results however if I leave the list unfiltered they appear.

    The only way I can get the news items that have that the category set to "staff-notice-board" to display in a filtered list  is to open them individually via "Content > News" and then clicking publish.

    Although my code is setting the category I don't think by doing it this way it is updating all the appropriate tables in the database which is why it isn't appearing in my news items that have been filtered by a category.

    It's a long shot but has anyone else experienced this? I have copied the code in my user control below.

    Thanks
    Richard

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="NoticeBoard.ascx.cs" Inherits="Controls_NoticeBoard" %>
    <div style="margin-top: 10px; display:block;">
        <asp:Panel ID="pnlClassifieds" runat="server" Visible="true">
            <div>
                <asp:Label ID="lblNewsTitle" runat="server" Text="Title" Style="font-weight: bold"></asp:Label></div>
            <div>
                <asp:TextBox ID="txtNewsTitle" runat="server" MaxLength="100" Style="width: 300px;"></asp:TextBox>
            </div>
            <div>
                <asp:RequiredFieldValidator ID="valNewsTitle" runat="server" ErrorMessage="Please complete this field"
                    Text="Please complete this field" Display="Dynamic" ControlToValidate="txtNewsTitle"
                    SetFocusOnError="True" ForeColor="Red" ValidationGroup="Classified"></asp:RequiredFieldValidator></div>
            <div style="margin-top: 10px;">
                <asp:Label ID="lblNewsSummary" runat="server" Text="Summary" Style="font-weight: bold"></asp:Label></div>
            <div style="margin-top: 4px;">
                <asp:TextBox ID="txtNewsSummary" runat="server" MaxLength="150" TextMode="MultiLine"
                    Rows="2" Style="width: 300px; font-family:Arial;"></asp:TextBox>
            </div>
            <div>
                <asp:RequiredFieldValidator ID="valNewsSummary" runat="server" ErrorMessage="Please complete this field"
                    Display="Dynamic" Text="Please complete this field" ControlToValidate="txtNewsSummary"
                    SetFocusOnError="True" ForeColor="Red" ValidationGroup="Classified"></asp:RequiredFieldValidator></div>
            <div style="margin-top: 10px;">
                <asp:Label ID="lblNewsContent" runat="server" Text="Content" Style="font-weight: bold"></asp:Label></div>
            <div style="margin-top: 4px;">
                <asp:TextBox ID="txtNewsContent" runat="server" TextMode="MultiLine" Rows="5" MaxLength="512"
                    Style="width: 300px; font-family:Arial;"></asp:TextBox>
            </div>
            <div>
                <asp:RequiredFieldValidator ID="valNewsContent" runat="server" ErrorMessage="Please complete this field"
                    Text="Please complete this field" ControlToValidate="txtNewsContent" SetFocusOnError="True"
                    ForeColor="Red" ValidationGroup="Classified"></asp:RequiredFieldValidator></div>
            <div style="margin-top: 10px;">
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"
                    ValidationGroup="Classified" />
            </div>
        </asp:Panel>
        <asp:Panel ID="pnlClassifiedsConfirm" runat="server" Visible="false">
            <div><b>Thank you, your item has been submitted successfully.</b></div>
        </asp:Panel>
    </div>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.OpenAccess;
    using Telerik.Sitefinity;
    using Telerik.Sitefinity.Model;
    using Telerik.Sitefinity.Modules.News;
    using Telerik.Sitefinity.News.Model;
    using Telerik.Sitefinity.Taxonomies;
    using Telerik.Sitefinity.Taxonomies.Model;
    using Telerik.Sitefinity.Workflow;
     
    public partial class Controls_NoticeBoard : System.Web.UI.UserControl
    {
        public const string UrlNameCharsToReplace = @"[^\w\-\!\$\'\(\)\=\@\d_]+";
        public const string UrlNameReplaceString = "-";
     
        protected void Page_Load(object sender, EventArgs e)
        {
     
        }
     
        private void CreateStaffNoticeBoardItem(string txtNewsTitle, string txtNewsSummary, string txtNewsContent)
        {
            // Create new news item id
            Guid masterNewsId = Guid.NewGuid();
            // Set up news manager
            NewsManager newsManager = NewsManager.GetManager();
            // Bypass security so any user can post
            NewsManager.GetManager().Provider.SuppressSecurityChecks = true;
            NewsItem newsItem = newsManager.GetNewsItems().Where(item => item.Id == masterNewsId).FirstOrDefault();
     
            if (newsItem == null)
            {
                // Add the news item
                // The news item is created as a master. The newsId is assigned to the master.
                newsItem = newsManager.CreateNewsItem(masterNewsId);
                newsItem.Title = txtNewsTitle;
                newsItem.Summary = txtNewsSummary;
                newsItem.Content = txtNewsContent;
                newsItem.DateCreated = DateTime.Now;
                newsItem.PublicationDate = DateTime.Now;
                newsItem.LastModified = DateTime.Now;
                newsItem.ExpirationDate = DateTime.Now.AddDays(+30);
                newsItem.AllowComments = false;
                newsItem.UrlName = Regex.Replace(txtNewsTitle.ToLower(), UrlNameCharsToReplace, UrlNameReplaceString);
                newsItem.ApprovalWorkflowState = "Published";
                newsManager.Lifecycle.Publish(newsItem);
                // Save the changes.
                newsManager.SaveChanges();
     
     
                // Set the category for new news item to classifieds - news item already needs to be created first
                // Get new news item id
                newsItem = newsManager.GetNewsItem(masterNewsId);
                TaxonomyManager manager = TaxonomyManager.GetManager();
                var categoryId = manager.GetTaxa<HierarchicalTaxon>().Where(t => t.Name == "staff-notice-board").Single().Id;
                var catlist = newsItem.GetValue<TrackedList<Guid>>("Category");
                catlist.Add(categoryId);
                newsItem.SetValue("Category", catlist);
     
                // Save the changes.
                newsManager.SaveChanges();
     
                // Publish the news item. The published version acquires new ID.
                var bag = new Dictionary<string, string>();
                bag.Add("ContentType", typeof(NewsItem).FullName);
     
     
     
            }
     
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            CreateStaffNoticeBoardItem(txtNewsTitle.Text, txtNewsSummary.Text, txtNewsContent.Text);
            pnlClassifieds.Visible = false;
            pnlClassifiedsConfirm.Visible = true;
        }
    }





  2. Lupi
    Lupi avatar
    38 posts
    Registered:
    17 May 2004
    14 Sep 2012
    Link to this post
    Hi Richard,

    Instead of these lines of code

    var catlist = newsItem.GetValue<TrackedList<Guid>>("Category");
    catlist.Add(categoryId);
    newsItem.SetValue("Category", catlist);

    use this line of code

    newsItem.Organizer.AddTaxa("Category", new Guid[] { categoryId });
  3. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    14 Sep 2012
    Link to this post
    Hi Lupi,

    Just tried this but it didn't make any difference.
  4. SelAromDotNet
    SelAromDotNet avatar
    912 posts
    Registered:
    18 Jul 2012
    14 Sep 2012
    Link to this post
    Richard, are you using Workflow on your news module?

    If not, try using the Lifecycle member of the NewsManager to publish the item, as follows:
    newsItem.ApprovalWorkflowState = "Published";
    newsManager.Lifecycle.Publish(albumItem);
    newsManager.SaveChanges();

    this should kick it through to the published state so that it appears as such in the backend list.

    I hope this is helpful!

  5. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    14 Sep 2012
    Link to this post
    Hi SelAromDotNet,

    This is how I am doing it and it and it is publishing fine but the category is the issue. Although it sets the category of the news item it does not appear in filtered lists by the category set for some reason.

    You have to re-publish it so to speak to get it to appear in the filtered list.
  6. SelAromDotNet
    SelAromDotNet avatar
    912 posts
    Registered:
    18 Jul 2012
    14 Sep 2012
    Link to this post
    oh sorry, my mistake I understood your problem to be that it wasn't "saving" your changes including the category as a published item...



    so when you open your created item in the backend, is that category selected? or do you have to select it then publish it?



    If it is you're saying that all you have to do is publish it, and it works as expected with the filter, is that correct?
  7. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    14 Sep 2012
    Link to this post
    My code inserts the news item fine, sets the category and sets the status to published. When you look in the backend "Content > News" and the newly created item everything looks correct.

    I'll add a news list to a page and by default it won't be filtered and it will be displayed. If I try to filter the list by the category that was assigned to the news item the list won't display anything.

    The only way you can get the news item in the filtered list is to re-publish it from the backend which seems to me that the code isn't populating the required tables that are needed to set categorys on the news items.
  8. Lupi
    Lupi avatar
    38 posts
    Registered:
    17 May 2004
    14 Sep 2012
    Link to this post
    Richard, this is the code I tried and it worked --

    if (newsItem == null)
    {
        // Add the news item
        // The news item is created as a master. The newsId is assigned to the master.
        newsItem = newsManager.CreateNewsItem(masterNewsId);
        newsItem.Title = "News Title";
        newsItem.Summary = "News Summary";
        newsItem.Content = "News Content";
        newsItem.DateCreated = DateTime.Now;
        newsItem.PublicationDate = DateTime.Now;
        newsItem.LastModified = DateTime.Now;
        newsItem.ExpirationDate = DateTime.Now.AddDays(+30);
        newsItem.AllowComments = false;
        newsItem.UrlName = "news-title";
        var manager = TaxonomyManager.GetManager();
        var categoryId = manager.GetTaxa<HierarchicalTaxon>().Where(t => t.Name == "staff-notice-board").Single().Id;
      
        newsItem.Organizer.AddTaxa("Category", new Guid[] { categoryId });
      
        // Save the changes.
        newsManager.SaveChanges();
      
        var bag = new Dictionary<string, string>();
        bag.Add("ContentType", typeof(NewsItem).FullName);
        WorkflowManager.MessageWorkflow(masterNewsId, typeof(NewsItem), null, "Publish", false, bag);
    }

    You don't need to save the news item before assigning a category to it.
  9. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    14 Sep 2012
    Link to this post
    Hi Lupi,

    In order to use the WorkflowManager you have to be authenticated and the users on this particular site are not which is why I am using newsManager.Lifecycle.Publish(newsItem); at the recommendation of Telerik.
  10. Lupi
    Lupi avatar
    38 posts
    Registered:
    17 May 2004
    14 Sep 2012
    Link to this post
    This is strange, the code below did it for me - executed it as anonymous user and after refreshing a test page with a News widget set to show only news items with category "staff-notice-board" the new item showed up.

    var newsItem = newsManager.CreateNewsItem(masterNewsId);
    newsItem.Title = "News Title";
    newsItem.Summary = "News Summary";
    newsItem.Content = "News Content";
    newsItem.DateCreated = DateTime.Now;
    newsItem.PublicationDate = DateTime.Now;
    newsItem.LastModified = DateTime.Now;
    newsItem.ExpirationDate = DateTime.Now.AddDays(+30);
    newsItem.AllowComments = false;
    newsItem.UrlName = "news-title";
    newsItem.Organizer.AddTaxa("Category", new Guid[] { categoryId });
     
    // Save the changes.
    newsItem.ApprovalWorkflowState = "Published";
    newsManager.Lifecycle.Publish(newsItem);
    newsManager.SaveChanges();
  11. Richard
    Richard avatar
    63 posts
    Registered:
    20 Jan 2010
    17 Sep 2012
    Link to this post
    Hi Lupi,

    I have modified my existing code and it now works as intended.

    The main change was newsItem.Organizer.AddTaxa("Category", new Guid[] { categoryId });

    Thanks for your help.

    Richard
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.OpenAccess;
    using Telerik.Sitefinity;
    using Telerik.Sitefinity.Model;
    using Telerik.Sitefinity.Modules.News;
    using Telerik.Sitefinity.News.Model;
    using Telerik.Sitefinity.Taxonomies;
    using Telerik.Sitefinity.Taxonomies.Model;
    using Telerik.Sitefinity.Workflow;
      
    public partial class Controls_NoticeBoard : System.Web.UI.UserControl
    {
        public const string UrlNameCharsToReplace = @"[^\w\-\!\$\'\(\)\=\@\d_]+";
        public const string UrlNameReplaceString = "-";
      
        protected void Page_Load(object sender, EventArgs e)
        {
      
        }
      
        private void CreateStaffNoticeBoardItem(string txtNewsTitle, string txtNewsSummary, string txtNewsContent)
        {
            // Create new news item id
            Guid masterNewsId = Guid.NewGuid();
            // Set up news manager
            NewsManager newsManager = NewsManager.GetManager();
            // Bypass security so any user can post
            NewsManager.GetManager().Provider.SuppressSecurityChecks = true;
            // Check if news item already exists - item might be saved as draft
            NewsItem newsItem = newsManager.GetNewsItems().Where(item => item.Id == masterNewsId).FirstOrDefault();
      
            if (newsItem == null)
            {
                // Add the news item
                newsItem = newsManager.CreateNewsItem(masterNewsId);
                newsItem.Title = txtNewsTitle;
                newsItem.Summary = txtNewsSummary;
                newsItem.Content = txtNewsContent;
                newsItem.DateCreated = DateTime.Now;
                newsItem.PublicationDate = DateTime.Now;
                newsItem.LastModified = DateTime.Now;
                newsItem.ExpirationDate = DateTime.Now.AddDays(+30);
                newsItem.AllowComments = false;
                newsItem.UrlName = Regex.Replace(txtNewsTitle.ToLower(), UrlNameCharsToReplace, UrlNameReplaceString);
      
                TaxonomyManager manager = TaxonomyManager.GetManager();
                var categoryId = manager.GetTaxa<HierarchicalTaxon>().Where(t => t.Name == "staff-notice-board").Single().Id;
                newsItem.Organizer.AddTaxa("Category", new Guid[] { categoryId });
      
                // Save the changes. 
                newsItem.ApprovalWorkflowState = "Published";
                newsManager.Lifecycle.Publish(newsItem);
                newsManager.SaveChanges();
            }
        }
      
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            CreateStaffNoticeBoardItem(txtNewsTitle.Text, txtNewsSummary.Text, txtNewsContent.Text);
            pnlClassifieds.Visible = false;
            pnlClassifiedsConfirm.Visible = true;
        }
    }
11 posts, 0 answered