Social Icons

Pages

Tuesday, May 21, 2013

Upload & Retrieve SharePoint attachments using Web Services (C#)

I did a lot of research to retrieve/ upload list item attachments using Client object model but found no solutions. The alternative method is Web services. This method returns the result in the form of XML Node. 

First to know about SharePoint Web Services please refer this


In order to connect to the web service first add a web reference to your Visual Studio project. Refer this

Here is the sample code which works absolutely.

Adding attachment to SharePoint list item
       public string AddingAttachments(string Url, string username, string password, string DomainName, int itemID, string attachFile, string ListName)
       {
           try
           {
               string attacnameName = "";
               byte[] contents;
               System.Net.NetworkCredential NC = new System.Net.NetworkCredential(username, password, DomainName);
               LService = new SharePointSvce.Lists();
               LService.Url = Url + "/_vti_bin/Lists.asmx";
               LService.Credentials = NC;

               System.IO.FileStream fStream = System.IO.File.OpenRead(attachFile);
               attacnameName = fStream.Name.Substring(3);
               contents = new byte[fStream.Length];
               fStream.Read(contents, 0, (int)fStream.Length);
               fStream.Close();

               try
               {
                   string addAttach = LService.AddAttachment(ListName, itemID.ToString(), attacnameName, contents);
               }
               catch (System.Web.Services.Protocols.SoapException ex)
               {

                   return ("Message:\n" + ex.Message + "\nDetail:\n" + ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace);
               }
           }
           catch (Exception ex)
           {

               return ex.Message;
           }
           return "";
       }
Retrieve attachment Details from SharePoint list item
public DataTable GetAvilableAttachmentsDetails(string Url, string username, string password, string DomainName, string SiteName, int taskID, string attachFile, string ListNAme)
       {
           try
           {
//Create table
              DataTable  dtAttachment = new DataTable();
              dtAttachment.Columns.Add("Name", typeof(string));
              dtAttachment.Columns.Add("SourceURL", typeof(string));

               System.Net.NetworkCredential NC = new System.Net.NetworkCredential(username, password, DomainName);
               LService = new SharePointSvce.Lists();
               LService.Url = currentURL + "/_vti_bin/Lists.asmx";
               LService.Credentials = NC;
               DataSet ds = new DataSet();
               XmlNode ndAttach = LService.GetAttachmentCollection(ListNAme, taskID.ToString());
               using (XmlNodeReader reader = new XmlNodeReader(ndAttach))
               {
                   ds.ReadXml(reader);
               }

               if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
               {
                   for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                   {
                       string sourceUrl = Convert.ToString(ds.Tables[0].Rows[i][0]);
                       int strLastIndx = sourceUrl.LastIndexOf(@"/");
                       string FileName = sourceUrl.Substring(strLastIndx + 1);
                       DataRow dr = dtAttachment.NewRow();
                       dr["SourceURL"] = sourceUrl;
                       dr["Name"] = FileName;
                       dtAttachment.Rows.Add(dr);
                   }
               }

           }
           catch (Exception)
           {
               return null;
           }
           return dtAttachment;
       }
Download attachment from SharePoint list item
public string DownloadAttachment(string Url, string username, string password, string DomainName, string SiteName, int taskID, string attachFile, string ListNAme, string SourceURL, string SavefilePath)

       {
           try
           {
               System.Net.NetworkCredential NC = new System.Net.NetworkCredential(username, password, DomainName);
               LService = new SharePointSvce.Lists();
               LService.Url = currentURL + "/_vti_bin/Lists.asmx";
               LService.Credentials = NC;
               using (WebClient client = new WebClient())
               {
                   client.UseDefaultCredentials = false;
                   client.Credentials = new NetworkCredential(username, password);
                   byte[] response = client.DownloadData(SourceURL);
                   int strLastIndx = SourceURL.LastIndexOf(@"/");
                   string FileName = SourceURL.Substring(strLastIndx + 1);
                   System.IO.FileStream fstream = System.IO.File.Create(@SavefilePath + "\\" + FileName);
                   fstream.Write(response, 0, response.Length);
                   fstream.Close();
                   return "";

               }

           }
           catch (Exception ex)
           {

               return ex.Message;
           }
       }
 
 Reference : http://msdn.microsoft.com/en-us/library/lists.lists.addattachment%28v=office.12%29.aspx
                  http://www.naumanahmed.com/2012/03/sharepoint-web-services-and-dataset-how.html

Tuesday, May 14, 2013

Retrieving SharePoint Task using Client Object Model (C#)

In this post I'm going to show how to retrieve Task details using Client Object model.
 

Step: 1 Add the SharePoint Reference
             Refer this article 

Step: 2  Add the SharePoint namespace
 using Microsoft.SharePoint.Client;
Create table

      void CreateTaskTable()
      {
          try
          {
            dtTask = new DataTable();
            dtTask.Columns.Add("TaskID", typeof(string));
            dtTask.Columns.Add("Title", typeof(string));
            dtTask.Columns.Add("Body", typeof(string));
            dtTask.Columns.Add("ListName", typeof(string));
            dtTask.Columns.Add("Status", typeof(string));
            dtTask.Columns.Add("StartDate", typeof(string));
            dtTask.Columns.Add("DueDate", typeof(string));
            dtTask.Columns.Add("AssignedTo", typeof(string));
            dtTask.Columns.Add("Priority", typeof(string));
            dtTask.Columns.Add("PercentComplete", typeof(string));
            dtTask.Columns.Add("Created", typeof(string));
            dtTask.Columns.Add("Modified", typeof(string));
            dtTask.Columns.Add("Created By", typeof(string));
            dtTask.Columns.Add("Modified By", typeof(string));
          }
          catch (Exception)
          {

              throw;
          }
      }
 Retrieving Task
       public DataTable GetTaskCollection(string Url, string UserName, string Password, string SiteName, string taskList)

       {
           try
           {
               ClientContext context = new ClientContext(Url);
               context.Credentials = new NetworkCredential(UserName, Password);
               context.Load(web);
               List list = web.Lists.GetByTitle(taskList);
               CamlQuery camlQuery = new CamlQuery();
               camlQuery.ViewXml = "<View/>";
               ListItemCollection listItems = list.GetItems(camlQuery);
               CreateTaskTable();
               context.Load(
               listItems,
               items => items.Include(
               item => item.Id,
               item => item["Title"],
               item => item["Status"],
               item => item["StartDate"],
               item => item["Modified"],
               item => item["Created"],
               item => item["Priority"],
               item => item["PercentComplete"],
               item => item["AssignedTo"],
               item => item["Body"],
               item => item["DueDate"]));
               context.ExecuteQuery();
               foreach (ListItem item in listItems)
               {
                   DataRow dr = dtTask.NewRow();
                   dr["TaskID"] = item.Id;
                   dr["Title"] = item["Title"];
                   dr["Status"] = item["Status"];
                   if (item["StartDate"] != null && item["StartDate"].ToString() != "")
                   {
                       DateTime dt = Convert.ToDateTime(item["StartDate"]);
                   }
                   if (item["DueDate"] != null && item["DueDate"].ToString() != "")
                   {
                       DateTime dt = Convert.ToDateTime(item["DueDate"]);
                   }
                   dr["Created"] = item["Created"];
                   dr["Modified"] = item["Modified"];
                   dr["Priority"] = item["Priority"];
                   dr["PercentComplete"] = item["PercentComplete"];
                   dr["Body"] = item["Body"];
                   dr["Reference"] = item["Reference"];
                   dr["ListName"] = taskList;
                   if (item["AssignedTo"] != null)
                   {
                       if (item["AssignedTo"].ToString() != "")
                       {
                           FieldUserValue uservalue = (FieldUserValue)item["AssignedTo"];
                           dr["AssignedTo"] = uservalue.LookupValue;
                       }
                   }
                   dtTask.Rows.Add(dr);
               }
           }
           catch (Exception)
           {
               return null;
           }
           return dtTask;
       }