SharePoint Developer Support Team Blog

The Official blog of the SharePoint Developer Support Team

How to subscribe for an alert for a “Post” in discussion board programmatically

How to subscribe for an alert for a “Post” in discussion board programmatically

  • Comments 16
  • Likes

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:

  1. Subscription alert: Whenever a user subscribes for an item/document/list, the user will get an email stating “you have subscribed for an alert…”.
  2. 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! Smile

Comments
  • Wonderful article to understand the alert basics for dicussion board. Thank you Jaishree for posting this.

  • Nice article.

  • For this requirement do i need to create a custom column as "ItemfullUrl" with value discussion folder item relative url?

    Thabks

    Srikanth

  • I like your use of discussion board for sharing work for feedback.

    www.investorshangout.com

  • 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.com

  • 24 Hours Loan Offer At 2%


    Do you need an urgent loan as fast as 24 Hours? if Yes Etihad Loans Limited Offer all kinds of loan to individuals and companies in need of loan at low interest rate of 2% . We offer loan ranging from (5,000 $,€ & £ ) to (100,000,000 $,€ & £ )if you need a loan today Contact us Via Email { etihadfirm@outlook.com } for a loan:

    YOUR DETAILS REQUIRED:

    Name
    Sex:
    Age:
    Country:
    Occupation:
    Monthly income:
    Loan Amount:
    Duration:
    Purpose of Loan.
    Phone Number:

    Regards

    Mr.Etihad
    M/D
    Etihad Loans Limited

    Make Sure you send your Reply to : etihadfirm@outlook.com

  • 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.in

  • In general we offer Personal Loans,home loans,car loans, hotel loans,commercial loans,construction loans,start working capital loans,business loans and bad credit loans, e.t.c,at lower interest rate.We offer the right solution to your financial needs. We stand apart from other lenders because we believe in customer service and we stay with you until you get the results you want.


    Please, do provide us with the Following information if interested.
    1) Full Name:
    2) Gender:
    3) Loan Amount Needed:
    4) Loan Duration:
    5) Country:
    6) Home Address:
    7) Mobile Number:
    8)Monthly Income:
    9)Occupation:
    )Which site did you here about us:
    Thanks and Best Regards.
    CONTACT US: ( sbifinancelive@hotmail.com )

  • 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.com



  • Hello, Do you need a loan from The most trusted and reliable company
    in the world? if yes then contact us now for we offer loan to all
    categories of seekers be it companies or for staff usage. We offer
    loan at 3% interest rate, Contact us via email:
    mohanmendserves@gmail.com

    (1) Full Name
    (2) Full Address
    (3) Country
    (4) Age
    (5) Occupation
    (6) Tell phone number
    (7) Sex:
    (8) Loan Amount needed:
    (9) Loan Duration

    Email us at: mohanmendserves@gmail.com


  • WE OFFER LOAN AT 3% INTEREST RATE


    Do you need an urgent loan we offer worldwide loan to who in need of loan the business opportunity you having being looking for is here again. email us now at: mrwilliam751@gmail.com
    LOAN APPLICATION FORM
    1) Full Name:
    2) Gender:
    3) Loan Amount Needed:.
    4) Loan Duration:
    5) Country:
    6) Home Address:
    7) Mobile Number:
    8)Monthly Income:
    9)Occupation:
    )Which did you here about us.

    Best Regards.

  • Hello
    Do you need a comfortable loan to your satisfaction?
    We offer affordable loan @ 3% interest rate available for local
    and international borrowers.
    We are certified,trustworthy,reliable,efficient, fast and dynamic
    and we co-operate with our costumers.
    We give out long term loan from two to fifty years maximum
    contact us on ( Adamfred23@GMAIL.COM )
    LOAN APPLICATION FORM
    NAME:................................
    GENDER:.........................
    MARITAL STATUS:...........................
    CONTACT ADDRESS:................................
    CITY/ZIP:.................
    COUNTRY:.................
    AGE:............
    AMOUNT REQUIRED AS LOAN:..............
    LOAN DURATION:...............
    MONTHLY INCOME:.............
    OCCUPATION:............
    PURPOSE OF LOAN:...........
    VALID PHONE NUMBER:.............
    FAX:................
    COMPLETE THIS FORM AND FORWARD IT BACK TO
    Adamfred23@gmail.COM
    Adamfred2@outlook.com

  • Good Day To The General Public!
    I am Mr Wilson Elliott from Los Angele’s in United State of America, am testifying of a loan lender(Mr Patrick Munro) that have human feeling and God fearing heart, who i meet in yahoo answer few months.I was looking for a Private Loan company where i can get a consolidation loan of about $15,000.00usdollars,so i saw someone post on Yahoo Answer testifying for about WEST AFRICA LOAN COMPANY LIMITED that give her a loan of about $25,000.00usdollars within 24 banking working hours. Then i contact the company because i don’t believe in testimony, so i just say let me try if the company can help out of my financial problem, Mr.Patrick Munro mail me and he said i should fill the form that was send to me that will enable them proceed on the loan immediately and i did and i follow all the process which they give me, so to my greatest surprise the loan was transfer to my bank account not less than 24 hour. I don’t know the kind of financial problem that you are having or you are have a dream of having your own house, this is the company that can make your dream come true email them today at( westafricaloancompanyltd@gmail.com ) and you will be happy as i am today
    Thanks,
    Mr Wilson Elliott

  • 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.com

  • 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.com

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment