Extending the SocialCommentControl

April 6 2011 182 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: 12% [?]

182 comments to “Extending the SocialCommentControl”

  1. Hi, jus wanted to say, I liked this blog post. It was funny.
    Keeep on posting!

  2. Благодарствую за материал. Впитал внятную мысль.
    Это означает, что нажиться уже завтра легко?

    Ошеломлен.

  3. I take pleasure in, lead to I discovered exactly what I used to be having a look for.
    You have ended my four day lengthy hunt! God Bless you man. Have
    a nice day. Bye

  4. Hello friends, how is all, and what you would like
    to say about this post, in my view its truly amazing for me.

  5. Normally I do not read article on blogs, but I wish
    to say that this write-up very compelled me to take a look at and do so!
    Your writing taste has been surprised me. Thnk you, very nice article.

  6. What’s up colleagues, how is all, and what you desire to
    say regarding this post, in my view its truly awesome for me.

  7. Tressa says:

    This content is really cool. I have bookmarked it. Do you allow guest post on your site ?
    I can provide hi quality posts for you. Let me know.

  8. 大田区・品川区・世田谷区・目黒区・港区で大切な父を家族で見送る。
    葬家の望みや故人の心情もきちんとヒアリングをします。私共は聞き取りを大切にしています。
    ポイントは一日葬の大きさ、葬儀のかたち、一日葬を執り行う斎場、希望です。
    そんなこと言ってたかな?と、あやふやな記憶に自信が持てません。そんな気持ちにさせたくない。だから間違いなく見積書を提出します。
    大田区・品川区・港区の格安葬儀社をサポート。
    臨海斎場も大きくなり斎場の大きさに合わせた白木祭壇を準備するなど、金額は益々と大きくなっていきます。
    葬儀を執り終えたとき、ありがとうございますと言ってくれるように。臨海斎場 家族葬
    臨海斎場で家族葬をやりたいとお考えのあなたへ。
    葬儀の催しは精神状態のけじめをつける意味もあります。
    こちらでは、ご家族にかわり、葬儀会社にご遺族の気分を伝え、しっかりと最後までお見送りのお手伝いをしています。
    そんな時は大田区・世田谷区で臨海斎場がとてもに良いです。
    葬儀式場の席順は原則としてはお通夜の場合と一緒です。臨海斎場 家族葬
    大切な父が天国に召された時は、感情にゆとりがありません。
    都営斎場では『心づけ』を手にすることが禁止されています。

  9. Asus ZenFone 3 Deluxe modelinde Snapdragon 823 modelinin kullanılacağı açıklanırken, yonga setinde yer alan 8GB LPDDR4 RAM de yüksek bir performansta çok iyi bir destek sağlıyor.

  10. Très pratique, vous n’aurez pas à vous soucier du rangement des guides de coupe.

  11. Graig says:

    Thanks on your marvelous posting! I certainly enjoyed reading it, you could be a great author.I will be sure to bookmark your blog
    and will eventually come back later in life. I want to encourage yourself to
    continue your great job, have a nice afternoon!

  12. Dvarma.com says:

    Hello there, You have done a fantastic job. I’ll definitely digg it and personally
    recommend to my friends. I’m sue they’ll be benefited from this site.

  13. Jonas Israel, CEO
    Jonas Israel has at least 20 years on practical experience within wooden world.
    Israel

    created McCorry within 1996. Prior to doing this, Jonas was in control of a Malaysian lumbermill
    and moulding.

  14. Jaxon says:

    Advancements provided by W88 incorporates retailer and welcome
    rewards for new individuals, whereas current individuals can profit
    by reload reward and as well as cash refunds.

  15. skup monet says:

    An impressive share! I have just forwarded this onto
    a co-worker who was conducting a little research on this.

    And he actually bought me dinner simply because I discovered it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending some time to talk about this
    subject here on your site.

  16. Some really great information, Gladiola I discovered this.

  17. 仕事人がアーリーリタイヤするには、毎月の暮らしをまかなうお金が必要です。働かずしてマネーを作り出すには資産を手に入れるしかありません。そのための選択肢の一つが投資です。お金のなる木である不動産という資産を買うことで、早期退職も可能となるのです。ただ不動産投資といってもマンション一棟の場合もあれば戸建て1軒の場合もあり、さまざまなスタイルがあります。またレバレッジをどのように活用するのかという点もあるので、自分にはどのような投資の仕方が合っているのかを見極めながら投資活動を進めることが大切です。

  18. Fastidious answer back in return of this matter with real arguments and telling everything about that.

  19. Thanks , I have just been looking for info about this subject for a long time and yours is the best I have found
    out till now. But, what concerning the conclusion? Are you certain in regards to the supply?

  20. evernote.com says:

    A prescription herpes treatment typically takes the type
    of antiviral medication that can be taken as a preventative measure, during
    an outbreak to decrease seriousness and speed up healing, or as
    a suppressive treatment (taken daily).

  21. ammoreslinol says:

    I was wondering if you ever thought of changing the
    structure of your website? Its very well written; I love what youve got to say.

    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two images.

    Maybe you could space it out better?

  22. whoah this weblog is great i love studying your articles.
    Keep up the good work! You recognize, lots of persons are looking round for this information,
    you can aid them greatly.

  23. This is really fascinating, You’re an overly professional blogger.
    I have joined your rss feed and stay up for in quest of extra of your
    wonderful post. Also, I’ve shared your website in my
    social networks

  24. Please let me know if you’re looking for a article author for your site.
    You have some really great posts and I believe I would be
    a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for
    a link back to mine. Please send me an email if interested.
    Kudos!

  25. Percy says:

    You really make it seem really easy together with your presentation but I to find this matter
    to be really one thing which I believe I might never
    understand. It seems too complex and extremely large for me.
    I am looking ahead on your subsequent post, I’ll try to get the grasp of it!

  26. It would only take about 25min just to get to the intersection in Downtown Evergreen which is from the Clear Creek County
    section of Evergreen in the Brook Forest Estates community.

    The housing boom is fueling a seller’s market
    that is pushing prices up to levels never seen before on a
    non-coastal city. The leader in the nation in a variety of different areas is Boston, Massachusetts.

  27. I am not positive the place you’re getting your information, but good
    topic. I must spend a while learning more or understanding more.
    Thank you for excellent info I used to be in search of this information for
    my mission.

  28. gayfuck says:

    I am not positive the place you are getting your info,
    however good topic. I needs to spend some time learning much more or figuring out more.
    Thank you for great info I was on the lookout for this
    information for my mission.

  29. Great blog you’ve got here.. It’s hard to find excellent writing
    like yours these days. I seriously appreciate individuals like you!
    Take care!!

  30. It’s awesome in favor of me to have a web page, which is valuable designed for my experience.
    thanks admin

  31. בניית אתרים בעולם העכשווי תפס חלק משמעותי בחיי היום יום שלנו,
    בעולם שכולו ONLINE המתרחב ומתעצם מעת לעת,
    אתר אינטרנט מודרני עם עיצוב ייחודי
    יהווה תפקיד חשוב בהצגת העסק שלך
    בפני הלקוחות.
    במיוחד עבור זאת, רן מחשבים מובילה את עולם בניית האתרים עם צוות מתכנתים וגרפיקאים מקצועיים בתחומם
    שילוו אתכם בכל התהליך החל מהיכרות ראשונית ועד להשלמת בניית האתר בצורה המושלמת עבורכם.

  32. Proceduralists about democracy tend to suppose democracy has the type of worth paintings and people have.

  33. Definitely believe that which you said. Your favorite justification seemed to be
    on the net the simplest thing to be aware of.

    I say to you, I certainly get annoyed while people consider
    worries that they plainly don’t know about. You managed
    to hit the nail upon the top as well as defined out the whole thing without having side-effects ,
    people can take a signal. Will likely be back to get more.
    Thanks

  34. If you are going for finest contents like me, simply pay a visit this site all
    the time because it provides quality contents, thanks

  35. Wow! At last I got a weblog from where I know how to actually obtain useful information concerning my study and knowledge.

  36. Marchesini has been offering throw wheels for supermoto wheels and all years in the last five years.

  37. As all kinds of activities that are skilled, blogging demands
    personal characteristics and unique qualified to achieve success.

  38. When I initially commented I appear to have clicked the -Notify me when new comments are added-
    checkbox and now every time a comment is added I recieve four emails
    with the same comment. There has to be an easy method you can remove me from that service?

    Cheers!

  39. Hello mates, good post and fastidious urging commented here, I am in fact enjoying by these.

  40. imgur.com says:

    Airbnb will permit Cubans to rent rooms or entire homes under Cuban regulations enabling little enterprise.

  41. Suzanna says:

    He concluded that the degree of biological disturbance and the resulting behavioral mal adaptations were directly associated to the difference in between the spectral structure of the artificial source which
    of natural light.

  42. This is very fascinating, You are an excessively
    skilled blogger. I have joined your rss feed
    and look forward to in search of extra of your magnificent post.
    Additionally, I’ve shared your site in my social networks

  43. Rosalind says:

    Fantastic site. A lot of helpful info here. I’m sending it to a few buddies ans additionally
    sharing in delicious. And obviously, thanks on your effort!

  44. クリバースを探して分かったこと。通信販売番組で紹介されている物品はすべてネットで入手できることではない。通販放送で通販放送終了から30分以内限定のサービスは、インターネット購入のケース、四六時中運用されている。

  45. Hiya very cool website!! Man .. Beautiful .. Superb .. I will bookmark your web site and take
    the feeds additionally? I’m glad to seek out numerous helpful info here in the post, we want develop extra
    strategies on this regard, thanks for sharing. . .
    . . .

  46. Rabatkoder says:

    Great post. I was checking constantly this blog and I’m impressed!
    Extremely useful info particularly the last part :
    ) I care for such information much. I was looking for
    this certain information for a long time. Thank
    you and best of luck.

  47. Juan says:

    It’s genuinely very complicated in this active life to listen news on TV,
    therefore I simply use world wide web for that reason, and get the most up-to-date information.

  48. Yanira says:

    Great items from you, man. I have remember your stuff prior to
    and you are simply extremely fantastic. I really like what
    you have got right here, really like what you are saying and the way in which
    wherein you say it. You make it enjoyable and
    you continue to care for to stay it wise. I can not wait to learn much more from you.

    This is really a wonderful website.

  49. It’s actually a cool and useful piece of info. I am glad that you
    shared this useful information with us. Please stay us up to date like this.
    Thanks for sharing.

  50. Vicki says:

    Of the assorted fitness trackers we have tried, this process has been the
    smmoothest and most trouble-free.

    Alsoo visit my page :: Vicki

Leave a Reply