Zieglers

Just little about C#, .NET, SQL Server, SharePoint and SAP

Archive for February, 2009

Featured Employee Web Part – AJAX Enabled

Posted by zieglers on February 18, 2009

Abstract: This document explains how to develop AJAX Enabled Featured Employee Web Part for SharePoint 2007. This web part displays a random employee profile after every 5 seconds using ASP.NET AJAX Technology.

Introduction

In this article, I’ll try to explain how to implement AJAX enabled “Featured Employee” web part. Actually what I mean by featured employee is any user profile which exists in SharePoint Shared Services user profiles list.

In most of the projects I worked, clients were asking for a web part which sort of displays or searches based on user profile info stored in Active Directory. I’ll try to show how to implement “Employee Directory Search” web part in another article. For this one, I’ll focus on just displaying employee info.

Let me mention some features of this web part. First of all, this web part will be changing displayed profile every 5 seconds using ASP.NET AJAX 1.0. Profiles will be displayed in a random fashion. Also, there is going to be a Department property to limit displayed profiles to a certain department of the company.

Department

Before we start, I’d like to show you how “Featured Employee” web part will look like once we are done. (After every 5 seconds, displayed profile will be randomly changed.)

Featured Employees

Design

Design of this web part can be divided into some sub sections as follows:

1. Implementing Featured Employee web part without AJAX capability

a. Get a list of user profiles and keep them in a collection

b. Filter user profiles based on following properties

i. Department (This is our first criteria. If user belongs to the department specified by web part properties pane, then include this user to “Displayable” collection)

ii. Photo Exists (Don’t display profiles w/o photo)

iii. Visible (If this additional ‘Visible’ Boolean property is true in user’s profile, then display this profile)

c. Randomly select only one employee profile

d. Display UI using control template

 

2. Adding AJAX capability

a. Enable SharePoint site for AJAX

i. Install ASP.NET AJAX 1.0

ii. Add necessary Web.Config entries

iii. Add Script Manager to master page

b. Create an Update Panel

c. Create a Timer and Event Handler for re-displaying profiles after each 5 sec.

d. Add code implemented in subsection 1 above to Update Panel.

First we will implement this web part as it will only display different employee profiles after every page load. Then, we will extend this functionality using AJAX.

Now, let’s start with the implementation of sub section 1.

Implementation

Implementing Featured Employee web part without AJAX capability

Get a list of user profiles and keep them in a collection

UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);

Filter user profiles based on following properties

i. Department (This is our first criteria. If user belongs to the department specified by web part properties pane, then include this user to “Displayable” collection)

Department User Profile Property

ii. Photo Exists (Don’t display profiles w/o photo)

Picture

iii. Visible (If this additional ‘Visible’ Boolean property is true in user’s profile, then display this profile)

Visible Property

private void FillDataListWithUserData(BaseDataList list)

{

// Get max number for randomazition

int max = 0;

ArrayList upc = new ArrayList();

 

foreach (UserProfile profile in profileManager)

// In order to show employee profile in web part,

// there should be a department value and this profile should be flagged as visible

if (Parse<String>(profile[“Department”]) != null

&& Parse<Boolean>(profile[“VisibleInFaceBook”])

&& Department == Parse<String>(profile[“Department”]))

{

// Add qualified user profile to list

upc.Add(profile);

max++;

}

 

}

Randomly select only one employee profile

// Generate a random index

Random random = new Random();

int randomIdx = random.Next(0, max);

 

int i = 0;

foreach (UserProfile profile in upc)

if (i == randomIdx)

{

users.Add(new FaceBookUser()

{

Name = Parse<String>(profile[“PreferredName”]),

FirstName = Parse<String>(profile[“FirstName”]),

LastName = Parse<String>(profile[“LastName”]),

Department = Parse<String>(profile[“Department”]),

Office = Parse<String>(profile[“Office”]),

Photo = Parse<String>(profile[“PictureURL”]),

AboutMe = Parse<String>(profile[“AboutMe”]),

Title = Parse<String>(profile[“Title”]),

MySiteUrl = Parse<String>(profile[“PersonalSpace”]),

HireDate = Parse<DateTime>(profile[“SPS-HireDate”])

});

break;

}

else

i++;

}

 

Display UI using control template

protected override string DeterminateView()

{

return @”~/_controltemplates/FaceBookWebPartControl.ascx”;

}

Adding AJAX capability

Enable SharePoint site for AJAX

i. Download & Install ASP.NET AJAX 1.0

Can be downloaded from Microsoft Download Center: http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en

ii. Add necessary Web.Config entries

You can follow the post I wrote in my blog for that:

https://zieglers.wordpress.com/2009/02/02/webconfig-entries-for-enabling-ajax-for-sharepoint-2007/

iii. Add Script Manager to master page

Add the following entry to the master page of the page which hosts Featured Employee web part:

<asp:ScriptManager runat=”server” ID=”ScriptManager1″></asp:ScriptManager>

ScriptManager in master page

Create an Update Panel

Now, we need an Update Panel in which contents of the web part will be displayed.

protected override void CreateChildControls()

{

base.CreateChildControls();

this.EnsureUpdatePanelFixups();

UpdatePanel up = new UpdatePanel();

up.ID = “UpdatePanel1”;

up.ChildrenAsTriggers = true;

up.UpdateMode = UpdatePanelUpdateMode.Conditional;

this.Controls.Add(up);

up.ContentTemplateContainer.Controls.Add(this.lstEmployeesList);

}

Note above that we add lstEmployeeList DataList to update panel container. This list is holding employee profiles to be displayed.

Create a Timer and Event Handler for re-displaying profiles after each 5 sec.

We also need a timer to fire the event which will be changing displayed profile after every 5 seconds.

Timer timer = new Timer();

timer.Interval = 5000;

timer.Tick += new EventHandler<EventArgs>(HandleButtonClick);

up.ContentTemplateContainer.Controls.Add(timer);

Display Employee Profile Event Handler

So, this timer will call HandleButtonClick event handler every 5 seconds and will change displayed profile. It does nothing but calls FillDataWithUserData to get lstEmployeeList DataList filled with new employee profile.

private void HandleButtonClick(object sender, EventArgs eventArgs)

{

using (SPWeb web = SPContext.Current.Site.OpenWeb())

{

// Change displayed user profile each time clock ticks

FillDataListWithUserData(lstEmployeesList);

}

}

Helper Code

This implementation makes use of some helper code.

Our first helper class is actually a base web part class. (BaseWebPart.cs)

Second helper class is just an entity class to hold some employee profile information. (FaceBookUser.cs)

Helper classes

Conclusion

As a result, we have an AJAX enabled web part displaying random employee profiles every 5 sec. from a selected department. This web part can be used at internal department sites of companies. It can also be useful for pages such as “contact us”, “board of directors”, “primary client contacts”… etc.

 

Advertisements

Posted in C#, IT Stuff, SharePoint | Tagged: , , , | 1 Comment »

How to filter list values based on current user profile? UserContextFilter Web Part

Posted by zieglers on February 17, 2009

In this article I’ll try to show you how to use UserContextFilter web part. UserContextFilter web part can be used in situations where you’d like to filter other web parts based on a property value of the current user. Mostly this filter criterion is current user id. However, in some cases one may need to use any of the user profile property values such as Title, Department, and Email … etc.

For this article I chose a simple scenario: We’ll add a Tasks web part and by using UserContextFilter web part only tasks assigned to current user will be shown.

Here are the details:

  • 1. Create a Team Site and delete all web parts on default.aspx page.

101

  • 2. Add Tasks web part.

 102

  • 3. Add Current User Filter WP.

103

This web part is only viewable in edit mode, and it needs to be configured prior to use.

104

  • 4. Add a connection to Tasks web part.

 1051

  • 5. Select “Assigned To” as Consumer Field Name and click “Finish”.

106

107

  • 6. Test UserContextFilter web part.
  • a. Create a test user called “testuser

 108

  • b. Assign this user to the test site’s visitors group.

 109

 110

  • c. Before signing in as testuser, create a sample task for this user.

 111

  • d. Now sign in as test user. Tasks web part, which is being filtered by UserContextFilter web part, should be displaying testuser’s tasks as follows.

112

113

zieglers

Posted in IT Stuff, SharePoint | Tagged: , , , , , , | 3 Comments »

Web.Config entries for enabling AJAX for SharePoint 2007

Posted by zieglers on February 2, 2009

   There are several steps to be followed when you want to enable AJAX for SharePoint 2007 such as installing Microsoft ASP.NET AJAX 1.0 and referencing AJAXControlToolkit.dll in your Visual Studio Web Part project. However, I think the most important part is providing required web.config entries. Most of the problems encountered during the process of enabling AJAX for SharePoint 2007 results from missing entries in web.config. That’s why I wanted to list them as follows:

 

Extending SharePoint web.config files with Microsoft ASP.NET AJAX 1.0

In order to enable and leverage ASP.NET AJAX capabilities for SharePoint 2007, some entries must be added to web.config file. 

 

1. Add a <sectionGroup> element to the <configSections> tag:

 

<configSections>   

    <sectionGroup name=”system.web.extensions” type=”System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″>
      <sectionGroup name=”scripting” type=”System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″>
          <section name=”scriptResourceHandler” type=”System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ requirePermission=”false” allowDefinition=”MachineToApplication”/>
        <sectionGroup name=”webServices” type=”System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″>
          <section name=”jsonSerialization” type=”System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ requirePermission=”false” allowDefinition=”Everywhere” />
          <section name=”profileService” type=”System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ requirePermission=”false” allowDefinition=”MachineToApplication” />
          <section name=”authenticationService” type=”System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ requirePermission=”false” allowDefinition=”MachineToApplication” />
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
</configSections>   

 

2. Add a <controls> section as a child of the <system.web>/<pages> tag.

 

    <pages>
      <controls>
        <add tagPrefix=”asp” namespace=”System.Web.UI” assembly=”System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
      </controls>
   
</pages>   


3. Add the following tag to the <assemblies> tag, within <compilation>:


      <assemblies>
       <add assembly=”System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
     
</assemblies>


4. Add some new registrations to the end of the <httpHandlers> section:


 <httpHandlers>
      <add verb=”*” path=”*.asmx” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
      <add verb=”*” path=”*_AppService.axd” validate=”false” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
      <add verb=”GET,HEAD” path=”ScriptResource.axd” type=”System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ validate=”false”/>
  </httpHandlers>

 

5. Add a new registration to the HttpModules section, beneath any existing registrations.


  <httpModules>
      <add name=”ScriptModule” type=”System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
  </httpModules>


 

6. Add a SafeControl entry for the System.Web.UI namespace from Microsoft Ajax Extensions, within the <SharePoint>/<SafeControls>section:


  <SafeControls>
      <SafeControl Assembly=”System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ Namespace=”System.Web.UI” TypeName=”*” Safe=”True” />
  </SafeControls>

 

7. Finally, add the following configuration tags at the bottom of web.config, near the bottom before the end <configuration> tag.


  <system.web.extensions>
    <scripting>
      <webServices>
      <!– Uncomment this line to enable the authentication service. Include requireSSL=”true” if appropriate. –>
      <!–
        <authenticationService enabled=”true” requireSSL = “true|false”/>
      –>
      <!– Uncomment these lines to enable the profile service. To allow profile properties to be retrieved and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and writeAccessProperties attributes. –>
      <!–
      <profileService enabled=”true”
                      readAccessProperties=”propertyname1,propertyname2″
                      writeAccessProperties=”propertyname1,propertyname2″ />
      –>
      </webServices>
      <!–
      <scriptResourceHandler enableCompression=”true” enableCaching=”true” />
      –>
    </scripting>
  </system.web.extensions>
  <system.webServer>
    <validation validateIntegratedModeConfiguration=”false”/>
    <modules>
      <add name=”ScriptModule” preCondition=”integratedMode” type=”System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
    </modules>
    <handlers>
      <remove name=”WebServiceHandlerFactory-Integrated” />
      <add name=”ScriptHandlerFactory” verb=”*” path=”*.asmx” preCondition=”integratedMode”
           type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
      <add name=”ScriptHandlerFactoryAppServices” verb=”*” path=”*_AppService.axd” preCondition=”integratedMode” type=”System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
      <add name=”ScriptResource” preCondition=”integratedMode” verb=”GET,HEAD” path=”ScriptResource.axd” type=”System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />
    </handlers>
  </system.webServer>

 

Adding a ScriptManager into a SharePoint MasterPage

 

Add the following into the markup of your master page.  A recommended location is right beneath the WebPartManager registration (search for  <WebPartPages:SPWebPartManager id=”m” runat=”Server” />):

    <asp:ScriptManager runat=”server” ID=”ScriptManager1″></asp:ScriptManager>

 

zieglers

 

Posted in IT Stuff, SharePoint | Tagged: , , , , , , , | 2 Comments »