Archive for the ‘SharePoint’ Category

Well, I’ve been asked to write a upcoming birthdays webpart and I tried to look up some examples on the net but wasn’t able to find anything interesting…

They wanted to have, for all users who have set their birthday in their SharePoint profile, a sorted list of people with their birthday coming up.

So, what I had to do was to check every user in the site collection to see if they filled in their birthday and then I had to sort them on their birthdate.

I will explain some pieces of the code and at the end of the post I will post the whole code in one piece so it’s easier to copy it.

So, first things first. Here’s the code of the ascx usercontrol:

<asp:Label runat="server" id="lblOutput" />

Yes! This is all.

Everyone should be able to access the SharePoint profiles without any exotic security errors so we’re going to use the try catch principle and the SPSecurity.RunWithElevatePrivileges method.

protected void Page_Load(object sender, EventArgs e)
{
try
{
lblOutput.Text = "";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSite = new SPSite(SPControl.GetContextSite(HttpContext.Current).Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{

SPSecurity.RunWithElevatedPrivileges is going to run the code under the ‘System Account’ account. Afterwards we are going to make use of our site collection (top level) which we fetch automatically by using the SPControl & HttpContext.
Then we open the SPWeb of our SPSite and we can use everything from our SharePoint site.
Now we need to get all our users from our site and use the SharePoint UserProfileManager object to access their data.

SPServiceContext serviceContext = SPServiceContext.GetContext(spSite);
UserProfileManager upm = new UserProfileManager(serviceContext);
SPUserCollection spUsers = spWeb.AllUsers;
List<DateTime> bdayDates = new List<DateTime>();
Hashtable bdayUsersByDate = new Hashtable();
int index = 0;
string[] keys = new string[spWeb.AllUsers.Count];

UserProfileManager is the object we’ll use to fetch our information. SPUserCollection contains all our site users and the other object are for later use in our webpart.
Now we need to check all our site users. Do they exist in the UserProfileManager (have they created their profile yet?) and if so, have they filled in their date of birth?
If all this is ok, we store the birthdates in our List bdayDates (if their birthday has already been this year, we add this year, otherwise we add this year – 1:


foreach (SPUser user in spWeb.AllUsers)
{
    string sAccount = user.LoginName;
    if (upm.UserExists(sAccount))
    {
        UserProfile u = upm.GetUserProfile(sAccount);
        if (u["SPS-Birthday"].Value != null)
        {
            string date = u["SPS-Birthday"].Value.ToString().Split(' ')[0];
            string day = date.Split('/')[1];
            string month = date.Split('/')[0];
            int year = DateTime.Now.Year + 1;
            if (int.Parse(month) > DateTime.Now.Month)
                year--;
            else
                if (int.Parse(month) == DateTime.Now.Month)
                     if (int.Parse(day) >= DateTime.Now.Day)
                         year--;
            DateTime bday = new DateTime(year, int.Parse(month), int.Parse(day));
            bdayDates.Add(bday);
            keys[index] = bday + "_" + index.ToString();
            bdayUsersByDate[keys[index]] = u.DisplayName;
            index++;
        }
    }
}

Now, we need to sort our birthdates by using lambda expressions. The following code will sort the birthdays but in the wrong order (sorry, my lambda experience is not great) so we have to swap the array in TempDT:


bdayDates.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });
List<DateTime> tempDT = new List<DateTime>();
int j = 0;
for (int i = bdayDates.Count - 1; i >= 0; i--)
{
    tempDT.Add(bdayDates[i]);
    j++;
}
bdayDates = tempDT;

Last but not least, we need to print the users:


int maxUsersToDisplay = 5;
if (bdayDates.Count < maxUsersToDisplay)
    maxUsersToDisplay = bdayDates.Count;
DateTime LastDate = new DateTime();
lblOutput.Text += "<table border='0' cellpadding='0' cellspacing='2' width='90%'>";
for (int i = 0; i < maxUsersToDisplay; i++)
{
    if (LastDate != bdayDates[i])
    {
        LastDate = bdayDates[i];
        for (int k = 0; k <= index; k++)
        {
            if (bdayUsersByDate[bdayDates[i] + "_" + k] != null)
            {
                if (bdayDates[i] == DateTime.Today)
                {
                    lblOutput.Text += "<tr><td style='width:60%; font-weight: bold;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right; font-weight: bold;'>Today</td></tr>";
                if(bdayUsersByDate[bdayDates[i] + "_" + k].ToString() == spWeb.CurrentUser.Name)
                {
                    divbday.Visible = true;
                }
            }
            else if(bdayDates[i] == DateTime.Today.AddDays(1))
            {
                lblOutput.Text += "<tr><td style='width:60%; font-weight: bold;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right; font-weight: bold;'>Tomorrow</td></tr>";
            }
            else
            {
                lblOutput.Text += "<tr><td style='width:60%;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right;'>" + bdayDates[i].Day + " " + bdayDates[i].ToString("MMMM") + "</td></tr>";
            }
        }
    }
}
lblOutput.Text += "</table>";

As Promised, here is the code in one block so if you want to copy, copy it from here 🙂


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Linq;
using System.Web;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Collections;
using System.Collections.Generic;

namespace JochimSergoyne_WebParts.JochimSergoyne_Birthdays
{
    public partial class JochimSergoyne_BirthdaysUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                lblOutput.Text = "";
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(SPControl.GetContextSite(HttpContext.Current).Url))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            SPServiceContext serviceContext = SPServiceContext.GetContext(spSite);
                            UserProfileManager upm = new UserProfileManager(serviceContext);
                            SPUserCollection spUsers = spWeb.AllUsers;
                            List<DateTime> bdayDates = new List<DateTime>();
                            Hashtable bdayUsersByDate = new Hashtable();
                            int index = 0;
                            string[] keys = new string[spWeb.AllUsers.Count];
                            foreach (SPUser user in spWeb.AllUsers)
                            {
                                string sAccount = user.LoginName;
                                if (upm.UserExists(sAccount))
                                {
                                    UserProfile u = upm.GetUserProfile(sAccount);
                                    if (u["SPS-Birthday"].Value != null)
                                    {
                                        string date = u["SPS-Birthday"].Value.ToString().Split(' ')[0];
                                        string day = date.Split('/')[1];
                                        string month = date.Split('/')[0];
                                        int year = DateTime.Now.Year + 1;
                                        if (int.Parse(month) > DateTime.Now.Month)
                                            year--;
                                        else
                                            if (int.Parse(month) == DateTime.Now.Month)
                                                if (int.Parse(day) >= DateTime.Now.Day)
                                                    year--;
                                        DateTime bday = new DateTime(year, int.Parse(month), int.Parse(day));
                                        bdayDates.Add(bday);
                                        keys[index] = bday + "_" + index.ToString();
                                        bdayUsersByDate[keys[index]] = u.DisplayName;
                                        index++;
                                    }
                                }
                            }
                            bdayDates.Sort(delegate(DateTime x, DateTime y){ return y.CompareTo(x); });
                            List<DateTime> tempDT = new List<DateTime>();
                            int j = 0;
                            for (int i = bdayDates.Count - 1; i >= 0; i--)
                            {
                                tempDT.Add(bdayDates[i]);
                                j++;
                            }
                            bdayDates = tempDT;
                            int maxUsersToDisplay = 5;
                            if (bdayDates.Count < maxUsersToDisplay)
                                maxUsersToDisplay = bdayDates.Count;
                            DateTime LastDate = new DateTime();
                            lblOutput.Text += "<table border='0' cellpadding='0' cellspacing='2' width='90%'>";
                            for (int i = 0; i < maxUsersToDisplay; i++)
                            {
                                if (LastDate != bdayDates[i])
                                {
                                    LastDate = bdayDates[i];
                                    for (int k = 0; k <= index; k++)
                                    {
                                        if (bdayUsersByDate[bdayDates[i] + "_" + k] != null)
                                        {
                                            if (bdayDates[i] == DateTime.Today)
                                            {
                                                lblOutput.Text += "<tr><td style='width:60%; font-weight: bold;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right; font-weight: bold;'>Today</td></tr>";
                                            }
                                            else if(bdayDates[i] == DateTime.Today.AddDays(1))
                                            {
                                                lblOutput.Text += "<tr><td style='width:60%; font-weight: bold;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right; font-weight: bold;'>Tomorrow</td></tr>";
                                            }
                                            else
                                            {
                                                lblOutput.Text += "<tr><td style='width:60%;'>" + bdayUsersByDate[bdayDates[i] + "_" + k] + "</td><td style='width:40%;text-align:right;'>" + bdayDates[i].Day + " " + bdayDates[i].ToString("MMMM") + "</td></tr>";
                                            }
                                        }
                                    }
                                }
                            }
                            lblOutput.Text += "</table>";
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                lblOutput.Text = ex.Message;
            }
        }
    }
}

If something is not clear or you have any questions, don’t hesitate to post a comment and I will try to answer asap!

 

Thanks to : http://jochimsergoyne.wordpress.com/2011/10/20/sharepoint-2010-upcoming-birthdays-webpart/