C
Christopher Robin
I'd like to preface this post with the simple fact that I'm not a programmer,
which could very well be the root cause of some frustration. =D
At any rate, I'm attempting to pull data from a SharePoint list and have
copied code from the internet that is supposed to make this easier. The code
is listed below.
using System;
using System.Collections.Generic;
using SharePointServices.NorthwindSync;
using System.Xml;
namespace SharePointServices {
/// <summary>
/// ListHelper provides static methods that make life a little easier
when using
/// a Lists web service proxy.
/// </summary>
public class ListHelper {
///<summary>
/// Retrieves a Lists web service proxy with default settings.
///</summary>
/// <returns>A Lists web service proxy.</returns>
public static Lists GetListsService() {
string strComputerName = System.Net.Dns.GetHostName().ToLower();
if (strComputerName == "myServer") {
return GetListsService(
"http://myServer/vop/success/_vti_bin/lists.asmx",
System.Net.CredentialCache.DefaultCredentials
);
} else {
return GetListsService(
"http://myServer/vop/success/_vti_bin/lists.asmx",
System.Net.CredentialCache.DefaultCredentials
);
}
}
///<summary>
/// Retrieves a Lists web service proxy given a URL and credentials.
///</summary>
///<param name="strUrl">
/// The URL of a Lists web service. Typically:
/// http://[server]/[site]/_vti_bin/Lists.asmx</param>
///<param name="objCredentials">
/// A set of credentials, for example:
/// new System.Net.NetworkCredential("username", "password",
"domain")</param>
///<returns>A Lists web service proxy.</returns>
public static Lists GetListsService(
string strUrl,
System.Net.ICredentials objCredentials) {
Lists listService = new Lists();
listService.Credentials = objCredentials;
listService.Url = strUrl;
return listService;
}
/// <summary>
/// Determines if a given list exists by name by looping through all
lists.
/// </summary>
/// <param name="listService">A Lists web service proxy.</param>
/// <param name="strListTitle">The name of a list.</param>
/// <returns>True if the list exists otherwise false.</returns>
public static bool ListExists(Lists listService, string
strListTitle) {
XmlNode xmlNode = listService.GetListCollection();
foreach (XmlNode nodeChild in xmlNode.ChildNodes) {
if (nodeChild.Attributes["Title"].Value.Equals(strListTitle))
return true;
}
return false;
}
/// <summary>
/// Gets all list items in a given list. This method is useful
because
/// the default implementation of GetListItems() won't return more
items
/// than is specified in the default view.
/// </summary>
/// <param name="listService">A Lists web service proxy.</param>
/// <param name="strListName">The name of the list to retrieve items
from.</param>
/// <returns></returns>
public static XmlNode GetAllListItems(Lists listService, string
strListName) {
return listService.GetListItems(strListName, null, null, null,
"1000000", null, null);
}
/// <summary>
/// Inserts a single field/value into a CAML insert or update
statement.
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document that holds the CAML
statement.</param>
/// <param name="elementMethod">
/// The CAML statement's method (i.e. an insert or update statement).
/// </param>
/// <param name="strField">The name of a field/column to insert
strValue into.</param>
/// <param name="strValue">The value to insert into strField</param>
public static void AppendField(
XmlDocument xmlDoc,
XmlElement elementMethod,
string strField,
string strValue) {
XmlElement elementField = xmlDoc.CreateElement("Field");
elementField.SetAttribute("Name", strField);
XmlText text = xmlDoc.CreateTextNode(strValue);
elementField.AppendChild(text);
elementMethod.AppendChild(elementField);
}
/// <summary>
/// Creates a CAML statement (e.g. insert, update, or delete).
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document that holds the CAML
statement.</param>
/// <param name="elementBatch">The Batch XML element that holds a
group of CAML statements.</param>
/// <param name="strCmd">The individual CAML command, probably
insert update or delete.</param>
/// <param name="strId">A value to identify this transaction shoudl
an error occur.</param>
/// <returns>A CAML (XML) method element into which Fields can be
inserted.</returns>
public static XmlElement CreateMethod(
XmlDocument xmlDoc,
XmlElement elementBatch,
string strCmd,
string strId
) {
// method
XmlElement elementMethod = xmlDoc.CreateElement("Method");
elementMethod.SetAttribute("ID", strId);
elementMethod.SetAttribute("Cmd", strCmd);
elementBatch.AppendChild(elementMethod);
return elementMethod;
}
/// <summary>
/// Creates Batch CAML element inside of xmlDoc and returns the
result.
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document to create the Batch
element in.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437562.aspx">Batch
Element</seealso>
/// <returns>A Batch XAML element.</returns>
public static XmlElement CreateBatch(XmlDocument xmlDoc) {
XmlElement elementBatch = xmlDoc.CreateElement("Batch");
elementBatch.SetAttribute("OnError", "Continue");
return elementBatch;
}
/// <summary>
/// Adds a CAML Delete command to a batch for each list item in a
given list.
/// </summary>
/// <param name="listService">
/// Required to retrieve all list items in order to create
/// each delete command.</param>
/// <param name="strItemList">The list to delete all list items
from.</param>
/// <param name="xmlDoc">The XML document to store the delete
commands in.</param>
/// <param name="elementBatch">
/// An XML element into which which this method will add delete
'Method' elements.
/// </param>
public static void AddDeleteAllItemsBatch(
Lists listService,
string strItemList,
XmlDocument xmlDoc,
XmlElement elementBatch
) {
// get all items
XmlNode nodeListItems = GetAllListItems(listService, strItemList);
// for each item
XmlNode nodeRsData = nodeListItems.ChildNodes[1];
foreach (XmlNode nodeRow in nodeRsData.ChildNodes) {
if (nodeRow.NodeType == XmlNodeType.Element) {
string strId = nodeRow.Attributes["ows_ID"].Value;
// create a "delete" method
XmlElement elementMethod = CreateMethod(xmlDoc,
elementBatch, "Delete", strId);
// tell the delete method to delete the current report
term evaluation
AppendField(xmlDoc, elementMethod, "ID", strId);
}
}
}
/// <summary>
/// Breaks a larg CAML query into smaller batches to avoid the error
"Some part
/// of your SQL statement is nested too deeply. Rewrite the query or
break it
/// up into smaller queries."
/// </summary>
/// <param name="listService">The SharePoint list service to execute
the CAML against.</param>
/// <param name="strListName">The name of the list to execute the
CAML against.</param>
/// <param name="elementLargeBatch">The CAML batch list of commands
to be broken up.</param>
/// <param name="intBatchSize">
/// The size of batches to use. If unsure use 300, it seems to work
fairly well.</param>
/// <returns>The results of all batched queries.</returns>
public static XmlNode ExecuteLargeQuery(
Lists listService,
string strListName,
XmlElement elementLargeBatch,
int intBatchSize
) {
// calculate useful information
int intMethodCount = elementLargeBatch.ChildNodes.Count;
int intBatchCount = (int)Math.Ceiling((double)intMethodCount /
(double)intBatchSize);
// prepare xml documents for batches and results
XmlDocument xmlDocBatch = new XmlDocument();
XmlDocument xmlDocResults = new XmlDocument();
XmlElement elementResults =
xmlDocResults.CreateElement("Results");
// for each batch
for (int intCurrentBatch = 0; intCurrentBatch < intBatchCount;
intCurrentBatch++) {
int intMethodStart = intCurrentBatch * intBatchSize;
int intMethodEnd = Math.Min(intMethodStart + intBatchSize -
1, intMethodCount - 1);
XmlElement elementSmallBatch = CreateBatch(xmlDocBatch);
// for each method in the batch
for (int intCurrentMethod = intMethodStart; intCurrentMethod
<= intMethodEnd; intCurrentMethod++) {
XmlElement element =
(XmlElement)elementLargeBatch.ChildNodes[intCurrentMethod];
elementSmallBatch.AppendChild(xmlDocBatch.ImportNode(element, true));
}
// execute the batch
XmlNode nodeBatchResult =
listService.UpdateListItems(strListName, elementSmallBatch);
// add the results of the batch into the results xml document
foreach (XmlElement elementResult in
nodeBatchResult.ChildNodes)
elementResults.AppendChild(xmlDocResults.ImportNode(elementResult, true));
// clean up
xmlDocBatch.RemoveAll();
}
return elementResults;
}
/// <summary>
/// Retrieves the value of a list item, but simply returns an empty
string if it didn't exist.
/// </summary>
/// <param name="nodeRow">A list item.</param>
/// <param name="strAttributeName">The field to retrieve from the
list item.</param>
/// <returns>The value of the list item.</returns>
public static string GetListItemValue(XmlNode nodeRow, string
strAttributeName) {
XmlAttribute attr = nodeRow.Attributes[strAttributeName];
if (attr == null)
return "";
else
return attr.Value;
}
/// <summary>
/// Creates a new custom SharePoint list. This method will not work
if any field
/// contains a self-referential relationship.
/// </summary>
/// <param name="listService">The lists web service proxy.</param>
/// <param name="strListName">The name of the new list.</param>
/// <param name="strDescription">A description of the new
list.</param>
/// <param name="strFieldsInnerXml">
/// The list of fields in the new list. For example:
/// "<Method ID='1' AddToView=''>" +
/// "<Field Type='Lookup' List='[GUID of a foreign list]'
DisplayName='Field1' Required='TRUE' /></Method>" +
/// "<Method ID='2' AddToView=''><Field Type='Number'
DisplayName='Field2' Required='FALSE' /></Method>"
/// </param>
/// <param name="properties">Properties list</param>
/// <param name="templateID">
/// The Id of the template to use for the list. 100 = Custom List;
/// 101 = Document Library.</param>
/// <param name="strNewGuid">The GUID of the new list.</param>
/// <param name="nodeUpdateResult">The results of the update
statement.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437580.aspx">Field
Element</seealso>
public static void CreateList(
Lists listService,
string strListName,
string strDescription,
string strFieldsInnerXml,
IDictionary<string, string> properties,
int templateID,
out string strNewGuid,
out XmlNode nodeUpdateResult
) {
XmlDocument xmlDoc = new XmlDocument();
// delete list if it exists
if (ListExists(listService, strListName))
listService.DeleteList(strListName);
// add list
XmlNode nodeAddResult = listService.AddList(
strListName,
strDescription,
templateID
);
strNewGuid = nodeAddResult.Attributes["ID"].Value;
// fields
XmlNode nodeFields = xmlDoc.CreateElement("Fields");
nodeFields.InnerXml = strFieldsInnerXml;
// properties
XmlNode nodeList = null;
if (properties != null) {
nodeList = xmlDoc.CreateElement("List");
foreach (KeyValuePair<string, string> property in
properties) {
XmlAttribute attribute =
xmlDoc.CreateAttribute(property.Key);
attribute.Value = property.Value;
nodeList.Attributes.Append(attribute);
}
}
// add fields
nodeUpdateResult = listService.UpdateList(strNewGuid, nodeList,
nodeFields, null, null, null);
}
/// <summary>
/// Creates a new SharePoint list or any derivitave such as a
document library.
/// This method will not work if any field contains a
self-referential relationship.
/// </summary>
/// <param name="listService">The lists web service proxy.</param>
/// <param name="strListName">The name of the new list.</param>
/// <param name="strDescription">A description of the new
list.</param>
/// <param name="strFieldsInnerXml">
/// The list of fields in the new list. For example:
/// "<Method ID='1' AddToView=''><Field Type='Lookup' List='[GUID of
a foreign list]' DisplayName='Field1' Required='TRUE' /></Method>" +
/// "<Method ID='2' AddToView=''><Field Type='Number'
DisplayName='Field2' Required='FALSE' /></Method>"
/// </param>
/// <param name="strNewGuid">The GUID of the new list.</param>
/// <param name="nodeUpdateResult">The results of the update
statement.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437580.aspx">Field
Element</seealso>
public static void CreateList(
Lists listService,
string strListName,
string strDescription,
string strFieldsInnerXml,
out string strNewGuid,
out XmlNode nodeUpdateResult
) {
CreateList(
listService,
strListName,
strDescription,
strFieldsInnerXml,
null,
100,
out strNewGuid,
out nodeUpdateResult
);
}
/// <summary>
/// When SharePoint fields reference foreign lists their values
typically
/// consist of a combination of the Id and Title of the foreign
record
/// (e.g. 1#;SomeTitle). This method parses both the Id and the
Title.
/// </summary>
/// <param name="strReference">The reference to a foreign
record.</param>
/// <param name="intId">The foreign record's unique id.</param>
/// <param name="strTitle">
/// The foreign record's title or other identifying (but not
necessarily unique) field.
/// </param>
/// <returns>True if parsing was successful, otherwise
false.</returns>
public static bool ParseSharePointReference(
string strReference,
out int intId,
out string strTitle) {
// provide default values for the out parameters if this method
fails
intId = -1;
strTitle = null;
if (String.IsNullOrEmpty(strReference))
return false;
// parse out the parts of the reference
int intSemiColonLoc = strReference.IndexOf(';');
if (intSemiColonLoc == -1)
return false;
if (!Int32.TryParse(strReference.Remove(intSemiColonLoc), out
intId))
return false;
strTitle = strReference.Substring(intSemiColonLoc + 2);
return true;
}
/// <summary>
/// When SharePoint fields reference foreign lists their values
typically
/// consist of a combination of the Id and Title of the foreign
record
/// (e.g. 1#;SomeTitle). This method returns just the foreign Id.
/// </summary>
/// <param name="strSharePointReference">The reference to a foreign
record.</param>
/// <returns>The foreign record's unique id. -1 if the reference
was empty.</returns>
public static int ParseIntFromSharePointReference(string
strSharePointReference) {
if (strSharePointReference.Equals("")) {
return -1;
} else {
int intSemiColonReference =
strSharePointReference.IndexOf(';');
strSharePointReference =
strSharePointReference.Remove(intSemiColonReference);
return Convert.ToInt32(strSharePointReference);
}
}
}
}
After referencing this DLL in the project, the author of this site uses:
Dim listService As Lists = ListHelper.GetListsService()
ListHelper.GetAllListItems( _
listService, "My List")
to pull the data in. I want to do something similar to get my feel for C#
programming and familiarize myself with interactin with SharePoint Lists.
I have a C# project created, I've referenced the DLL, and added a data grid
view, which is bound to the ListHelper function of the DLL, but now I need
some help with actually populating the grid with the data from the SharePoint
List.
I've been having problems finding sample code for this. Everyone seems to
connect to a SQL Database.
Any pointers, insights or sample bits of code would be greatly appreciated.
Thanks,
Chris
which could very well be the root cause of some frustration. =D
At any rate, I'm attempting to pull data from a SharePoint list and have
copied code from the internet that is supposed to make this easier. The code
is listed below.
using System;
using System.Collections.Generic;
using SharePointServices.NorthwindSync;
using System.Xml;
namespace SharePointServices {
/// <summary>
/// ListHelper provides static methods that make life a little easier
when using
/// a Lists web service proxy.
/// </summary>
public class ListHelper {
///<summary>
/// Retrieves a Lists web service proxy with default settings.
///</summary>
/// <returns>A Lists web service proxy.</returns>
public static Lists GetListsService() {
string strComputerName = System.Net.Dns.GetHostName().ToLower();
if (strComputerName == "myServer") {
return GetListsService(
"http://myServer/vop/success/_vti_bin/lists.asmx",
System.Net.CredentialCache.DefaultCredentials
);
} else {
return GetListsService(
"http://myServer/vop/success/_vti_bin/lists.asmx",
System.Net.CredentialCache.DefaultCredentials
);
}
}
///<summary>
/// Retrieves a Lists web service proxy given a URL and credentials.
///</summary>
///<param name="strUrl">
/// The URL of a Lists web service. Typically:
/// http://[server]/[site]/_vti_bin/Lists.asmx</param>
///<param name="objCredentials">
/// A set of credentials, for example:
/// new System.Net.NetworkCredential("username", "password",
"domain")</param>
///<returns>A Lists web service proxy.</returns>
public static Lists GetListsService(
string strUrl,
System.Net.ICredentials objCredentials) {
Lists listService = new Lists();
listService.Credentials = objCredentials;
listService.Url = strUrl;
return listService;
}
/// <summary>
/// Determines if a given list exists by name by looping through all
lists.
/// </summary>
/// <param name="listService">A Lists web service proxy.</param>
/// <param name="strListTitle">The name of a list.</param>
/// <returns>True if the list exists otherwise false.</returns>
public static bool ListExists(Lists listService, string
strListTitle) {
XmlNode xmlNode = listService.GetListCollection();
foreach (XmlNode nodeChild in xmlNode.ChildNodes) {
if (nodeChild.Attributes["Title"].Value.Equals(strListTitle))
return true;
}
return false;
}
/// <summary>
/// Gets all list items in a given list. This method is useful
because
/// the default implementation of GetListItems() won't return more
items
/// than is specified in the default view.
/// </summary>
/// <param name="listService">A Lists web service proxy.</param>
/// <param name="strListName">The name of the list to retrieve items
from.</param>
/// <returns></returns>
public static XmlNode GetAllListItems(Lists listService, string
strListName) {
return listService.GetListItems(strListName, null, null, null,
"1000000", null, null);
}
/// <summary>
/// Inserts a single field/value into a CAML insert or update
statement.
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document that holds the CAML
statement.</param>
/// <param name="elementMethod">
/// The CAML statement's method (i.e. an insert or update statement).
/// </param>
/// <param name="strField">The name of a field/column to insert
strValue into.</param>
/// <param name="strValue">The value to insert into strField</param>
public static void AppendField(
XmlDocument xmlDoc,
XmlElement elementMethod,
string strField,
string strValue) {
XmlElement elementField = xmlDoc.CreateElement("Field");
elementField.SetAttribute("Name", strField);
XmlText text = xmlDoc.CreateTextNode(strValue);
elementField.AppendChild(text);
elementMethod.AppendChild(elementField);
}
/// <summary>
/// Creates a CAML statement (e.g. insert, update, or delete).
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document that holds the CAML
statement.</param>
/// <param name="elementBatch">The Batch XML element that holds a
group of CAML statements.</param>
/// <param name="strCmd">The individual CAML command, probably
insert update or delete.</param>
/// <param name="strId">A value to identify this transaction shoudl
an error occur.</param>
/// <returns>A CAML (XML) method element into which Fields can be
inserted.</returns>
public static XmlElement CreateMethod(
XmlDocument xmlDoc,
XmlElement elementBatch,
string strCmd,
string strId
) {
// method
XmlElement elementMethod = xmlDoc.CreateElement("Method");
elementMethod.SetAttribute("ID", strId);
elementMethod.SetAttribute("Cmd", strCmd);
elementBatch.AppendChild(elementMethod);
return elementMethod;
}
/// <summary>
/// Creates Batch CAML element inside of xmlDoc and returns the
result.
/// Usage Example (an insert statement):
///
/// XmlDocument xmlDoc = new XmlDocument();
/// XmlElement elementBatch = ListHelper.CreateBatch(xmlDoc);
/// elementMethod = ListHelper.CreateMethod(xmlDoc, elementBatch,
"New", "1");
/// ListHelper.AppendField(xmlDoc, elementMethod, "Title", "Hello
World");
/// listService.UpdateListItems("[ListName]", elementBatch);
/// </summary>
/// <param name="xmlDoc">The XML document to create the Batch
element in.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437562.aspx">Batch
Element</seealso>
/// <returns>A Batch XAML element.</returns>
public static XmlElement CreateBatch(XmlDocument xmlDoc) {
XmlElement elementBatch = xmlDoc.CreateElement("Batch");
elementBatch.SetAttribute("OnError", "Continue");
return elementBatch;
}
/// <summary>
/// Adds a CAML Delete command to a batch for each list item in a
given list.
/// </summary>
/// <param name="listService">
/// Required to retrieve all list items in order to create
/// each delete command.</param>
/// <param name="strItemList">The list to delete all list items
from.</param>
/// <param name="xmlDoc">The XML document to store the delete
commands in.</param>
/// <param name="elementBatch">
/// An XML element into which which this method will add delete
'Method' elements.
/// </param>
public static void AddDeleteAllItemsBatch(
Lists listService,
string strItemList,
XmlDocument xmlDoc,
XmlElement elementBatch
) {
// get all items
XmlNode nodeListItems = GetAllListItems(listService, strItemList);
// for each item
XmlNode nodeRsData = nodeListItems.ChildNodes[1];
foreach (XmlNode nodeRow in nodeRsData.ChildNodes) {
if (nodeRow.NodeType == XmlNodeType.Element) {
string strId = nodeRow.Attributes["ows_ID"].Value;
// create a "delete" method
XmlElement elementMethod = CreateMethod(xmlDoc,
elementBatch, "Delete", strId);
// tell the delete method to delete the current report
term evaluation
AppendField(xmlDoc, elementMethod, "ID", strId);
}
}
}
/// <summary>
/// Breaks a larg CAML query into smaller batches to avoid the error
"Some part
/// of your SQL statement is nested too deeply. Rewrite the query or
break it
/// up into smaller queries."
/// </summary>
/// <param name="listService">The SharePoint list service to execute
the CAML against.</param>
/// <param name="strListName">The name of the list to execute the
CAML against.</param>
/// <param name="elementLargeBatch">The CAML batch list of commands
to be broken up.</param>
/// <param name="intBatchSize">
/// The size of batches to use. If unsure use 300, it seems to work
fairly well.</param>
/// <returns>The results of all batched queries.</returns>
public static XmlNode ExecuteLargeQuery(
Lists listService,
string strListName,
XmlElement elementLargeBatch,
int intBatchSize
) {
// calculate useful information
int intMethodCount = elementLargeBatch.ChildNodes.Count;
int intBatchCount = (int)Math.Ceiling((double)intMethodCount /
(double)intBatchSize);
// prepare xml documents for batches and results
XmlDocument xmlDocBatch = new XmlDocument();
XmlDocument xmlDocResults = new XmlDocument();
XmlElement elementResults =
xmlDocResults.CreateElement("Results");
// for each batch
for (int intCurrentBatch = 0; intCurrentBatch < intBatchCount;
intCurrentBatch++) {
int intMethodStart = intCurrentBatch * intBatchSize;
int intMethodEnd = Math.Min(intMethodStart + intBatchSize -
1, intMethodCount - 1);
XmlElement elementSmallBatch = CreateBatch(xmlDocBatch);
// for each method in the batch
for (int intCurrentMethod = intMethodStart; intCurrentMethod
<= intMethodEnd; intCurrentMethod++) {
XmlElement element =
(XmlElement)elementLargeBatch.ChildNodes[intCurrentMethod];
elementSmallBatch.AppendChild(xmlDocBatch.ImportNode(element, true));
}
// execute the batch
XmlNode nodeBatchResult =
listService.UpdateListItems(strListName, elementSmallBatch);
// add the results of the batch into the results xml document
foreach (XmlElement elementResult in
nodeBatchResult.ChildNodes)
elementResults.AppendChild(xmlDocResults.ImportNode(elementResult, true));
// clean up
xmlDocBatch.RemoveAll();
}
return elementResults;
}
/// <summary>
/// Retrieves the value of a list item, but simply returns an empty
string if it didn't exist.
/// </summary>
/// <param name="nodeRow">A list item.</param>
/// <param name="strAttributeName">The field to retrieve from the
list item.</param>
/// <returns>The value of the list item.</returns>
public static string GetListItemValue(XmlNode nodeRow, string
strAttributeName) {
XmlAttribute attr = nodeRow.Attributes[strAttributeName];
if (attr == null)
return "";
else
return attr.Value;
}
/// <summary>
/// Creates a new custom SharePoint list. This method will not work
if any field
/// contains a self-referential relationship.
/// </summary>
/// <param name="listService">The lists web service proxy.</param>
/// <param name="strListName">The name of the new list.</param>
/// <param name="strDescription">A description of the new
list.</param>
/// <param name="strFieldsInnerXml">
/// The list of fields in the new list. For example:
/// "<Method ID='1' AddToView=''>" +
/// "<Field Type='Lookup' List='[GUID of a foreign list]'
DisplayName='Field1' Required='TRUE' /></Method>" +
/// "<Method ID='2' AddToView=''><Field Type='Number'
DisplayName='Field2' Required='FALSE' /></Method>"
/// </param>
/// <param name="properties">Properties list</param>
/// <param name="templateID">
/// The Id of the template to use for the list. 100 = Custom List;
/// 101 = Document Library.</param>
/// <param name="strNewGuid">The GUID of the new list.</param>
/// <param name="nodeUpdateResult">The results of the update
statement.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437580.aspx">Field
Element</seealso>
public static void CreateList(
Lists listService,
string strListName,
string strDescription,
string strFieldsInnerXml,
IDictionary<string, string> properties,
int templateID,
out string strNewGuid,
out XmlNode nodeUpdateResult
) {
XmlDocument xmlDoc = new XmlDocument();
// delete list if it exists
if (ListExists(listService, strListName))
listService.DeleteList(strListName);
// add list
XmlNode nodeAddResult = listService.AddList(
strListName,
strDescription,
templateID
);
strNewGuid = nodeAddResult.Attributes["ID"].Value;
// fields
XmlNode nodeFields = xmlDoc.CreateElement("Fields");
nodeFields.InnerXml = strFieldsInnerXml;
// properties
XmlNode nodeList = null;
if (properties != null) {
nodeList = xmlDoc.CreateElement("List");
foreach (KeyValuePair<string, string> property in
properties) {
XmlAttribute attribute =
xmlDoc.CreateAttribute(property.Key);
attribute.Value = property.Value;
nodeList.Attributes.Append(attribute);
}
}
// add fields
nodeUpdateResult = listService.UpdateList(strNewGuid, nodeList,
nodeFields, null, null, null);
}
/// <summary>
/// Creates a new SharePoint list or any derivitave such as a
document library.
/// This method will not work if any field contains a
self-referential relationship.
/// </summary>
/// <param name="listService">The lists web service proxy.</param>
/// <param name="strListName">The name of the new list.</param>
/// <param name="strDescription">A description of the new
list.</param>
/// <param name="strFieldsInnerXml">
/// The list of fields in the new list. For example:
/// "<Method ID='1' AddToView=''><Field Type='Lookup' List='[GUID of
a foreign list]' DisplayName='Field1' Required='TRUE' /></Method>" +
/// "<Method ID='2' AddToView=''><Field Type='Number'
DisplayName='Field2' Required='FALSE' /></Method>"
/// </param>
/// <param name="strNewGuid">The GUID of the new list.</param>
/// <param name="nodeUpdateResult">The results of the update
statement.</param>
/// <seealso
href="http://msdn2.microsoft.com/en-us/library/ms437580.aspx">Field
Element</seealso>
public static void CreateList(
Lists listService,
string strListName,
string strDescription,
string strFieldsInnerXml,
out string strNewGuid,
out XmlNode nodeUpdateResult
) {
CreateList(
listService,
strListName,
strDescription,
strFieldsInnerXml,
null,
100,
out strNewGuid,
out nodeUpdateResult
);
}
/// <summary>
/// When SharePoint fields reference foreign lists their values
typically
/// consist of a combination of the Id and Title of the foreign
record
/// (e.g. 1#;SomeTitle). This method parses both the Id and the
Title.
/// </summary>
/// <param name="strReference">The reference to a foreign
record.</param>
/// <param name="intId">The foreign record's unique id.</param>
/// <param name="strTitle">
/// The foreign record's title or other identifying (but not
necessarily unique) field.
/// </param>
/// <returns>True if parsing was successful, otherwise
false.</returns>
public static bool ParseSharePointReference(
string strReference,
out int intId,
out string strTitle) {
// provide default values for the out parameters if this method
fails
intId = -1;
strTitle = null;
if (String.IsNullOrEmpty(strReference))
return false;
// parse out the parts of the reference
int intSemiColonLoc = strReference.IndexOf(';');
if (intSemiColonLoc == -1)
return false;
if (!Int32.TryParse(strReference.Remove(intSemiColonLoc), out
intId))
return false;
strTitle = strReference.Substring(intSemiColonLoc + 2);
return true;
}
/// <summary>
/// When SharePoint fields reference foreign lists their values
typically
/// consist of a combination of the Id and Title of the foreign
record
/// (e.g. 1#;SomeTitle). This method returns just the foreign Id.
/// </summary>
/// <param name="strSharePointReference">The reference to a foreign
record.</param>
/// <returns>The foreign record's unique id. -1 if the reference
was empty.</returns>
public static int ParseIntFromSharePointReference(string
strSharePointReference) {
if (strSharePointReference.Equals("")) {
return -1;
} else {
int intSemiColonReference =
strSharePointReference.IndexOf(';');
strSharePointReference =
strSharePointReference.Remove(intSemiColonReference);
return Convert.ToInt32(strSharePointReference);
}
}
}
}
After referencing this DLL in the project, the author of this site uses:
Dim listService As Lists = ListHelper.GetListsService()
ListHelper.GetAllListItems( _
listService, "My List")
to pull the data in. I want to do something similar to get my feel for C#
programming and familiarize myself with interactin with SharePoint Lists.
I have a C# project created, I've referenced the DLL, and added a data grid
view, which is bound to the ListHelper function of the DLL, but now I need
some help with actually populating the grid with the data from the SharePoint
List.
I've been having problems finding sample code for this. Everyone seems to
connect to a SQL Database.
Any pointers, insights or sample bits of code would be greatly appreciated.
Thanks,
Chris