Extending the SocialCommentControl

April 6 2011 188 comments

SocialCommentControl is the control, which enables commenting on a page. You can use social commenting feature with the Note Board web part (Social Collaboration > Note Board) by adding the web part onto your page. You would have to have User Profile Service Application provisioned to enable social comments. Comments are stored in the Social DB (SocialComments table) of your Service Application.

What we did recently was that we extended the out-of-box SocialCommentControl to be included in a custom page layout with a custom content type. The content type contains a boolean field to indicate, if commenting would be enabled on the published page. Another thing is that we can catch the events when a new comment is added, deleted or updated and build our own custom functionality, if needed, to handle those events.

The first thing was to take a look at the SocialCommentControl class with reflector in Microsoft.SharePoint.Portal assembly. The control inherits from System.Web.UI.WebControls.WebControl and implements the System.Web.UI.WebControls.ICallbackEventHandler. The event handling for comments takes place in RaiseCallBackEvent and the code can be dug out with reflector.

So what if there was a case where the editor wants to specify if commenting is allowed on a published page and wants to get the added comments via email if commenting would be enabled to the page. The scenario is not from our business case and is purely hypothetical but as a demo the case will do just fine.

Below is a quick demonstration of how to handle enabling commenting on a page and get the editor of the page to receive email every time a comment is either added or edited. The sample contains also a workaround for the inconvenient behavior of the out-of-box SocialCommentControl which breaks the DOM and makes web designers mumble when they come across the fact that one div is unclosed.

public class SocialComments : SocialCommentControl, ICallbackEventHandler
{
    public SocialComments()
    {
        Load += SocialComments_Load;
    }
       
    protected void SocialComments_Load(object sender, EventArgs e)
    {
        var item = SPContext.Current.ListItem;
        // check if the current page has commenting allowed
        var allowComments = (item["AllowComments"] != null &&
            (bool)(item["AllowComments"])) ? true : false;
        if (!allowComments)
        {
            Visible = false;
            return;
        }
    }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        // the DOM is a terrible thing to break
        // http://www.sharepointblues.com/2010/09/28/fix-disabled-page-scrolling-on-navigation-settings/
        Controls.Add(new LiteralControl("</div>"));
    }

    public string GetCallbackResult()
    {
        return base.GetCallbackResult();
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        base.RaiseCallbackEvent(eventArgument);

        try
        {
            var item = SPContext.Current.ListItem;
            var page = PublishingPage.GetPublishingPage(item);
            var editorEmail = page.CreatedBy.Email;
            var url = SPContext.Current.Web.Url + "/" + item.Url;
            var currentUser = SPContext.Current.Web.CurrentUser.Name;

            var document = new XmlDocument();
            document.LoadXml(eventArgument);
            var documentElement = document.DocumentElement;

            /*
            eventArgument when added:
            <Item  type='Add'>
                <Title>News</Title>
                <RTEContents>This is a new comment</RTEContents>
            </Item>
            */

            /*
            eventArgument when edited
            <Item type='Edit'
            SequenceId='0'
            CommentId='144'
            CurrentPage='1' >
            <RTEContents>This is an&amp;#160;edited comment</RTEContents>
            </Item>
            */

            if (documentElement != null)
            {
                var event = documentElement.GetAttribute("type");
                if (event != "Get")
                {
                    if (event == "Add" || event == "Edit")
                    {
                        var contentElement =
                        (XmlElement)documentElement.
                        SelectSingleNode("./RTEContents");
                        var content =
                        SPHttpUtility.NoEncode(contentElement.
                        InnerText);
                        var subject =
                        string.Format("Comment event '{0}' at {1}",
                        event, DateTime.Now);
                        var message =
                        string.Format("Content:
                        {0}<br/><br/>By {1}<br/><br/>Url: {2}"
,
                        content, currentUser, url);
                        SPUtility.SendEmail(SPContext.Current.Web, true,
                            false, editorEmail, subject, message);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            // log the exception
        }
    }
}

Below is the email the editor would get when a new comment is added to the page where commenting is enabled and the custom extension of the SocialCommentControl is included.

Popularity: 13% [?]

188 comments to “Extending the SocialCommentControl”

  1. Mckenzie says:

    Please let me know if you’re looking for a article author for your site.

    You have some really great posts and I think I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some content
    for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested.
    Regards!

  2. Link exchange is nothing else however it is simply placing the other person’s webpage link on your page at appropriate place
    and other person will also do similar for you.

  3. Hey there, I think your website might be having browser compatibility issues.
    When I look at your website in Safari, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to
    give you a quick heads up! Other then that, excellent blog!

  4. お肌が弱くて化粧水をつけるとお肌が赤くなってしまう方。敏感肌でお化粧もできない。敏感用のものを使ってもヒリヒリして痒くなってしまって、自分に合うものがどうしても見つからない人はオージュンヌという化粧水を試してみるといいかもしれません。もちろん香料などの不要なものは一切入っていないですから安心して使えます。アトピーでお化粧ができなかったという人でも、お肌の状態が良くなったケースがあります。ヒリヒリして赤みが出てしまったり、保湿タイプを使うと逆にニキビができてしまったりという方に向いています。

  5. webpage says:

    I notice there is certainly lots of spam on this blog. Do you need help cleaning them up? I might help between courses!

  6. Grace says:

    I die ganze Zeit mailte diese weblog Post-Seite, um allle meine Freunde Mitarbeiter, aaus
    dem Grund,, wenn es gerne lesen danach meiner Freunde auch.

  7. N級品 says:

    2018激安通販専門店
    ロレックス、ブルガリ、フランク ミュラー、
    オーデマ ピゲ、ブライトリング、グッチ、エルメス、パネライ、
    当店のスーパーコピー商品は他店よりも質が高く、
    金額も安くなっております。
    ご購入する度、ご安心とご満足の届けることを旨にしております

  8. erotic says:

    Yoou actually make it seem so easy along with your presentation however I in finding this topic to be realoy something tjat I think I’d by no means understand.
    It seems too compllicated and very huge for me. I’m taking a look forward in your next put up, I will try too get
    the hold of it!

    Alsso visit my blog … erotic

  9. If you do what you always did, you will get what you always got. ~Anonymous

  10. zobacz tutaj says:

    Aw, this was an incredibly good post. Taking the time and actual effort to produce a great article… but what can I say… I
    procrastinate a lot and don’t seem to get nearly
    anything done.

  11. Aw, thiѕ was ɑ really ցood post. Finding the time and actual effort to generate a νery gooԀ article… bᥙt whɑt саn I
    ѕay… I hesitate а lot and never seem tⲟ get anythіng done.

  12. zobacz tutaj says:

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your website?

    My blog is in the exact same niche as yours and my users would genuinely
    benefit from a lot of the information you provide here. Please let me know
    if this alright with you. Many thanks!

  13. Hi there, everything is going well here and ofcourse every one is sharing data,
    that’s in fact fine, keep up writing.

  14. It’s genuinely very difficult in this busy life to listen news on Television, so I only use internet for that purpose,
    and obtain the latest information.

  15. I do not even know how I stopped up right here, but I believed this publish used to be good.
    I don’t understand who you’re however certainly you are going to a
    famous blogger in case you aren’t already. Cheers!

  16. proboards98 says:

    If you are going for finest contents like me, just go
    to see this web site everyday for the reason that it offers feature contents, thanks

  17. see this says:

    Hi colleagues, how is the whole thing, and what you would like to say about this article, in my view its in fact awesome for me.

  18. wonderful issues altogether, you just gained a new reader.
    What would you suggest about your post that you simply
    made a few days in the past? Any positive?

  19. Its not my first timе to pay a quick visit this web ρage, i ɑm
    browsing thiѕ web рage dailly ɑnd ɡet nice facts from
    heгe аll the tіme.

  20. Вау, эту статью предложила поклонникам страницы моя сестра.
    Ее действительно интересует эта тема,
    поспешу передать ей ваши комменты.

  21. Ola says:

    It’s an remarkable paragraph f᧐r aⅼl thе web uѕers; they wiⅼl take
    advantage fгom it I ɑm sure.

    mү blog post terjebak kerja judi online (Ola)

  22. Hello! Dօ you ҝnow if they make any plugins tо protect against
    hackers? Ι’m kinda paranoid aЬоut losing еverything Ӏ’ve worked harⅾ on. Any tips?

  23. Привет, я думаю, что это отличный блог.
    Я перехожу сюда снова. Надо сохранить этот адрес
    в “Избранное”. Деньги и свобода лучший способ изменить жизнь, – может вы разбогатеете и
    продолжите обучать окружающих

  24. Everything iѕ vеry oρen witһ a cllear explanation of the challenges.

    Ӏt ᴡas ԁefinitely informative. Үоur site is vеry useful.
    Ƭhanks foг sharing!

    My site https://idcmcpoker.org

  25. Вау, эту статью предложила администрации
    страницы моя младшая сестра.
    Ее действительно интересует данная
    тема, думаю передать ей ваши отзывы.

  26. If you are alone and looking for nice ladies ready for free sexy chat all night long you must to visit transe münchen and enjoy!

  27. Nice answer back in return of this matter with genuine arguments and telling everything concerning that.

  28. aboutme says:

    I don’t even know the way I ended up here, but I assumed this put up
    was great. I do not recognise who you are however certainly you’re going to a famous blogger
    in case you are not already. Cheers!

  29. I got this website from my pal who shared
    with me about this site and now this time I am visiting this
    site and reading very informative articles or reviews here.

  30. Find hot girls from France for the hotest sexy contacts only on our web platform Sexe Provence Alpes Cote Azur

  31. internet says:

    I think this is among the so much vital info for me.
    And i’m happy studying your article. But should commentary on few common things, The site taste is great, the articles is in point of fact excellent :
    D. Excellent job, cheers

  32. transexuel sex le havre is web place created for finding casual contacts with fine ladies in France

  33. Green says:

    I do agree with all the ideas you’ve presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for beginners. Could you please extend them a little from next time? Thanks for the post.

  34. I found your blog web site on google and verify a number of of your early posts. Continue to maintain up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Looking for forward to studying more from you afterward!…

  35. Angel17 says:

    I am happy to read this blog post. This is helpful. concrete driveway cary nc

  36. כאמור, הדרך הטובה ביותר לאיתור נערות ליווי בתל והמרכז, עוברת
    באינטרנט ובראש ובראשונה באתרי אינטרנט שהמהווים כפלטפורמות
    ייעודיות למטרה.

  37. طراحی هودی به گونه ای است که می توان آن را با هر سبک
    پوشش و استایلی ست و هماهنگ کرد.
    یکی از دلایل مهمی که لباس هودی پسرانه تا این حد
    مورد محبوبیت قرار گرفته کیفیت جنس و تنوع طرح در آن است.

    بنابراین خرید سوییشرت و هودی دخترانه یک
    خرید ترندی خواهد بود.

  38. Vivian says:

    You are an absolute inspiration, Water Well Services Two Hills, AB

Leave a Reply