Tuesday, August 29, 2006

Common (and simple) coding tasks in sharepoint

Well, everyone went to teched last week and I was left at work stuck with a project with a strict deadline. So out of boredom I decided that I will compile a small snippet database for beggining sharepoint developers.
I see a lot of people in the microsoft public sharepoint developer forums asking these questions over and over again, so I thought I will save everyone some time by answering these right here.
Some people may say these are RTFM questions, since the SDK contains all of these examples, but apperantly people dont bother with the SDK, or find it confusing to navigate through. So here is my 2 cents.

The purpose here is to give some code samples to common tasks like:

  • getting a reference to a site
  • Iterating over all lists in a site
  • getting a reference to a list
  • getting a reference to an item in a list
  • getting a reference to the item's properties
  • getting a reference to a document and its properties
  • adding a new item to a list
  • modifying an item in a list

If you feel I should add to this list, let me know and I will write some sample code. However, please remember this is for simple, common tasks and I wont start giving application samples here.

So, lets get down to it!

Getting a reference to a site

Ok, you have a sharepoint site in a URL "http://server/sites/site" and you want to get the object of the site from its URL. What do you do?

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
   using(SPWeb myWeb = mySite.OpenWeb())
   {
   }
}

Now you have the SPWeb object, allowing you to get information about the site you used in the URL. For example, iterating all lists in the site:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
   using(SPWeb myWeb = mySite.OpenWeb())
   {
      string linksHtml = "";
      foreach(SPList list in myWeb.Lists)
      {           
         string listLink = "<a href='" + list.DefaultView.Url.ToString()          + "'>" + list.Title + "</a>(<b>"+list.Items.Count+"</b>)<br>";
         linksHtml += listLink;
      }
   }
}

The above example also showed how to get a reference to a list by iterating over the lists in a site. But what if you want a specific list called "contacts"? The following will show you how to get the object for a list that you know the name of:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
   using(SPWeb myWeb = mySite.OpenWeb())
   {
      SPList contactsList = myWeb.Lists["Contacts"];
   }
}

Now lets iterate through the items in the list and get item's properties:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
   using(SPWeb myWeb = mySite.OpenWeb())
   {
      SPList contactsList = myWeb.Lists["Contacts"];
      foreach (SPListItem contact in contactsList.Items)
      {
         string contactLastName = contact["Last Name"].ToString();
      }
   }
}

Now some of you are saying - "what about documents?", to which I answer that document libraries are the same as lists (ok, there are some differences but we will leave that for future articles). To get to a document in a document library you can either use the code above to iterate through the library and its files, or, if you know the file's URL, you can do this:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPFile file = myWeb.GetFile("http://server/sites/site/library/folder/file");
}
}

File properties are available through its Item property. If you have for example a text field in the document library called "My Custom String Property", and you want to know the value for that field in a specific file, use the following code:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPFile file = myWeb.GetFile("http://server/sites/site/library/folder/file");
string filePropertyValue = file.Item["My Custom String Property"].ToString();
}
}

We now want to add a new item to a list:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
SPListItem newItem = contactsList.Items.Add();
newItem["First Name"] = "Ishai";
newItem["Last Name"] = "Sagi";
newItem.Update();
}
}

Lets change all items in the list to build the email address based on the first and last name (in the format of 'first.last@testing.com') :

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
foreach(SPListItem existingItem in contactsList.Items)
{
existingItem["E-mail Address"] = existingItem["First Name"] + "." + existingItem["Last Name"] + "@testing.com";
newItem.Update();
}
}
}

Well, that's it. If you think of more snippets like that, let me know!

[Update 4/4/2007 : I have replaced the old samples to best practice format (using using)]

12 comments:

Henry said...

Ishai, you're the man.

Puneetn said...

Whenever opening a SPSite or SPWeb explicitly (Not Context webs or sites) you should dispose them. I feel any post giving out how to use SPSite and SPWeb should also make sure that they are correctly disposing these objects. This is one of the big reasons for bad perf/memory leaks in sharepoint environment.

You can find a good article on best practices here: http://msdn2.microsoft.com/en-us/library/ms778813.aspx

Ishai Sagi said...

Puneetn, I agree, and if I recall I wrote about that about a month ago. however, its true that if i write this kind of post I should remind my readers of that.

Kanwal said...

You are now part of the BUZZ, SharePoint BUZZ

Visit http://www.sharepointbuzz.com

Anonymous said...

What about item level security when iterrating though a item list, a folders file list etc???

When a user try who hasent acces to a special file/Item in a list this required som kind of 'has read access' aproach or??? Code for that???

Bob C said...

How about getting the current user from context?

Mark Kruger, WSS MVP said...

Great idea for a post and very handy! Hope you dont mind that I reposted with full credit and direct link! Keep up the good work ;o)

Anonymous said...

good work!
you should fix a small bug in the last example:

foreach(SPListItem existingItem in contactsList.Items)
{
existingItem["E-mail Address"] = existingItem["First Name"] + "." + existingItem["Last Name"] + "@testing.com";
newItem.Update(); // bug - should be existingItem
}

SnowMirror said...

One correction in List code above:

using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
foreach (SPListItem contact in contactsList.Items)
{
string contactLastName = contact["Last Name"].ToString();
}
}
}

Anonymous said...

Great Work! helped me a lot
- Grace

Anonymous said...

SPWeb mySite = SPContext.Current.Web;
SPList li = mySite.Lists["List"];
SPQuery oQuery = new SPQuery();
oQuery.Query = string.Concat("", "", "6", "");
oQuery.ViewFields = string.Concat( "", "", "", "");
oQuery.ViewFieldsOnly = true;
SPListItemCollection collListItems = li.GetItems(oQuery);
foreach (SPListItem oListItem in collListItems)
{
MyLabel.Text = oListItem["Title"].ToString();
}

i want to ask how can i insert item in the list .. can u give me idea of doing this in server object model .. and what will be the query in this case ??

Saad Zulfiqar said...

SPWeb mySite = SPContext.Current.Web;

SPList li = mySite.Lists["List"];

SPQuery oQuery = new SPQuery();

oQuery.Query = string.Concat("",
"",
"6",
"");


oQuery.ViewFields = string.Concat(
"",
"",
"",
"");

oQuery.ViewFieldsOnly = true;
SPListItemCollection collListItems = li.GetItems(oQuery);



foreach (SPListItem oListItem in collListItems)
{
Label9.Text = oListItem["Title"].ToString();
}

i want to ask how can i insert item in the list .. can u give me idea of doing this in server object model .. and what will be the query in this case ??