Tuesday, August 09, 2011

SharePoint 2010 Getting List Item Attachments using Silverlight Client Object Model


I did a lot of research to get list item attachments. I have searched in forums but found no solution.
Using Client Object Model, we cannot get List Item Attachments collection, client object model will return a list item object, but the object doesn't contain the attachments collection info and supports no methods to get attachments collection.
  The alternative method is calling web service method GetAttachmentCollection from the service lists.asmx. This method returns the result in the form of XMLNode. Here is the sample code which works perfectly.
The below example Gets the list item from a given list, then Gets its first image attachment and shows it in the Silverlight Image Control.
Add the below line in the import section to import SharePoint.Client dll.
using SP = Microsoft.SharePoint.Client;

Here follows the code. This code I have copied from my Visual studio and formatted here to relate it to the post, I may forgot to declare some of the variables, but once you copy this code in to your Visual Studio, you can easily fix those compilation errors.

SP.ClientContext context;
SP.Web spWeb;
SP.Web currentWeb;
SP.List propertiesList;
string serviceUrl = string.Empty;
SP.ListItemCollection listItems;
 
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
 
private void RequestFailed(object sender, SP.ClientRequestFailedEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Error occured: " + e.Exception);
});
}
 
 
private void GetRequestSucceeded(object sender, SP.ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
serviceUrl = e.Request.WebRequest.RequestUri.AbsoluteUri;
serviceUrl = serviceUrl.Substring(0, serviceUrl.IndexOf("_vti_bin"));
foreach (SP.ListItem item in listItems)
{
   GetAttchmentCollection(item.Id.ToString());
}
});
}
 
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName,id);
}
 
void oClient_GetAttachmentCollectionCompleted(object sender, ServiceReference1.GetAttachmentCollectionCompletedEventArgs e)
{
XElement element = e.Result;
string attachments = element.Value;
string[] splitString = { "http" };
string[] attchmentArray = attachments.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < attchmentArray.Length; i++)
{
string extension=System.IO.Path.GetExtension(attchmentArray[i]).ToLower();
if (extension == ".png" || extension == ".jpg" || extension == ".jpeg" || extension == ".tif")
{
DownloadAttachedFileFromListItem("http" + attchmentArray[i]);
break;
}
}
}
 
 
public void DownloadAttachedFileFromListItem(string fileName)
{
using (ClientContext clientContext = new ClientContext(serviceUrl))
{
File.OpenBinaryDirect(clientContext, "/" + fileName.Replace(serviceUrl, ""), OpenBinaryFileSuccess, OpenBinaryFileFailure);
}
}
 
void OpenBinaryFileSuccess(object o, OpenBinarySucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
BitmapImage bitmapimage = new BitmapImage();
bitmapimage.SetSource(e.Stream);
imgPhoto.Width = bitmapimage.PixelWidth > imgPhoto.ActualWidth ? imgPhoto.ActualWidth : bitmapimage.PixelWidth;
imgPhoto.Height = bitmapimage.PixelHeight > imgPhoto.ActualHeight ? imgPhoto.ActualHeight : bitmapimage.PixelHeight;
imgPhoto.Source = bitmapimage;
});
}
 
void OpenBinaryFileFailure(object o, OpenBinaryFailedEventArgs e)
{
}