Second Life of a Hungarian SharePoint Geek

December 5, 2009

Getting the list of new items from code

Filed under: CAML, SharePoint — Tags: , — Peter Holpar @ 00:26

You have probably already noticed the little ‘NEW’ icon next to the items recently created in SharePoint. This icon appears by default next to the items not older than two days, but you can configure the time interval if you wish. This can be done by altering the days-to-show-new-icon parameter for the web application:

stsadm.exe -o setproperty -pn days-to-show-new-icon -pv 0 -url [Your Virtual Server’s URL]

This example sets the value to zero, that means the icon does not appear at all beside the items, even when they are just created.

Sometimes it may be useful to get the list of these kind of „latest items” from code. The key of this job is to know how to get the above-mentioned parameter from code, all the others are simple CAML query. So let’s see, how to do that!

First, we have to get a reference for the web application. If it is the application of the current web, it is so straightforward:

SPWebApplication webApp = web.Site.WebApplication;

Otherwise, it is a bit more difficult, you should know the name of the web application:

SPWebApplication webApp = 
SPWebService.ContentService.WebApplications["WebAppName"];

From the web application it is rather easy to get the value of the parameter:

int days = webApp.DaysToShowNewIndicator;

That is the number of days. Based on that there are two approaches to get the items created in this interval. In the first one, we get the exact time, that will be used for comparison, then build the CAML query using that exact value:

DateTime fromDate = DateTime.Now.AddDays(-days);
String fromDateString =
SPUtility.CreateISO8601DateTimeFromSystemDateTime(fromDate);
String query =
String.Format("<Where><Gt><FieldRef Name='Created'
IncludeTimeValue='TRUE' /><Value
Type='DateTime'>{0}</Value></Gt></Where>"
, fromDateString);

The second approach is even more simple. In this case we use the number of days as an offset in the query:


String query = String.Format("<Where><Gt><FieldRef
Name='Created' IncludeTimeValue='TRUE' /><Value
Type='DateTime'><Today OffsetDays='{0}'
/></Value></Gt></Where>"
, -days);

Note, that since the item creation happened in the past, we should use negative values in both cases.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: