Module 4 - Code Snippets: Accessing SharePoint 2010 Data with Server-Side APIs

The following code shows how to obtain a reference to a specific Web, then to a specific list, and then how to enumerate the fields in the list:

SPSite thisSite = SPContext.Current.Site;
using (SPWeb targetWeb = thisSite.AllWebs["Project Management"])
{
SPList targetList = targetWeb.Lists["Announcements"];
foreach (SPField fld in targetList.Fields)
{
if(!fld.Hidden)
{
LiteralControl output = new LiteralControl(fld.InternalName + "<br/>");
this.Controls.Add(output);
}
}
}

 

The following code shows how to manipulate the field values for a list.
Note: The commented lines show alternative ways to reference a specific field in a list item.

SPSite thisSite = SPContext.Current.Site;
using (SPWeb targetWeb = thisSite.AllWebs["Project Management"])
{
SPList targetList = targetWeb.Lists["Announcements"];
SPListItemCollection allItems = targetList.Items;
//The following all show ways of accessing an individual list item
//allItems[0][0] = "<Some New Value>";
//allItems[0]["Title"] = "<New Title>";
//allItems[<Known GUID>]["Title"] = "<New Title>";
targetWeb.AllowUnsafeUpdates = true;
SPListItem newItem = allItems.Add();
newItem.Update();
Guid itemGuid = newItem.UniqueId; //Could be used later to ensure we can access this item
newItem["Title"] = "SharePoint Conference is a HUGE success!";
newItem["Body"] = "The much awaited for sneak peek of SharePoint 2010 was unveiled...";
newItem.Update();
targetWeb.AllowUnsafeUpdates = false;
}

 

The following code shows how to add two buttons to a Web Part that update list items. One button updates all items in a list, while the other button updates only those items returned by an efficient CAML query:

protected override void CreateChildControls()
{
Button updateAllProducts = new Button();
updateAllProducts.Text = "Apply 10% Discount";
updateAllProducts.Click += new EventHandler (updateAllProducts_Click);
updateAllProducts.Style.Add("Cursor", "Hand");
this.Controls.Add(updateAllProducts);
Button updateWingTipProducts = new Button();
updateWingTipProducts.Text = "Increase WingTip Prices";
updateWingTipProducts.Click += new EventHandler (updateWingTipProducts_Click);
updateWingTipProducts.Style.Add("Cursor", "Hand");
this.Controls.Add(updateWingTipProducts);
}
void updateAllProducts_Click(object sender, EventArgs e)
{
SPWeb thisWeb = SPContext.Current.Web;
SPList productList = thisWeb.Lists["Products"];
foreach (SPItem product in productList.Items)
{
double currentPrice = double.Parse(product["SellingPrice"].ToString());
currentPrice = (currentPrice*0.9);
product["SellingPrice"] = currentPrice;
product.Update();
}
this.Page.Response.Redirect(productList.DefaultViewUrl);
}
void updateWingTipProducts_Click(object sender, EventArgs e)
{
SPWeb thisWeb = SPContext.Current.Web;
SPList productList = thisWeb.Lists["Products"];
SPQuery wingTipsQuery = new SPQuery(productList.DefaultView);
wingTipsQuery.ViewFields = "<FieldRef Name='SellingPrice' />";
wingTipsQuery.Query =
"<Where><Contains><FieldRef Name='Manufacturer' /><Value Type='Text'>WingTips</Value></Contains></Where>";
foreach (SPItem product in productList.GetItems(wingTipsQuery))
{
double currentPrice = double.Parse(product["SellingPrice"].ToString ());
currentPrice = (currentPrice * 1.2);
product["SellingPrice"] = currentPrice;
product.Update();
}
this.Page.Response.Redirect(productList.DefaultViewURL);
}

 

The following code sample shows how to use Linq to SharePoint to access list items and display them in a table in a Web Part.
Note: This code relies on an entities class having been created by using SPMetal, and that entities class having been added to the Visual Studio project.

Table productsTable;
protected override void CreateChildControls()
{
Button linqToProducts = new Button();
linqToProducts.Text = "Run LINQ Query";
linqToProducts.Click += new EventHandler (linqToProducts_Click);
linqToProducts.Style.Add("Cursor", "Hand");
this.Controls.Add(linqToProducts);
productsTable = new Table();
this.Controls.Add(productsTable);
}
void linqToProducts_Click(object sender, EventArgs e)
{
ContosoEntitiesDataContext cdc = new ContosoEntitiesDataContext(https://intranet.contoso.com);
var products = from productList in cdc.Products
orderby productList.Manufacturer
select new { productList.Title, productList.SellingPrice, productList.Manufacturer };
foreach (var bikeProduct in products)
{
TableRow row = new TableRow();
TableCell productName = new TableCell();
productName.Text = bikeProduct.Title;
TableCell productManf = new TableCell();
productManf.Text = bikeProduct.Manufacturer;
TableCell productPrice = new TableCell();
productPrice.Text = bikeProduct.SellingPrice.ToString();
row.Cells.Add(productName);
row.Cells.Add(productManf);
row.Cells.Add (productPrice);
productsTable.Rows.Add(row);
}
}

 

The following code shows how to achieve content type manupulation that is not possible by using the browser user interface. Essentially, the code adds specific content types to folders in a document library when those folders are created with specific names of 'Quotes' and 'POs'.

public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPListItem added = properties.ListItem;
SPContentType fld = added.ParentList.ContentTypes["Folder"];
SPContentType po = added.ParentList.ContentTypes["PO"];
SPContentType quote = added.ParentList.ContentTypes["Quote"];
if (added.ContentType.Id == fld.Id)
{
SPFolder addedFolder = added.Folder;
IList<SPContentType> currentContentTypes = addedFolder.ContentTypeOrder;
List<SPContentType> cts = new List<SPContentType>();
if (added.Title == "POs")
{
cts.Add(po);
addedFolder.UniqueContentTypeOrder = cts;
addedFolder.Update();
}
if (added.Title == "Quotes")
{
cts.Add(quote);
addedFolder.UniqueContentTypeOrder = cts;
addedFolder.Update();
}
}
}