How to subscribe for an alert for a “Post” in discussion board programmatically
This post is a contribution from Jaishree Thiyagarajan, an engineer with the SharePoint Developer Support team.
Let’s first talk about some basic facts about discussion board and alert terminologies.
Discussion Board
We all know about discussion board. Discussion board is where we can add “posts” and for every single post we can add “replies (comments)”. The discussion board is designed in such a way that all posts are stored as Folders and replies to the posts are stored as items within the folder.
In SharePoint, we can subscribe for alerts at the list/library levels and also at individual item levels.
Now that we know that “posts” are added as folder and “replies” are added as items to the folder in the discussion board , the first question that pops in our mind is “Which alert-type (SPAlertType) should I use?”
If I use SPAlertType.Item for a post then I would not get alert for newly added replies. If I use SPAlertType.List then I may end up receiving alerts for items that I didn’t subscribe to.
If you are looking for a solution to receive the alerts for a “post you are subscribed” and “any replies added to the subscribed post”, then you are at the right blog post.
Now, let’s check out the alert terminology for better understanding.
Alerts
In SharePoint, there are two types of alerts:
- Subscription alert: Whenever a user subscribes for an item/document/list, the user will get an email stating “you have subscribed for an alert…”.
- Changed alert (commonly referred to as alert): Based on the subscription option chosen (added, modified etc.,) alert email will be triggered.
As we can see, any site administrator can subscribe any user for an alert. These subscription alerts are NOT security trimmed. But the changed alerts are security trimmed. The alert emails will only be triggered if the subscribed user has sufficient permissions for the item (for item level alerts) or lists (for list level alerts).
Now, if your users complain that they are not receiving the changed alerts, your first action should be to check whether they have sufficient permissions for subscribed item or not.
Ok – we’ve learnt some details on discussion board and alerts. Now, let’s check out how to subscribe for a Post in discussion board programmatically.
Subscribe for a “Post” in discussion board programmatically
Posts are added as items (i.e., in UI when you open a discussion board, you can see all the posts listed as items; the folder structure mentioned above is the internal design) to a discussion board and so whenever we subscribe for a post, item level alerts would be added via UI. Assuming this, if we specify SPAlertType.Item when programmatically subscribing to an item in discussion board, alerts would not be sent out for replies to the post.
To circumvent this, if we set SPAlertType.List, alerts would be sent out for any new post to the discussion board, but the requirement is to receive alert emails for just a particular post and replies to that post.
The trick to achieve this requirement programmatically is to specify alert filter in the code.
SPList list = web.Lists["Team Discussion"];
SPListItem item = list.GetItemById(8);
SPUser user = web.AllUsers[@"mydomain\username"];
SPAlert alert = user.Alerts.Add();
alert.AlertType = SPAlertType.List;
alert.AlertTemplate = list.AlertTemplate;
alert.AlertFrequency = SPAlertFrequency.Immediate;
alert.EventType = SPEventType.All;
// Here, we filter the alert for the specific discussion, so only responses to that discussion get an alert
alert.Filter = string.Format("<Query><BeginsWith><FieldRef Name=\"ItemFullUrl\"/><Value type=\"string\">{0}</Value></BeginsWith></Query>", item.Url);
alert.List = list;
alert.Title = "Team Discussion: Sports";
The above code will work for discussion board present in the root site; but for sub-sites it won’t work.
After breaking my head for a long time and comparing programmatically added subscription with the out of the box subscription (in the ImmediateSubscription table in SharePoint content database, thanks to my colleague Selvakumar Ganapathi, escalation resource from SharePoint team), I finally figured out the value passed to “ItemFullUrl” should begin with a “/” (forward slash).
Here’s the complete and working code for subscribing an alert for a post in a discussion board
string url = "";
if (item.ParentList.ParentWebUrl == "/")
{
url = item.Url;
}
else
{
url = item.ParentList.ParentWebUrl + "/" + item.Url;
}
string itemFullUrl = url.StartsWith("/") ? url.Substring(1) : url;
string itemBeginswithFilter = itemFullUrl + "/";
string filter = string.Format("<Query><Or><Eq><FieldRef Name=\"ItemFullUrl\"/><Value type=\"string\">{0}</Value></Eq><BeginsWith><FieldRef Name=\"ItemFullUrl\"/><Value type=\"string\">{1}</Value></BeginsWith></Or></Query>", itemFullUrl, itemBeginswithFilter);
SPList list = web.Lists["Sports"];//list name
SPListItem item = list.GetItemById(1);//post ID
SPUser user = web.AllUsers["mydomain\\username"];//user
SPAlert alert = user.Alerts.Add();
alert.AlertType = SPAlertType.List;
alert.AlertTemplate = list.AlertTemplate;
alert.AlertFrequency = SPAlertFrequency.Immediate;
alert.EventType = SPEventType.Add;
alert.Filter = filter;
alert.Title = "Sports: Cricket"; //title
alert.List = list;
alert.Update();
The above code works for alerts subscribed to a discussion board post at the root as well as sub-sites.
Happy Coding!
Comments
Anonymous
January 01, 2003
Nice article.Anonymous
January 01, 2003
For this requirement do i need to create a custom column as "ItemfullUrl" with value discussion folder item relative url? Thabks SrikanthAnonymous
May 31, 2012
Wonderful article to understand the alert basics for dicussion board. Thank you Jaishree for posting this.Anonymous
October 03, 2013
I like your use of discussion board for sharing work for feedback. www.investorshangout.comAnonymous
March 01, 2015
A licensed Loan Lender, We offer Affordable Loan at 3% interest rate available for local and international borrowers, Are you seriously interested in getting a genuine Loan without stress? Do you need this Loan for business and to clear your bills? Then send us an email now for more details via: skycreditfaa@gmail.comAnonymous
April 29, 2015
The comment has been removedAnonymous
July 28, 2015
Do you need urgent cash
We have an easy way to get you extra money to spend or to settle your debts !
Need cash to pay off bills ?
Need cash to tide up for the month ?
Need cash urgently to settle your personal needs ?
Need ready cash to solve your financial status ?
But turned down by the bank, your relatives and friends?
We provide totally LEGAL ways to help you get more money to spend or
to settle your outstanding debts. CONTACT US: apply98@outlook.inAnonymous
July 28, 2015
The comment has been removedAnonymous
July 28, 2015
We offer financial service of any reason,finance to start business,paying of bills all kind of financial assistance unsecured loans without stress and quick to honest and reliable individuals and companies globally at 3% interest rate. Here is the solution to your financial problem, contact us today via email: smartersolution247@gmail.comAnonymous
September 08, 2015
The comment has been removedAnonymous
September 08, 2015
The comment has been removedAnonymous
September 13, 2015
The comment has been removedAnonymous
September 13, 2015
The comment has been removedAnonymous
September 28, 2015
Qué usted necesita un préstamo urgente?
Necesitabas préstamos de dinero entre los individuos para hacer frente a dificultades financieras para finalmente romper el estancamiento provocado por los bancos, por el rechazo de su solicitud de crédito .allant registra 500-1000000 € en un período de 5 a 30 años, dependiendo de la cantidad solicitada, con una tasa de interés anual fija de interés del 3% para todas las cantidades solicitadas. Usted está atascado, el banco prohibido y usted no tiene el beneficio de los bancos o que es mejor tener un proyecto y necesita financiación, mal crédito o necesitan dinero para pagar las cuentas, el dinero para invertir en el negocio. Así que si usted necesita préstamo de dinero no dude en ponerse en contacto con nosotros para conocer más acerca de mis condiciones muy favorables. Ninguna persona seria abstenerse aquí está mi correo electrónico: ludinarazica@gmail.comAnonymous
October 03, 2015
Wow! I can't still believe that I'm off depts and also set up a small business and even got my self a new truck. I can't thank you enough Dynamicloanoffer@gmail.com for the sweet and nice loan you gave me in the past and now I would make sure I tell the whole word about your generosity and kindness towards the needing. I will also refer lots of friends and family members to you and I know they are going to get the best service ever. If you need a loan with good interest rate and good and genieu service contact Mr. Eugene via Dynamicloanoffer@gmail.comAnonymous
December 02, 2015
The comment has been removedAnonymous
July 17, 2017
Hey there, You've done an excellent job. I'll definitely digg it and personally recommend to my friends. I'm sure they will be benefited from this web site.Anonymous
January 03, 2018
I'm really loving the theme/design of your web site.Do you ever run into any browser compatibility issues? A handful of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Firefox. Do you have any solutions to help fix this issue?Anonymous
January 06, 2018
I am actually thankful to the owner of this site who has shared this wonderful post at at this place.