Ads

Showing posts with label Alert & Notification. Show all posts
Showing posts with label Alert & Notification. Show all posts

Thursday, 4 July 2013

Default Sharepoint Notifications setting from UI



1.JPG

Assuming that your 'Notifications' list has the following items in it.

2.JPG

Creating New Notifications

Power users or site collection admins can use this simple custom application page to create new notifications and assign to users or SP groups.

6.JPG
3.JPG

Mark As Read functionality

Also, when your users read a message and close them by clicking little 'x', that message is 'marked as read' and won't be displayed next time user visits the page.

4.JPG

5.JPG

How to use Notifications in SharePoint 2010

In SharePoint 2010, Notifications is another way to display information/warnings without distracting user. It'll be shown in top right below Topbar and Ribbon. Just like Status bar, No Server side code or manual setup required to use Notifications. The required functions are bundled in SP.UI.Notify class that defined in SP.Js/SP.Debug.Js and it's included in SharePoint master page. So no manual include of Js is required.

Well, Status bar is used to display content and to hide developer has to invoke RemoveStatus or RemoveStatusAll Method, whereas Notifications by default getting hide after few seconds. It's possible to make notifications Sticky(stay until closed by code).

SP.UI.Status Notify
The SP.UI.Notify class has 2 functions. They are
  1. SP.UI.Notify.addNotification(strHTMLContent, boolIsSticky) This function used to display specified content in Notification area. The parameters are self explanatory. boolIsSticky parameter specifies whether this content should be shown as sticky(true) or hide after few seconds(false). It's possible to show multiple Notifications at a time and they getting aligned themselves.
  2. SP.UI.Notify.removeNotification(strNotifyID) This function hides the Notification that passed as parameter.
Sample Code
<
Script type="text/javascript">
var
strNotificationID, strStickyNotificationID;

function showNofication()
{
  strNotificationID = SP.UI.Notify.addNotification(
"Quick Info : <font color='#AA0000'>Registration in Progress..</font> <img src='/_Layouts/Images/kpiprogressbar.gif' align='absmiddle'> ", false);
  

strStickyNotificationID = SP.UI.Notify.addNotification("Sticky Notes : <font color='#AA0000'>Welcome to My World.</font> <img src='/_Layouts/Images/lg_ICPINNED.gif' align='absmiddle'> ", true);
}

function removeNofication()
{
 
if (strStickyNotificationID != null)
    SP.UI.Notify.removeNotification(strStickyNotificationID);
}
</Script>

<
div class="ms-toolpanefooter">
  <
input type="button" onclick="Javascript:showNofication();" value="Show Nofitication" class="UserButton" />
 
<input type="button" onclick="Javascript:removeNofication()" value="Remove Nofitication" class="UserButton" />
</div>
Notifications

Wednesday, 3 April 2013

C# code to customize Sharepoint alert emails using IAlertNotifyHandler interface

We can make use of the IAlertNotifyHandler interface to intercept the email and modify it.


We can create our own class that inherits from the IAlertNotifyHandler interface and uses the OnNotification method. This will allow you to intercept the outgoing alert emails and modify them. We can access most of the properties for the alert and with some xml parsing and SharePoint object model code, we can extract all the information we need to build up the email. We can then construct the HTML stub to display the email based on your requirements and send the email out using SharePoint’s SendMail functionality.


Steps:
I have included the sample code below along with the steps to set up the scenario. I have formatted the output of my code to resemble the default alert template emails as close as possible, you can customize it further to suit your needs.

1      Create a class project that inhertits from the IAlertNotifyHandler interface. Include the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces in the project.
                    This is the code for the class:

    public class Class1:IAlertNotifyHandler

    {
        #region IAlertNotifyHandler Members
        public bool OnNotification(SPAlertHandlerParams ahp)
        {
            try
            {
                SPSite site = new SPSite(ahp.siteUrl+ahp.webUrl);
                SPWeb web = site.OpenWeb();
                SPList list=web.Lists[ahp.a.ListID];
                SPListItem item = list.GetItemById(ahp.eventData[0].itemId) ;
               
                string FullPath=HttpUtility.UrlPathEncode(ahp.siteUrl+"/"+ahp.webUrl+"/"+list.Title+"/"+item.Name);
                string ListPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl + "/" + list.Title);
                string webPath=HttpUtility.UrlPathEncode(ahp.siteUrl+"/"+ahp.webUrl);
                
                string build = "";
                 if (ahp.eventData[0].eventType==1)
                 eventType="Added";
                 else if(ahp.eventData[0].eventType==2)
                 eventType="Changed";
                 else if(ahp.eventData[0].eventType==3)
                 eventType="Deleted";

                build = "<style type=\"text/css\">.style1 {              font-size: small; border: 1px solid #000000;"+
                    "background-color: #DEE7FE;}.style2 {               border: 1px solid #000000;}</style></head>"+                    
                    "<p><strong>"+ item.Name.ToString() +"</strong> has been "+eventType +"</p>"+
                    "<table style=\"width: 100%\" class=\"style2\"><tr><td style=\"width: 25%\" class=\"style1\">"+
                    "<a href="+ webPath +"/_layouts/mysubs.aspx>Modify my Settings</a></td>"+
                    "<td style=\"width: 25%\" class=\"style1\"> <a href="+ FullPath +">View "+item.Name+"</a></td>"+
                    "<td style=\"width: 25%\" class=\"style1\"><a href=" + ListPath + ">View " + list.Title + "</a></td>" +
                    "        </tr></table>";
                string subject=list.Title.ToString() ;              
                SPUtility.SendEmail(web,true , false, ahp.headers["to"].ToString(), subject,build);
                return false;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }
        #endregion
    }

2.            GAC the dll. 
3.            Make a copy of the alertTemplates.xml file found at this location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\XML. Always work with a copy of AlertTemplates.xml, not the original.
4.            Call this new file CustomAlertTemplates and save the file. Edit the file and search for the keyword properties:
Include these additional lines into the properties block:

          <NotificationHandlerAssembly>AlertHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d59ecf2a3bd66904</NotificationHandlerAssembly>
          <NotificationHandlerClassName>AlertHandler.Class1</NotificationHandlerClassName>
    <NotificationHandlerProperties></NotificationHandlerProperties>

The entire stub should look like this now:
        <Properties>
            <ImmediateNotificationExcludedFields>ID;Author;Editor;Modified_x0020_By;Created_x0020_By;_UIVersionString;ContentType;TaskGroup;IsCurrent;Attachments;NumComments;</ImmediateNotificationExcludedFields>
            <DigestNotificationExcludedFields>ID;Author;Editor;Modified_x0020_By;Created_x0020_By;_UIVersionString;ContentType;TaskGroup;IsCurrent;Attachments;NumComments;</DigestNotificationExcludedFields>
            <NotificationHandlerAssembly>AlertHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d59ecf2a3bd66904</NotificationHandlerAssembly>
                <NotificationHandlerClassName>AlertHandler.Class1</NotificationHandlerClassName>
                <NotificationHandlerProperties></NotificationHandlerProperties>
  </Properties>

Include this xml stub in each alert template section you want in the alert template file.

5.            Run this command from C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN:  stsadm -o updatealerttemplates -filename "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\XML\customalerttemplates.xml" -url <your sharepoint site url>
6.            Run this command:  stsadm -o setproperty -pn job-immediate-alerts -pv "every 1 minutes" so that you can see the log file come back in one minute. Be sure to set the time back after testing.
7.            Make sure you have SharePoint already configured for outgoing emails.
8.            Make sure that you have alerts for the document library turned on if you are testing with the document library. 
9.            Run this command from the command prompt: iisreset
10.         Run this command from the command prompt: services.msc
11.         From the services window, restart the Windows SharePoint Services Timer.

Your custom email alert handler should be configured at this point. Create a new alert and you should get the updated custom email.


Saturday, 23 March 2013

C# code to send Email in Sharepoint using SPUtility.SendEmail using HTML tags.

SPUtility.SendEmail has 4 overloaded method in Sharepoint for sending email to any email address. We will discuss mainly 2 methods which can handle every type of html email body in Sharepoint.
1) SPUtility.SendEmail(SPWeb web, bool fAppendHtmlTag, bool fHtmlEncode, string to, string subject,string htmlEmailBody)
Most of the time we may need to write a html email body having different styles for text and fonts.Then we can go for this method without much overhead.We can write our email body using html tags but to display our actual email content without html tags we have to take care of one important thing otherwise we will get the email with html tags embedded.
We will have to pass 'false' for 'fHtmlEncode' and 'true' for 'fAppendHtmlTag' as boolean value.
Limitations: We cannot send email to one than one person at a time with this method.
2) SPUtility.SendEmail(SPWeb web, StringDictionary messageHeaders, string messageBody)
This overloaded method has more functionality than the one we discussed above.The second parameter includes all the details about the sender,receiver, subject, cc, bcc, and content-type which we will have to add by making object of StringDictionary class and including System.Collections.Specialized in the beginning.We can send email to any number of people at a time.
For example:

//send mail to the member               
StringDictionary headers = new StringDictionary();
headers.Add("to", currCtxt.Web.CurrentUser.Email);
headers.Add("cc", "xyz@abc.com");
headers.Add("bcc", "");
headers.Add("from", "email@add.com");
headers.Add("subject", "Email Subject");
headers.Add("content-type", "text/html");
string bodyText = "Hello how are you?";
SPUtility.SendEmail(currCtxt.Web, headers, bodyText.ToString());
NOTE:  One important thing needs to be taken care of in the 'from' we can't provide email address randomly because that will result in no mail to our inbox.The reason behind this is that SharePoint has its setting for SPUtility.SendEmail() method which by default picks the 'From address' from Central administartion-> Operations-> Outgoing E-Mail Settings. Its better not to experiment with 'From addres' without knowledge.Leaving the above reason there will be no problem in sending email to any email address of any domain.

C# code to create alerts in document library & List programmatically

SharePoint gives some inbuilt functionality to create and manage alerts in lists & Libraries by using alert me option. It can also be done by code as shown below:
using (SPSite oSite = new SPSite("http://servername"))
{
  using (SPWeb oWeb = oSite.OpenWeb())
  {
    SPUser oUser = oWeb.SiteUsers["domain name
\\username"];
    SPAlert oListAlert = oUser.Alerts.Add(); 
    //Define the type of object to which alert is applied
    oListAlert.AlertType = SPAlertType.List;  
    //Gets or sets the List or Document Library to which alert is applied
    oListAlert.List = oWeb.Lists["List_Name"];
    //Define the Event type to which alert is applied
    oListAlert.EventType = SPEventType.All;
    //Set the time interval for sending alert.
    oListAlert.AlertFrequency = SPAlertFrequency.Immediate; 
    //Passing true to Update method will send alert confirmation mail 
    oListAlert.Update(false); 
    //Dispose unused objects                 
    oListAlert = null;
    oUser = null;
  }
}

Ads