Search This Blog

Tuesday, February 11, 2014

Programmatically add list items using SharePoint 2010 COB with list web service



Add the SharePoint list web service using the below snapshots





Click Advanced section



Click Add Web Reference



In the URL type the corresponding site list web service



private static void CreateWithAttachment(string subject, DateTime frmDate, string fromAdd, string body, List<object> attCollections)
        {

            const string listName = "Read Mails";
            // set up our credentials
            var credentials = new NetworkCredential("spdev", "pwd", "domainname");

            // create a soap client
            var soapClient = new ListsService.Lists();
            soapClient.Credentials = credentials;

            // var create a client context
            var clientContext = new Microsoft.SharePoint.Client.ClientContext("vSiteUrl");
            clientContext.Credentials = credentials;

            // create a list item
            var list = clientContext.Web.Lists.GetByTitle(listName);
            var itemCreateInfo = new ListItemCreationInformation();
            var newItem = list.AddItem(itemCreateInfo);

            // set its properties
            newItem["Title"] = subject;
            newItem["From_x0020_Date"] = frmDate;
            newItem["From_x0020_Address"] = fromAdd;
            newItem["Body"] = body;

            //newItem["Status"] = "New";
            //newItem["_Comments"] = "here are some comments!!";

            // commit it
            newItem.Update();
            clientContext.ExecuteQuery();

            // load back the created item so its ID field is available for use below
            clientContext.Load(newItem);
            clientContext.ExecuteQuery();

            // use the soap client to add the attachment
            //const string path =filePath;

            foreach (List<object> attachColl in attCollections)
            {
                byte[] fs=null;
                string fn =string.Empty;
                foreach (var item in attachColl)
                {
                    fs = ((ReadPopMails.Program.Attachments)(item)).File;
                    fn = ((ReadPopMails.Program.Attachments)(item)).FileName;
                    //string fileName = Convert.ToString(item["FileName"]);
                    string filePath = SaveData(fn, fs);
                    soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(filePath),
                                         System.IO.File.ReadAllBytes(filePath));

                }

            }

            //soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(filePath),
            //                          System.IO.File.ReadAllBytes(filePath));
        }