Friday, January 8, 2010

Silverlight ClientObject Model, uploading File to Document Library

Hi,
I want to share the new learning with all of you,I was trying to upload file to document library suing client object model. the client Object Model for Managed code gives option for 'SavebinaryDirect()' but no such thing for silverlight, then how to achieve the same goal using silverligt. hey below is the code -

private void uploadFileToDocumentLibrary(string fileName, byte[] fileContent)
{
ClientContext cnt = ClientContext.Current;

listForUpload = cnt.Web.Lists.GetByTitle("Redmond");

this.Dispatcher.BeginInvoke(delegate()
{
cnt.Load(listForUpload);
cnt.Load(listForUpload.RootFolder);
cnt.Load(listForUpload.RootFolder.Files);
cnt.ExecuteQueryAsync(succeedUploadFileListner, failureUploadFileListner);
});

}


private void succeedUploadFileListner(object sender, ClientRequestSucceededEventArgs e)
{

// byte[] dataArray;
Microsoft.SharePoint.Client.File file1 = listForUpload.RootFolder.Files[0];
this.Dispatcher.BeginInvoke(delegate()
{
byte[] dataArray = allFiles[lstFiles.Items[0].ToString()];
FileCreationInformation file = new Microsoft.SharePoint.Client.FileCreationInformation();

file.Content = dataArray;
file.Overwrite = true;
file.Url = lstFiles.Items[0].ToString();
listForUpload.RootFolder.Files.Add(file);
listForUpload.Update();
ClientContext.Current.ExecuteQueryAsync(s1, f1);


});


}

private void s1(object sender, ClientRequestSucceededEventArgs e)
{
this.Dispatcher.BeginInvoke(delegate()
{
MessageBox.Show("File Uploaded");
});
}
private void f1(object sender, ClientRequestFailedEventArgs e)
{
this.Dispatcher.BeginInvoke(delegate()
{
if (string.IsNullOrEmpty(e.Message))
{
MessageBox.Show(e.Exception.InnerException.Message);
}
else
{
MessageBox.Show(e.Message);
}
});
}
Key things are - First list should be loaded, then you can access .rootFolder and add files to it. this is the reason why I am writting actual file upload code in succeddLisnter of List load.

File.Url is file name and list.rootFolder gives the address like http:///.

In this snippet the error which bugged me most is 'Remote server returned error:Not found'. this error comes when the requested object is not reachabel, reasons could be typo error or invalid url or like in my case I was giving file.Url = "http://... full url where as it should be file Name like try.txt.

the second error I found at I was trying to add files before list lost, the moment I replaced to add file code to succeddLisnter it worked like charm. try this

Cheers :)

No comments:

Post a Comment