SocialCommentWebPart is one of the new features of Sharepoint 2010 which allows users add comments to the pages where this web part is added. This web part makes Sharepoint site more social and increases users communication level. One of the common requirement with this type of functionality is that not all users should be able to leave their comments on site. For example, you can decide that only registered users should be able to leave comments (in case of self-service system), or you can use membership in particular groups in order to grant possibility to leave comments for users. In both cases you will need to make SocialCommentWebPart read only (i.e. allow users only read comments, not post them) dynamically in run time. There is a property SocialCommentWebPart.WebPartPropertyAllowNewComment, but as all other properties it is assumed to be configured once by content producer (or another user with permissions to edit web parts). This is not our goal. Our goal is to allow some users to post comments, while other users should not have this possibility.
If you will check SocialCommentWebPart in reflector you will notice that all functionality is implemented in separate user control SocialCommentControl. It has property AllowNewComment and SocialCommentWebPart sets this property when add SocialCommentControl into controls collection. This property is what we need. But unfortunately it is internal, so we can’t just set it up in our code. Reflection will help us here. Suppose that we put web part on page layout directly (i.e. it is not added via UI on publishing page, but in last case code will remain the same – the only thing you will need to solve is to retrieve web part Id):
In order to make SocialCommentWebPart read only check the following code which we can add directly into page layout:
Function yourOwnLogic() here is any function which you can use in order to determine should current user have possibility to post comments or not (as I said above you can use membership in Sharepoint groups for example). Here we use 2 external components: ControlFinder and ReflectionHelper. They are not complicated. ControlFinder searches for control of specified generic type in controls collection recursively:
ReflectionHelper is a helper class which can be used if you need to play with internal details of Sharepoint (I understand that it can be necessary in some cases, but don’t make it too much as it non supported way to work with Sharepoint):
After this SocialCommentWebPart will be read only for users which don’t have necessary permissions, and will allow post comments for users which have such permissions.