Friday, April 24, 2009

Sharepoint Web Services: creating Lists


Just felt like posting this snippet that shows how to create a List in Sharepoint using the web service that SP provides. Those web services could be found at hhtp://superDomain/sites/elSite/_vti_bin/Lists.asmx. Once you add the service reference to your project and create the proxy, the function of interest here is AddList() also how you define your InnerXml property for the new fields node is important and easy to make a mistake with. So as always with Sharepoint is very trial and errorish at least for me (scarred for ever by SP)

I hope this snippet stands the test of time in this blog post and I can easily find it one day, or if I can help some poor soul traveling through the Sharepoint ‘realms* the better/

More information can be found in MSDN at


public void CreateList()
     var listService = new Lists
       Url = @"http://superDomain/sites/elSite/_vti_bin/Lists.asmx",
       Credentials = CredentialCache.DefaultCredentials
     const string listName = "Web Service Created";
     var listCreatedAsXmlNode = listService.AddList(listName, "Web Service Created List Description", 100);
     var listRetrieved = listService.GetList(listName);
     XmlNode version = listRetrieved.Attributes["Version"]; 
     var xmlDoc = new XmlDocument();
     var titleAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Title", String.Empty);
     var descriptionAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Description", String.Empty);
     titleAttrib.Value = listName; // Can use this to update it
     //descriptionAttrib.Value = "!" ;
     var properties = xmlDoc.CreateNode(XmlNodeType.Element, "List", String.Empty);
     var newFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", String.Empty);
     newFields.InnerXml =
     @"<Method ID='1'>
       <Field Type='DateTime' DateOnly='TRUE' DisplayName='My Date Field' FromBaseType='TRUE' Required='TRUE' Description='some text description'/>
     <Method ID='2'>
       <Field Type='Number' MAX='10' DisplayName='NumberColumn' FromBaseType='TRUE' Required='TRUE' Description='This is a Number' />
     <Method ID='3'>
       <Field Type='Calculated' DisplayName='MyCalcField' ResultType='Text'>
             <FieldRef Name='Title'/>
             <FieldRef Name='NumberColumn'/>
       <Method ID='4'>
         <Field ReadOnly='TRUE' Type='Counter' PrimaryKey='FALSE' DisplayName='Counter' FromBaseType='TRUE' />
     var returnedNode = listService.UpdateList(listName ,properties,  newFields, null, null, version.Value);


David said...

Strangely enough, this isn't making me miss SharePoint ;)

troyhunt said...

Does this mean we'll be seeing more of elsharpo after his 7 mnth siesta?!

Dave - you're in denial mate ;)