April 18th, 2008Making "user-aware" Web Parts
I have currently been tasked with the duty of providing a web part that displays patient satisfaction scores for the hospital. However, there was one stipulation:
“Can you make the web part reflect the unit that the nurse is working on?”.
In other words, could I create a web part that would observe the user’s login and display appropriate information based on where, in the hospital, that employee worked. In this case, the requester (ahem, my boss) wanted the scores to display for the nurse’s unit (think of a unit as a “wing” or “floor” in a hospital).
Provocative.
Right off the bat, I figured the best way to access the nurse’s unit was by pulling the “Department” property from our Active Directory schema.
But then I thought: “Why not build a function that would return any property I might want from Active Directory?” That way, from here on out, as I am building my web parts I could make decisions of the data to display based on a user’s department, job title, director, etc.
Essentially, creating web parts that are “user-aware”.
Good idea self!
Below is a namespace (ActiveDirectoryInfo) , class (UserInfo), and function (GetPropertyValue) that I created to do just this:
using Microsoft.Office.Server.Audience;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Text;
using System.Web;
namespace ActiveDirectoryInfo
{
class UserInfo
{
public String GetPropertyValue(string PropKey)
{
//Get user’s Department from Active Directory
SPWeb spw = SPControl.GetContextWeb(HttpContext.Current); //Establishes the current SharePoint site.
SPUser spu = spw.CurrentUser; //Grabs user information from the logged in state of the user.
DirectoryEntry dentry = new DirectoryEntry(@”LDAP://DC=<hidden>,DC=<hidden>”, “<domain_user>”, “<domain_user_password>”);
DirectorySearcher dsearch = new DirectorySearcher(dentry);
String retUserName= “”;
dsearch.Filter = “(objectSid=” + spu.Sid + “)”; //Filters the search result based on the user’s SID.
//dsearch.Filter = “(sAMAccountName=” + spu.LoginName.Replace(@”Domain\”, “”) + “)”; //Filters the search result based on the user’s login (without Domain\).
dsearch.PropertiesToLoad.Add(PropKey); //Loads the specific property to be viewed.
SearchResult result = dsearch.FindOne(); //Peforms the search for one matching record.
if (null == result)
{
//Nothing
}
else
{
retUserName = result.Properties[PropKey][0].ToString();
}
return retUserName;
}
}
}
So here is how we might call upon this function within a web part:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
UserInfo ui = new ActiveDirectoryInfo.UserInfo();
writer.Write(ui.GetPropertyValue(“cn”)); //Returns user’s full name
writer.Write(ui.GetPropertyValue(“mail”)); //Returns user’s e-mail
writer.Write(ui.GetPropertyValue(“Department”)); //Returns user’s Department
}