Pages

Search This Blog

Thursday, December 29, 2011

SharePoint - Programmatically creating comments of a blog post in blog site

Last week, one guy faced a problem when he was trying to create "Blog Post Comments" programmatically. He was not able to increase the Comments counts (below blog post).

I have done some R&D on that and found that any blog site in SharePoint there are two main lists: 
1. Posts and 2. Comments 

We need to update the Comments list's "Post Title" column with the Posts list's "Title" column lookup. This will automatically update the comments count.

Note: Comments lists's "Post Title" field is hidden field.

I am providing the sample code for the same:

//Update Blog Post Comments Programatically
using (SPSite site = new SPSite("http://br-pc-275:3670/blog/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList objPostList = web.Lists["Posts"];
        SPListItem objItem = objPostList.GetItemById(1);
        SPList objCommentsList = web.Lists["Comments"];
        SPListItem objNewComment = objCommentsList.Items.Add();
        objNewComment["Title"] = "New Comment 1";
        //Id of blogPost + ";#" + Title of blogPost
        objNewComment["Post Title"] = "1" + ";#" + Convert.ToString(objItem["Title"]);
        objNewComment.Update();
    }
}

Thanks

Wednesday, December 28, 2011

Show apostrophe in Javascript

In many scenarios, we need to call some Javascript method in our applications. Most common of which can be javascript:alert('message'). We ususlly pass out string in javascript alert, but if the string contains ( ' ) character, the method fails and throw an exception as:

alert('This ' will terminate the string');





One way to resolve this is to replace "'" with ' like:

alert('string works well with ' used here');

However you need to ensure that you are not using this on Older versions of Internet Explorer since ' is not supported in earlier versions of HTML. For behaving correctly in older versions also, you can use: '

alert('This works in all the browsers for the constant '');

If you are working on .Net Framework 4.0, then you can also make use of the folllowing property to create a javascript supported script as:

HTTPUtility.JavascriptEncode("the constant ' is supported here")

Monday, December 26, 2011

Accessing SharePoint List using REST - WCF based Data Service

In this post I will tell you how a SharePoint List can be accessed through the REST (Representational State Transfer) WCF based Data service. In this example I have a list name “LearningList, which is accessed and shown in a Data Grid. Using this I have also shown how to update the same. To have the source code to the example Click here.

Before you can proceed further with the example verify that the WCF Data services are installed in your environment, as it does not comes with the SharePoint installation. To verify the install enter the following URL to your browser: http://<server name>/_vti_bin/ListData.svc

Otherwise to download it Click here.

CODE SNIPPET
  • Create a new Custom List and name it “LearningList”.
  •  Create the fields as shown in the image

  • Create a new Visual Studio 2010 --> Visual C# --> Windows  --> Windows Forms Application. And provide the name for the project (for example: RestSharepointList).

  • Now Right click the References and click on the Add Service Reference. Enter the following URL:  http://<server name>/_vti_bin/ListData.svc and click Go.  Visual Studio will search and return the number of lists, which will include the example list.

  • Provide the Namespace for the service (for example: RestListService )
  • Add the Lists Data Grid to the Designer by clicking on the Data -->Show data Sources -->LearningList (drag this to the designer which will be added as the Data Grid).


  • Re-Design the form as shown in the image.


  • On the Form_Load add the code 


  • · I have added three buttons 
    •   Add: This is to add the new Item in the List.

    • Refresh: This is to refresh the list so as to see the current added item in the List.

    • Clear: This is to clear the textboxes.
  • Full Code from the code behind
namespace RestSharePointList
{
    public partial class Form1 : Form
    {
        //Create a Proxy of the service
        RESTListService.LearningDataContext objContext = new LearningDataContext(new Uri("http://br-pc-350:2789/_vti_bin/ListData.svc"));

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //provide the credentials for the proxy to access the SharePoint List
            objContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            //Create a Linq Query to get the data from the list using the proxy
            var listData = from p in objContext.LearningList
                           select p;
            //You can also filter the data from the List by modifing the LINQ Query

            //Bind the DataGrid with the data retreived from the List
            this.learningListBindingSource.DataSource = listData;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //Emptying the Text Boxes
            txtAuthor.Text = "";
            txtInStock.Text = "";
            txtPrice.Text = "";
            txtTitle.Text = "";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //create a List object and assign the values
            LearningListItem objItem = new LearningListItem();
            objItem.Author = txtAuthor.Text;
            objItem.Price = txtPrice.Text;
            objItem.InStock = txtInStock.Text;
            objItem.Title = txtTitle.Text;

            try
            {
                //Add the Items to the List
                objContext.AddToLearningList(objItem);
                objContext.SaveChanges();
                MessageBox.Show("Item added Successfully");
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error Occured: " + ex.Message);
            }

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

            //provide the credentials for the proxy to access the SharePoint List
            objContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            //Create a Linq Query to get the data from the list using the proxy
            var listData = from p in objContext.LearningList
                           select p;
            //You can also filter the data from the List by modifing the LINQ Query

            //Bind the DataGrid with the data retreived from the List
            this.learningListBindingSource.DataSource = listData;
        }
    }
}

  •  Now press F5 and the output will look something like this.
Happy Coding..!!!