Sharepoint 2010 Upload file using Silverlight 4.0 - silverlight

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu

Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Related

Save file to device with memorystream

I was wondering if it is possible with xamarin.forms to download any type of file to the device.. de files are stored on Azure, i get a Memorystream of the file, its very important for my app. my question excists of 2 parts actually,
how to download de file to the device of the user?,
and how to show the file of Any type in a default application of the type ( like pdf reader)
this is what i tried
MemoryStream memoryStream = AzureDownloader.DownloadFromAzureBlobStorage(null, doc.azure_container, doc.file_path, ref filen, true);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = doc.filename;
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, memoryStream.ToArray()); // this is a try to save to local storage
any help appreciated
how to download the file to the device of the user?
Use PCLStorage as its cross-platform and would work for iOS and Android:
public async Task CreateRealFileAsync()
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync("Sample Text...");
}
how to show the file of Any type in a default application of the type
( like pdf reader)
this is too broad and could have several solutions depending on what exactly you want to achieve.
Hope this helps

Silverlight: Business Application Needs Access To Files To Print and Move

I have the following requirement for a business application:
(All of this could be on local or server)
Allow user to select folder location
Show contents of folder
Print selected items from folder (*.pdf)
Display which files have been printed
Potentially move printed files to new location (sub-folder of printed)
How can I make this happen in Silverlight?
Kind regards,
ribald
First of all, all but the last item can be done (the way you expect). Due to security protocols, silverlight cannot access the user's drive and manipulate it. The closest you can get is accessing silverlight's application storage which will be of no help to you whatsoever in this case. I will highlight how to do the first 4 items.
Allow user to select folder location & Show contents of folder
public void OnSelectPDF(object sender)
{
//create the open file dialog
OpenFileDialog ofg = new OpenFileDialog();
//filter to show only pdf files
ofg.Filter = "PDF Files|*.pdf";
ofg.ShowDialog();
byte[] _import_file = new byte[0];
//once a file is selected proceed
if (!object.ReferenceEquals(ofg.File, null))
{
try
{
fs = ofg.File.OpenRead();
_import_file = new byte[fs.Length];
fs.Read(_import_file, 0, (int)fs.Length);
}
catch (Exception ex)
{
}
finally
{
if (!object.ReferenceEquals(fs, null))
fs.Close();
}
//do stuff with file - such as upload the file to the server
};
}
If you noticed, in my example, once the file is retrieved, i suggest uploading it to a webserver or somewhere with temporary public access. I would recommend doing this via a web service. E.g
//configure the system file (customn class)
TSystemFile objFile = new TNetworkFile().Initialize();
//get the file description from the Open File Dialog (ofg)
objFile.Description = ofg.File.Extension.Contains(".") ? ofg.File.Extension : "." + ofg.File.Extension;
objFile.FileData = _import_file;
objFile.FileName = ofg.File.Name;
//upload the file
MasterService.ToolingInterface.UploadTemporaryFileAsync(objFile);
Once this file is uploaded, on the async result, most likely returning the temporary file name and upload location, I would foward the call to some javascript method in the browser for it to use the generic "download.aspx?fileName=givenFileName" technique to force a download on the users system which would take care of both saving to a new location and printing. Which is what your are seeking.
Example of the javascript technique (remember to include System.Windows.Browser):
public void OnInvokeDownload(string _destination)
{
//call the browser method/jquery method
//(I use constants to centralize the names of the respective browser methods)
try
{
HtmlWindow window = HtmlPage.Window;
//where BM_INVOKE_DOWNLOAD is something like "invokeDownload"
window.Invoke(Constants.TBrowserMethods.BM_INVOKE_DOWNLOAD, new object[] { _destination});
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Ensure you have the javascript method existing either in an included javaScript file or in the same hosting page as your silverlight app. E.g:
function invokeDownload(_destination) {
//some fancy jquery or just the traditional document.location change here
//open a popup window to http://www.myurl.com/downloads/download.aspx? fileName=_destination
}
The code for download.aspx is outside the scope of my answer, as it varies per need and would just lengthen this post (A LOT MORE). But from what I've given, it will "work" for what you're looking for, but maybe not in exactly the way you expected. However, remember that this is primarily due to silverlight restrictions. What this approach does is rather than forcing you to need a pluging to view pdf files in your app, it allows the user computer to play it's part by using the existing adobe pdf reader. In silverlight, most printing, at least to my knowledge is done my using what you call and "ImageVisual" which is a UIElement. To print a pdf directly from silverlight, you need to either be viewing that PDF in a silverlight control, or ask a web service to render the PDF as an image and then place that image in a control. Only then could you print directly. I presented this approach as a lot more clean and direct approach.
One note - with the temp directory, i would recommend doing a clean up by some timespan of the files on the server side everytime a file is being added. Saves you the work of running some task periodically to check the folder and remove old files. ;)

How to modify an XML file present in a folder in the Silverlight project?

I'm trying to read & modify an XML file present in the Silverlight project from a view's code behind.
This is how I've read & modified the XML file:
StreamResourceInfo s = Application.GetResourceStream(new Uri("XML/Settings.xml", UriKind.Relative));
XElement doc = XElement.Load(s.Stream, LoadOptions.None);
IEnumerable<XElement> settingElement = (from b in doc.Descendants(
"setting")
select b).Take(1);
if (settingElement.Count<XElement>() > 0)
{
foreach (var node in newsIdNode)
{
node.Remove();
}
}
What I want to do now, is to save the XML file. I tried the following:
doc.Save(s.Stream, SaveOptions.None);
But got a runtime error that the stream is not writable.
How can I save changes to this XML file?
You can't- the stream is only for reading. If you want to save something consider isolated storage, saving to a file or persisting state via Web services.

File Uploading in Silverlight

I want to upload a particular file on server in Silverlight 4,
Simply, to upload any file we can use the "Browse" button.
When you click on this button we can get the file directory and choose any file & we can upload the particular file.
i have coded on browse button
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.ShowDialog();
fileDialog.Multiselect = true;
txtUploader.Text = fileDialog.File.DirectoryName;
fileDialog.File.CopyTo("C:/UploadedFiles");
}
here the problem is, only the dialog box is opening
not able to select multiple file,
not getting path,
not able to upload the file to specified location.
Try changing the order that you are setting up your OpenFileDialog Box.
Also you are returning a FileInfo object. If you are going to return multiple files you need use Files instead of File it will return a collection of FileInfo objects. You can then iterate over the collection to get your information. In testing out the code I was getting a Security Exception on reading the path of the files, you do not have the permissions needed to do what you want to do per #MattGreer's comment.
Edit added from #AnthonyWJones comment.
There is not any way to do what you are trying to do, except to create an OOB with elevated trust, and that will limit you to the users MyDocuments Folder.
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var fileDialog =new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.ShowDialog();
IEnumerable<System.IO.FileInfo> files = fileDialog.Files;
foreach (System.IO.FileInfo fi in files)
{
txtUploader.Text = fi.DirectoryName;
fi.CopyTo("C:/UploadedFiles");
}
}

Silverlight file upload - file is in use by another process (Excel, Word)

all. I have a problem with uploading of the file in Silverlight application. Here is a code sample. In case when this file is opened in other application (excel or word for example) it fails to open it, otherwise it's working fine. I'm using OpenFileDialog to choose the file and pass it to this function.
private byte[] GetFileContent(FileInfo file)
{
var result = new byte[] {};
try
{
using (var fs = file.OpenRead())
{
result = new byte[file.Length];
fs.Read(result, 0, (int)file.Length);
}
}
catch (Exception e)
{
// File is in use
}
return result;
}
Is there any way i can access this file or should i just notify the user that the file is locked?
You should notify the user that the file is currently in use by another program. If another program has the file open with a lock that does allow a shared read there is no way to bypass this lock.

Resources