How to download and upload file to SkyDrive via Live Connect SDK - c#

I have an app that I want to download & upload a simple .txt file with a URL inside. I have downloaded Live Connect SDK V5.4, referenced the documentation, but it appears that the documentation is incorrect. The sample code uses event handlers for when a download/upload is complete, but that no longer can be used in V5.4.
I have two methods, downURL & upURL. I have started working on downURL:
private async void downURL()
{
try
{
LiveDownloadOperationResult download = await client.DownloadAsync("URL.txt");
}
catch { }
}
I am not sure what I am suppose to use for the path, I put "URL.txt" for now, I've seen some examples with "/me/". Do I need this? The file does not need to be visible to the user, as the user can't really do anything with it, but it is vital for the app to work.
My question is how do I use the LiveDownloadOperationResult download to save the file to Isolated Storage Settings, get the text contents, and put that in a string? Also, if you know how to upload the file back up, the upload event handler looks the same (but without the Result variable).

This code help you download content a file which you want. It get content have format OpenXML
Here, "item.id" is Id of "URL.txt".
private async void downURL()
{
try
{
LiveDownloadOperationResult operationResult = await client.DownloadAsync(item.id + "/Content?type=notebook");
StreamReader reader = new StreamReader(operationResult.Stream);
string Content = await reader.ReadToEndAsync();
}
catch { }
}

Related

Windows 10 UWP App XElement.Save() "Access is denied" exception

I'm writing a Windows 10 UWP App, and I'm hitting a snag. I have a Settings.xml in the root of the app folder that I will use to store the DB connection information, as well as a few ancillary settings. I can load the XML fine, and my function to edit works (I can extract the XML through debug and see the changes). My problem comes when trying to write the edited file. I understand that I don't have direct access to the file system with UWP, however I've tried several different methods I've found online to work within my constraints and still can't find one that works. I always come back with an "Access is denied" error in some form or another. Here is a snippet of what my Save function looks like right now. Any help would be greatly appreciated.
try
{
XElement xmlSettings = XElement.Load(uri: "Settings.xml");
XElement xmlNode;
//Do Stuff (clipped for brevity).
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(desiredName: "Settings.xml", options: CreationCollisionOption.ReplaceExisting);
Stream stream = await file.OpenStreamForWriteAsync();
xmlSettings.Save(stream);
Error = "";
}
catch (Exception e)
{
Error = "SaveSettings";
}
I added an xml file to my solution (in the root) and copy pasted your code.
It runs the first time, but gets the exception the second time. The reason is that your stream is not closed. You should use it with using:
using (Stream stream = await file.OpenStreamForWriteAsync())
{
xmlSettings.Save(stream);
}
With this change the code worked even the second time.

Process cannot access the file exception

As it was common to guess what kind of reason for this exception. But let me explain the exact scenario which am facing . Please find the overview of my code block.
Task.Factory.StartNew(()=> Method1());
private void Method1()
{
//A process which loads the file and uploads it to server. If the file was large, it will take some amount of time.
using (var fileStream = System.IO.File.OpenRead(filePath))
{
//Upload file
}
//Once uploads deletes from local.
File.Delete(path);
}
Before uploading the file delete method was called as I have used separate tasks . So I get the exception that process cannot access the file.
I should delete the file once upload was over. Need some suggestions on that.
TPL Continuewith
you can also make use of contnuewith over here because
you want to updload file
once update done you want to delete file
than you can do this
Task t =Task.Factory.StartNew(()=> Method1());//remove delete file form method one
t.ContinueWith((as)=> {File.Delete(path);} );
there might be syntax error in above code so please solve it in visual studio
Singling Construct
As you are updloading and delete file on different threds that I suggest you
make use of signaling construct
public class test
{
private static AutoResetEvent event_2 = new AutoResetEvent(false);
public void uploadfile()
{
///do file updating
//than give signale
event_2.set();
}
public void deletefile()
{
event_2.WaitOne();
//delete file
}
}
it doesn't seem thread issue , it look like file you want to delete is not present so its better you check file exists or not by file exits method
if (File.Exists(path))
{
File.Delete(path);
}

Sending file(s) to my PHP script via C#

I have been working on my first C# application lately and I finished working on the interface - it's perfect.
Now I am stuck at the part where I get an Open File dialog and then send that file to my PHP script located on localhost (wamp).
This is what I've been trying to do:
private void menu_upload_file_Click(object sender, EventArgs e)
{
DialogResult dialogOpened = openFileDialog1.ShowDialog();
if (dialogOpened == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
using (var client = new WebClient())
{
client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename);
}
}
}
Nothing is happening and the file is not being sent (copied over) to my desired location.
You might understand that I am succeeding on opening the Open File dialog, but I have no clue if I am catching the filename/directory and send it over to my website so it can deal with it.
Maybe the url is complicated? I need to send those submit and action parameters or the script wont load.
OH AND: In PHP, the $_FILES array MUST BE named images ($_FILES['images']), maybe this is the problem? (thought of this while asking here).
So what is the problem that the file is not being sent to my website?
Assuming the client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename); is not throwing an exception try to look at the response.
var response = client.UploadFile("http://dugi/imgitv3/upload.php?submit=true&action=upload", "POST", filename);
Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
System.Text.Encoding.ASCII.GetString(response));
The problem was in my PHP script. I was always looking for $_FILES['images'] there and nothing else. Then after some googles, I noticed that C# sends the file array named with file ($_FILES['file']).
I did the necessary changes in my PHP script and now everything is working.

How to identify whether a download is completed using an ashx handler

In one of our project we need the functionality to download a file from server to client location.
For this we are using an ashx handler to do the operation. Its working perfectly and we are able to download files.
Now we need a requirement like we need to update a field when a download is started and completed. Is there any way to do this.
Once we click the download link the Save as dialog box will appear and after that i think we don't have any control to check the progress. I think we even don't know which button is clicked ie we don't know whether the user is clicked a 'Yes' or 'No'.
Can anyone please suggest a method to know when the download is started and when it has been completed? We are using Asp.Net 2.0 with c#.
The handler used for download is given below
string fileUrl = string.Empty;
if (context.Request["fileUrl"] != null)
{
fileUrl = context.Request["fileUrl"].ToString();
}
string filename = System.IO.Path.GetFileName(fileUrl);
context.Response.ClearContent();
context.Response.ContentType = "application/exe";
context.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", filename));
context.Response.TransmitFile(fileUrl);
context.Response.Flush();
The file is downloaded from an aspx page method like
private void DownloadExe()
{
string downloadUrl = "Test.exe");
Response.Redirect("Test.ashx?fileUrl=" + downloadUrl, false);
}
Your ASHX handler knwos if download started (since it is actually get called) and when download is completed (end of handler is reached). You may even get some progress server side if you are writing response manually in chunks, this way you also may be able to detect some cases when user cancels download (if writing to response stream fails at some point).
Depending on your needs you may be able to transfer this information to other pages (i.e. via session state) or simply store in some database.
How about this:
Response.BufferOutput = false;
Response.TransmitFile(fileUrl);
//download complete code
If you disable response output buffering then it won't move past the line of code that sends the file to the client until the client has finished receiving it. If they cancel the download half way through it throws a HttpException so the download complete code doesn't get run.
You could also place your download complete code after your call to flush the buffer. But it's better not to enable buffering when sending large binary files to save on server memory.
Ok I had the same problem and jumped over this site:
Check over coockies
This works great for me.

How to play music in Metro using file URL mechanism

I need to play Music Library files using file URL, that I will set to MediaPlayer object in a XAML c# object.
I constructed URI as followed
StorageFile file = await KnownFolders.MusicLibrary.GetFileAsync(track.Id);
return new Uri("file:///" + file.Path);
URI looks like this: streamingUri = {file:///C:/Users/user/Music/04 - A Train Makes A Lonely Sound.mp3}
I need URL based scheme to play so that I can reuse same logic for web streaming too.
How do I make this work?
Take a look at
this sample. It should give you some ideas of how to do media playback from file.
While I notice you are saying you need a URI-based, you should use a stream for a local file. The only part you need to extract is a call to set the MediaElement's Source. You can just make a function with 2 overrides and it should be relatively clean.
So, for a web stream:
void SetMediaElementSource(Uri webStreamUri)
{
MyMediaElement.Source = webStreamUri;
}
And for a local file:
void SetMediaElementSource(StorageFile file)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
MyMediaElement.SetSource(stream, file.ContentType);
}

Categories