WebClient - Saving a downloaded file to disk - silverlight

In Silverlight 4 has anyone tried to download a file using the WebClient (read or string method, does not matter) and save it to disk? (using File or FileStream class, again does not matter)
I have been trying to get this to work with no luck, for some reason the file downloads fine, while in memory the string length of it seems to match the downloaded file, yet when it gets to disk its almost twice as big and obvious corrupt :(.
To reproduce simply create a SL4 OOB applicatoin, use a WebClient to download an MP3 of your choice and save it to disk using lets say the FileStream class. If tihs works for you, please post a sample!

try this sample, in a OOB Elevated Trust Application:
private void download_Click(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://www.yourdomain.com/test.txt", UriKind.Absolute));
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if ((bool)sfd.ShowDialog())
{
StreamReader sr = new StreamReader(e.Result);
string str = sr.ReadToEnd();
StreamWriter sw=new StreamWriter(sfd.OpenFile());
sw.Write(str);
}
}

Related

AxInterop.ShockwaveFlashObjects missing in COM objects

I am trying to run SWF game in my WPF application. This game accepts some variables which should be constantly updated (about 100 times a second). I did some research and I know that basically there are 2 possibilities to run SWF in WPF:
Embed WebBrowser and pass path to the SWF file.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// fixes warning about ActiveX security
string C_Drive_local = "file://127.0.0.1/c$/";
// path of the flash file, here its in C:\DemoContent\bounce.swf
Uri swfPath = new Uri( C_Drive_local + "DemoContent/bounce.swf");
// load it in the browser
MySWFBrowser.Source = swfPath;
}
Use WindowsFormsHost to host an AxShockwaveFlash control
private void FlashLoaded(object sender, RoutedEventArgs e)
{
WindowsFormsHost formHost = new WindowsFormsHost();
AxShockwaveFlash axShockwaveFlash = new AxShockwaveFlash();
formHost.Child = axShockwaveFlash;
mainGrid.Children.Add(formHost);
string flashPath = Environment.CurrentDirectory;
flashPath += #"\game.swf";
axShockwaveFlash.Movie = flashPath;
}
I would like to try with AxShockwaveFlash since it provides methods for setting variables but in my COM objects I can not see AxInterop.ShockwaveFlashObjects.dll
I tried to install several different versions of Flash Player but without success. I cannt find any information about it. How can I get AxInterop.ShockwaveFlashObjects.dll ? What should I install to have it?

How do I extract zip file in Windows Phone 7?

I have a zip file in my Windows Phone 7 project. I have set the Build Action to Content and Copy to output directory to Always. The zip file contains the folder structure. I want this to be copied entirely as it is in my Phone Project. I am using SharpZipLib for this. This is the code :-
Stream stremInfo = Application.GetResourceStream(new Uri("xip.zip", UriKind.Relative)).Stream;
new FastZip(). ExtractZip(stremInfo,
"",FastZip.Overwrite.Always,null,null,null,true,true);
However I get error when ExractZip is called. The exception I get is "MethodAccessException". Cannot call GetFullPath(). Can anybody let me know what am I missing? What can I do to avoid it?
You dont need to use another library if you know what files you want out of the Zip. You can use the App.GetResourceStream phone API to reach into the Zip and get the file.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("http://www.foo.com/pictures.zip"));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamResourceInfo info = new StreamResourceInfo(e.Result,"");
StreamResourceInfo pic = App.GetResourceStream(info, new Uri("IMG_1001.jpg", UriKind.Relative));
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(pic.Stream);
img.Source = bitmap;
}
For more informaiton on reading the list of files from th Zip check out this blog post.
Check out this utility, it may help you out.
http://www.sharpgis.net/post/2009/04/22/REALLY-small-unzip-utility-for-Silverlight.aspx
I've used the SL port of the SharpZipLib to do this - see http://slsharpziplib.codeplex.com/
There's lots of example code available for how to use it - and a good quickstart in their source - http://slsharpziplib.codeplex.com/SourceControl/changeset/view/75568#1416103

synchronizing webClient download (silverlight)

so I have this function which gets called multiple times during my program.
//global variable
BitmapImage img;
private void LoadImageFile(string ImageName)
{
WebClient ImageClient = new WebClient();
ImageClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ImageFileLoaded);
xmlClient.DownloadStringAsync(new Uri("/images/"+ImageName, UriKind.RelativeOrAbsolute));
}
void ImageFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
img.set = e.Result;
}
}
the following code uses the new value of "img" so I want it to start only after img has been assigned the new source but it seems that it runs before that happens
You want to use WebClient.OpenReadAsync() instead of WebClient.DownloadStringAsync() because you want to read a binary image, not a string.
Then when you get the stream, you call BitmapImage.SetSource() using that stream.
I would check out this blog by Jeremy Likness.
It uses corountines to help organise async requests. I have used this approach and have dealt with similar issues where I want actions to occur after several async tasks.

Silverlight Windows Phone 7: Load Images From URL

I got the code below that is trying to load an image from the web into an Image control, when I run it I get an error on the given line that no network access is allowed:
private void button1_Click(object sender, RoutedEventArgs e)
{
WebClient webClientImgDownloader = new WebClient();
webClientImgDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(webClientImgDownloader_OpenReadCompleted);
webClientImgDownloader.OpenReadAsync(new Uri("http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif", UriKind.Absolute));
}
void webClientImgDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result); // ERROR HERE!
image1.Source = bitmap;
}
Silverlight for Windows Phone 7
Trying to download content with WebClient will require a client access policy file to be present on the source server. For images you can avoid this requirement by doing it like this:-
private void button1_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif", UriKind.Absolute)
image1.Source = new BitmapImage(uri);
}
I see you're retrieving the image from Dilbert.com does that site have a cross domain policy file?
Silverlight doesn't support GIF only JPG, so I wrote:
www.lenniedevilliers.net/displaygif.aspx?link=http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif
the displaygif.aspx page convert the GIF into a JPG.
Can you give us the full exception stack trace? the error could be that your phone emulator does not have internet access, or it could be the image on the dilbert server that does not allow anonymous requests that did not originate from their site ... so guidance on a solution will differ :-)

How can a silverlight app download and play an mp3 file from a URL?

I have a small Silverlight app which downloads all of the images and text it needs from a URL, like this:
if (dataItem.Kind == DataItemKind.BitmapImage)
{
WebClient webClientBitmapImageLoader = new WebClient();
webClientBitmapImageLoader.OpenReadCompleted += new OpenReadCompletedEventHandler(webClientBitmapImageLoader_OpenReadCompleted);
webClientBitmapImageLoader.OpenReadAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem);
}
else if (dataItem.Kind == DataItemKind.TextFile)
{
WebClient webClientTextFileLoader = new WebClient();
webClientTextFileLoader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientTextFileLoader_DownloadStringCompleted);
webClientTextFileLoader.DownloadStringAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem);
}
and:
void webClientBitmapImageLoader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
DataItem dataItem = e.UserState as DataItem;
CompleteItemLoadedProcess(dataItem, bitmapImage);
}
void webClientTextFileLoader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
DataItem dataItem = e.UserState as DataItem;
string textFileContent = e.Result.ForceWindowLineBreaks();
CompleteItemLoadedProcess(dataItem, textFileContent);
}
Each of the images and text files are then put in a dictionary so that the application has access to them at any time. This works well.
Now I want to do the same with mp3 files, but all information I find on the web about playing mp3 files in Silverlight shows how to embed them in the .xap file, which I don't want to do since I wouldn't be able to download them dynamically as I do above.
How can I download and play mp3 files in Silverlight like I download and show images and text?
You would download the MP3 as binary stream and store the result in a byte array. Its this byte array you would store in your dictionary.
At the point that you want to assign the byte array to a MediaElement you would use code like this:-
void SetMediaElementSource(MediaElement me, byte[] mp3)
{
me.SetSource(new MemoryStream(mp3));
}

Resources