maandag 9 april 2012

Update or Insert Sharepoint ListItems in a List Library


Looking for a way to update a Sharepoint ListItem by using the Lists.asmx webservice...
For doing this you need to create your function to create your Xml Layout
and afterwards call the function below UpdateSPList.
 

 XmlDocument xmlDoc = new XmlDocument();
 XmlElement elBatch = xmlDoc.CreateElement("Batch");
 elBatch.SetAttribute("OnError", "Continue");
 // this because if one of the methods gives an error it will continue with the next method
 elBatch.SetAttribute("ViewName", Sharepoint_ViewId);
 elBatch.InnerXml = strBatch;
 
 returncode = UpdateSPList( sSiteUrl,  sSiteList,  elBatch);


 
strBatch containing for example:
        
<Method ID='0' Cmd='Update'>
    <Field Name='ID'> SharepointListItem.ows_ID </Field>
</Method>
<Method ID='1' Cmd='Update'>
    <Field Name='ID'>OtherSharepointListItem.ows_ID </Field>
</Method>
<Method ID='0' Cmd='New'>
            <Field Name='ID'>New</Field>
            <Field Name='Title'>YOUR TEXT HERE</Field>
</Method>
<Method ID='1' Cmd='New'>
            <Field Name='ID'>New</Field>
            <Field Name='Title'>YOUR TEXT HERE</Field>

 



Remark: The next Chars must be translated in the text values for your Fieldtag:
    "&" ==> "&"
    "<" ==> "<"
    ">" ==> ">"
    "\"" ==> """
    "'" ==> "'"

Below you find my Function that I have created that actualy does 
the update or insert into your List.
It requires three parameters : 
- the Site Url you are working on
- the List name on which you want to add or update one or more items
- the XML that contains the Batch Element

You will see that the function also uses the next global parameters
- sTechnicalUser
- sTechnicalPw
- sDomain
- bDefaultLogon (if true you will connect to the webservice with the 
user that is executing the program, otherwise use the technical user with it's
password and domain.  
This is done for giving the possibility to let shedule the program. 
         
 private Boolean UpdateSPList(string sSiteUrl, string sSiteList, XmlElement elBatch)
        {
            Boolean retcode = true;

            REFERANCENAME.Lists list = new REFERANCENAME.Lists();
            list.Url = sSiteUrl + "/_vti_bin/lists.asmx";
            if (bDefaultLogon)
                list.Credentials = System.Net.CredentialCache.DefaultCredentials;
            else
            {
                list.PreAuthenticate = true;
                list.Credentials = new System.Net.NetworkCredential(sTechnicalUser, sTechnicalPw, sDomain);
            }
            logThis("Start updateSPList " + sSiteUrl + " " + sSiteList + " ...");
            try
            {
                XmlNode ndReturn = list.UpdateListItems(sSiteList, elBatch);
                logThis(sSpaces + "return " + ndReturn.OuterXml);
                // Instantiate a new XML document object to hold the return value(s)
                XmlDocument xmlResult = new XmlDocument();
                xmlResult.LoadXml(ndReturn.OuterXml);
                // SharePoint XML always uses a fixed namespace; you'll need your own NamespaceManager object to parse the return values
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlResult.NameTable);
                nsMgr.AddNamespace("sp", ndReturn.NamespaceURI);
                XmlNode ndRoot = xmlResult.SelectSingleNode("sp:Results", nsMgr);
                // Find the ErrorCode node, which exists for all operations regardless of status.
                XmlNodeList nlResults = ndRoot.SelectNodes("//sp:Result/sp:ErrorCode", nsMgr);
                // Loop through the node collection and find each ErrorCode entry
                foreach (XmlNode ndResult in nlResults)
                {
                    // Check the value of the node to determine its status
                    if (ndResult.InnerText != "0x00000000")
                    {
                        XmlNode ndError = ndResult.NextSibling;
                        string sError = ndError.InnerText;
                        // Set the value of string variable to hold the error code
                        this.logThis("Update operation failed for " + sSiteList + ": " + sError + ".");
                        // If you want to trip the Try…Catch, throw and exception of whatever type suits you
                        iFailedUpdatedRecords++;
                    }
                    else
                    {
                        iUpdatedRecords++;
                    }
                }
           }
            catch (Exception e)
            {
                logThis(sSpaces + "Error UpdateSPList ", e);
                retcode = false;
            }
            finally
            {
                list.Dispose(); // important!!!! always dispose your sharepoint objects !!!!!
                logThis("End updateSPList " + sSiteUrl + " " + sSiteList);
            }
            return retcode;
        }
 


Geen opmerkingen:

Een reactie posten