Thursday, January 7, 2010

Accessing User Profile details programmatically

When you configure User Profiles, you can get a lot of information of the SPUser. These details can also be fetched programmatically. Let me show you how to do that.

Before we get into the coding, let me first explain you about user profile properties. To check what kind of user profile properties you have in your SSP, open your SSP -> User profile and Properties -> View Profile Properties. Here it displays the list of Profile Properties. You can edit some of the properties and set some conditions like whether user should be able to edit the property or not and so on.

Let's look at the code:

1. First you should add a reference to Microsoft.Office.Server

2. Define the namespace:

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

3. The actual code looks like this:

using (SPSite mySite = new SPSite("my Site URL"))
{
ServerContext context = ServerContext.GetContext(mySite);
UserProfileManager profileManager = new UserProfileManager(context);
foreach (UserProfile profile in profileManager)
{
Console.WriteLine(profile["FirstName"].Value.ToString()); //Gets First Name
Console.WriteLine(profile["Manager"].Value.ToString()); // Gets Manager's Name
}
}

Here, I'm trying to get the First Name and user's Manager Name for all the profiles who exists in my SharePoint site. As shown in the above code, you can get the details of the profile using the Property Name (FirstName, Manager).

When you run the above code, you may get "Access Denied" error. To resolve this, you should ensure that the credential under which the code runs should have proper permissions. To verify that, navigate to SSP home page, under "User Profiles and My Sites", click on "Personalization services permissions". Under Manage Permissions page, ensure that the user (under that credential the above code runs) has "Manage User Profiles" and "Personal Features" rights. And you got that code working!

Thursday, December 31, 2009

Limiting number of Attachments per SPListItem

Here is an example on how we can limit the number of attachments per SPListItem.

We need to write an event handler on the event "ItemAttachmentAdding". Lets straight away get into the example:

public override void ItemAttachmentAdding(SPItemEventProperties properties)
{
if (properties.ListTitle == "List Name")
{
//Do not allow more than one attachment per List Item
if (properties.ListItem.Attachments.Count >= 1)
{
properties.Cancel = true;
properties.ErrorMessage = "More than one attachment is not allowed per List Item!";
}
}
}
For the particular List, it checks for the number of attachments. If the ListItem already contains an attachment (Count = 1), it cancels the event and displays a custom message to the user.

Monday, December 28, 2009

Instead of custom error message, it displays %1!.512s!

I was working on some event handlers. I was trying to display a custom error message whenever a condition is met. So my code went like this:
properties.Cancel = true;
properties.ErrorMessage = "Custom Error Message";
Even though, the event was getting canceled, but to my surprise, the SharePoint always displayed a message as "%1!.512s!". I spent so much of time to figure out what was wrong. Finally, when I did googling, I was taken to this KB article where it is mentioned that it is a bug! :( Well, it was time to bang my head for some other reason!

Tuesday, December 15, 2009

Restore error due to different versions (RTM and SP1)

One of my friends faced an error during the restoration of Site Collection from one server to another server.

Error:
Your backup is from a different version of Windows SharePoint Services and cannot be restored to a server running the current version. The backup file should be restored to a server with version '12.0.0.6219' or later.
Cause:
The source server was installed with SharePoint SP1 (12.0.0.6219). The destination server was installed with SharePoint RTM version (12.0.0.4518).

To find out the SharePoint version installed, follow these simple steps:
  1. Open Central Administration
  2. Click on Operations
  3. Click on Servers in Farm
  4. Under "Farm Information", you can see the version.

Resolution:
It is a normal practise to ensure that Dev, and Staging servers are in sync with Production server. In the above case, either the source server should be made same as the destination server or destination server needs to be upgraded to SP1. The former approach is better as it involves less risks and of course, that should be planned before the start of the development.

Friday, December 11, 2009

Calculated field for Date column

In a SharePoint list or document library, we can create a calculated field. This field becomes handy when we have to display a formatted/calculated value based on the existing column. We often hear the requirements wherein we have to display a formatted value of the Date column.

Ex., Display only Month value of a date column, display only Month and year part of the date column and so on. Let me show you how we can achieve this:

For this example, create a list having a date field. When you create a list, by default, SharePoint adds two date fields "Modified" and "Created". So you can use any of these columns or you can create a custom Date field.

After creating a list, now create a column of type "Calculated". Under the Formula text box, we need to enter the formula which will fetch us the desired value. In my example, I'm going to use a custom date field "StartDate".

I want to display Month of the StartDate column in 3 characters like Jan, Feb. I'll use the below formula for that:
=TEXT(StartDate,"mmm")
Here, second parameter decides the format for the Date.

Now, I want to extend this to display something like this: Jan 2009, Oct 2010. I'll change the formula as:
=TEXT(StartDate,"mmm")&" "&YEAR(StartDate)
Let us see one complex formula. I want to calculate Quarter based on the date: Something like Q1, Q2 etc. The formula for this looks something like this:
=IF(AND(MONTH(StartDate)>=10,MONTH(StartDate)<=12),"Q3",IF(AND(MONTH(StartDate)>=1,MONTH(StartDate)<=3),"Q4",IF(AND(MONTH(StartDate)>=4,MONTH(StartDate)<=6),"Q1",IF(AND(MONTH(StartDate)>=7,MONTH(StartDate)<=9),"Q2",""))))
This is a nested IF condition using AND logical condition. The output looks something like this:



Similarly, we can use calculated column effectively to display formatted data. In my next post, I'm going to show you some more formulae.

Thursday, July 23, 2009

Deleting SPListItem using Web Service

I was working on adding/deleting list items using web services. When we have to delete the SPListItem from a document library/list, it is mandatory to mention ID of that SPListItem.

Ex.,


I cannot do something like this:



This way of coding would have helped more:
First, I would like to delete all the list items where City="Bengaluru".

Second, many a times we do not expose ID column for the user. So, we would be interested only in those columns which matters.

As a workaround, I had to use GetListItems to get the SPListItems where City = "Bengaluru" and then for each ID, execute UpdateListItems to delete those SPListItems.

Tuesday, July 7, 2009

GetDataTable() returns null

This actually bugged me for sometime! Look at this code:

SPListItemCollection results = list.GetItems (myQuery);
DataTable dtResults = results.GetDataTable();


Here, I'll execute a CAML (SPQuery) query against a list. From the SPListItemCollection, I'll try to get a DataTable.

If the SPListItemCollection is empty (i.e., results.Count = 0), the second line assigns null to dtResults. So, if you are referring to dtResults in the following lines, application throws NullReferenceException ("Object reference not set to an instance of an object"). I was expecting that, if there is no list item, the data table should be kind of empty table (no row but it should have schema).

So the summary is, whenever you are using GetDataTable(), make sure that you handle the null appropriately.