I have an app that downloads an image to the phone and depending on the image category it will assign it to a news feed. I am using this function:
private static void DownloadImage(string furl, string ids)
{
// Connect Again to the API
WebClient client = new WebClient();
client.Headers["NewsID"] = ids;
string url = "www.xxx.com/image/xyz";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(url));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (e.Error == null && !e.Cancelled)
{
Stream reply = null;
StreamReader s = null;
// i am not able to read the sender who is a webclient to retrieve the information it is always skipping it
WebClient wcd = sender as WebClient;
reply = (Stream)e.Result;
s = new StreamReader(reply);
//Console.WriteLine(s.ReadToEnd());
s.Close();
reply.Close();
if (!myIsolatedStorage.DirectoryExists("ImageCache"))
{
myIsolatedStorage.CreateDirectory("ImageCache");
}
//try
//{//((MS.Internal.InternalMemoryStream)(e.Result)).FinalUri.Segments[2]
var graphImage = e.Result;
Random rand = new Random();
string fileName = string.Format("ImageCache/{0}.jpg", rand.Next());
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(image);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
//}
//catch (IsolatedStorageException ex)
//{
//IsolatedStorageException
//Exception handle appropriately for your app
//}
}
}
}
In the OpenReadComplete function which I'm using to download the image, I want to get the newsID from the header, and then assign it to the image before saving it into the database. I can't seem to access the header. Is this possible?
I think you can read it with sender.
WebClient c = (WebClient)sender;
string id = c.Headers["NewsID"];
Related
I followed the examples here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662940%28v=vs.105%29.aspx
I made the live preview and stuff work, but how can I take a picture? This is what i tried:
private PhotoCaptureDevice _photoCaptureDevice = null;
string strImageName = "IG_Temp";
private NokiaImagingSDKEffects _cameraEffect = null;
private MediaElement _mediaElement = null;
private CameraStreamSource _cameraStreamSource = null;
private Semaphore _cameraSemaphore = new Semaphore(1, 1);
MediaLibrary library = new MediaLibrary();
private async void ShutterButton_Click(object sender, RoutedEventArgs e)
{
if (_cameraSemaphore.WaitOne(100))
{
await _photoCaptureDevice.FocusAsync();
_cameraSemaphore.Release();
CameraCaptureSequence seq = _photoCaptureDevice.CreateCaptureSequence(1);
await seq.StartCaptureAsync();
MemoryStream captureStream1 = new MemoryStream();
// Assign the capture stream.
seq.Frames[0].CaptureStream = captureStream1.AsOutputStream();
try
{
// Set the position of the stream back to start
captureStream1.Seek(0, SeekOrigin.Begin);
// Save photo as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(strImageName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to the local folder.
while ((bytesRead = captureStream1.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
finally
{
// Close image stream
captureStream1.Close();
}
// Navigate to the next page
Dispatcher.BeginInvoke(() =>
{
NavigationService.Navigate(new Uri("/Edit.xaml?name=" + strImageName, UriKind.Relative));
});
}
}
But I will get an error:
System.InvalidOperationException
in line: await seq.StartCaptureAsync();
What am I doing wrong?
Not sure why, and two days of trying different things I'm getting nowhere. Keep getting the NRP at the WriteableBitmap line. You can see I've tried to both close and flush (and both together) the stream.
Any ideas would be appreciated.
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XDocument document = XDocument.Load(myIsolatedStorage.OpenFile("Selections.xml", FileMode.Open));
MyClass enclaves = (MyClass)serializer.Deserialize(document.CreateReader());
enclavesList.ItemsSource = enclaves.Collection1;
foreach (XElement xencl in document.Descendants("rest"))
{
WebClient downloader = new WebClient();
String theelement = xencl.Element("couplink").Value;
String nameElement = xencl.Element("coup").Value;
String uriring = theelement.ToString();
Uri uri = new Uri(uriring, UriKind.RelativeOrAbsolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(enclavesDownloaded);
downloader.DownloadStringAsync(uri);
Random random = new Random();
int randomNumber = random.Next(0, 100);
using (IsolatedStorageFile newIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
String tempJPEG = randomNumber.ToString();
IsolatedStorageFileStream fileStream = newIsolatedStorage.CreateFile(tempJPEG);
//fileStream.Close();
//fileStream.Flush();
BitmapImage image = new BitmapImage(new Uri("" + uri ));
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
}
}
I've googled till I'm blind and not sure what to do now.
Thanks in advance all you folks.
Add handlers to the image before the "new BitmapImage" line, like so:
this.Image.ImageOpened += ImageOpened;
this.Image.ImageFailed += ImageFailed;
Then, in the ImageOpened event, save to the WriteableBitmap:
private void ImageOpened(object sender, RoutedEventArgs e)
{
WriteableBitmap wb = new WriteableBitmap((BitmapImage)sender);
using (IsolatedStorageFile newIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
String tempJPEG = randomNumber.ToString();
IsolatedStorageFileStream fileStream = newIsolatedStorage.CreateFile(tempJPEG);
//fileStream.Close();
//fileStream.Flush();
BitmapImage image = new BitmapImage(new Uri("" + uri ));
image.CreateOptions = BitmapCreateOptions.None;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
}
You are currently attempting to save the image before it has loaded, hence the null pointer exception.
Posting this for all who have tried to download multiple images to isolated storage and keep the names of the file on the WP. Notice that it requires a url path with the file name from the xml file that is first downloaded, strips the path then saves the file with the original name.
Borrowed some code (Thanks to all, especially philorube), wrote other and cursed a LOT to get here, but it works.
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
XDocument document = XDocument.Load(myIsolatedStorage.OpenFile("Selections.xml", FileMode.Open));
MyClass enclaves = (MyClass)serializer.Deserialize(document.CreateReader());
foreach (var xe in document.Descendants("couplink"))
{
mane = xe.Value.ToString();
WebClient webClient = new WebClient();
Uri uri = new Uri(mane, UriKind.RelativeOrAbsolute);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync((uri),mane);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
int count;
Stream stream = e.Result;
byte[] buffer = new byte[1024];
String imgName = (string)e.UserState;
String cleanImgName = System.IO.Path.GetFileName(imgName);
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(cleanImgName, FileMode.Create, isf))
{
count = 0;
while (0 < (count = stream.Read(buffer, 0, buffer.Length)))
{
isfs.Write(buffer, 0, count);
}
stream.Close();
isfs.Close();
}
}
Please Help! I've tried everything, i dont know what else to do. I just want to upload an image that the user chooses from their library to my websever.
I already have a code that uses webclient to upload to a url.
private void OnChoosePicturel(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("URL");
WebClient wc = new WebClient();
NetworkCredential g = new NetworkCredential();
g.UserName = "USERNAME";
g.Password = "PASSWORD";
wc.Credentials = g;
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
try
{
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
}
catch(Exception t)
{
}
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "STOR");
}
The problem is , the webclient class only works for "http" urls, but i need to connect and upload the file to an "ftp" url. How do i do this? Ive tried EVERYTHING. Nothing works.
So i have the following code:
WebClient webClient = new WebClient();
Stream data = webClient.OpenRead("http://awesomeurl.com/file.zip");
UnzipFromStream(data, #"c:/dir/");
And i would like to have the data of that stream in a progress bar, just like if you would use WebClient with .DownloadProgressChanged
I cant however seem to figure out how to make it work...
Please note: i am using ICSharpCode.SharpZipLib
UPDATE #1.1
Ok, i managed to get the following code to work (it downloads and unzips + the complete msg is shown), however the progress bar is not updating:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// first, we need to get the exact size (in bytes) of the file we are downloading
Uri url = new Uri(filename);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
// gets the size of the file in bytes
Int64 iSize = response.ContentLength;
// keeps track of the total bytes downloaded so we can update the progress bar
Int64 iRunningByteTotal = 0;
string outFolder = folder;
// use the webclient object to download the file
using (System.Net.WebClient webClient = new WebClient())
{
// open the file at the remote URL for reading
using (System.IO.Stream zipStream = webClient.OpenRead(filename))
{
ZipInputStream zipInputStream = new ZipInputStream(zipStream);
ZipEntry zipEntry = zipInputStream.GetNextEntry();
while (zipEntry != null)
{
String entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
// Manipulate the output filename here as desired.
String fullZipToPath = Path.Combine(outFolder, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath))
{
int iByteSize = 0;
byte[] buffer = new byte[iSize]; // 4K is optimum
StreamUtils.Copy(zipInputStream, streamWriter, buffer);
while ((iByteSize = zipStream.Read(buffer, 0, buffer.Length)) > 0)
{
iRunningByteTotal += iByteSize;
// calculate the progress out of a base "100"
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)iSize;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
// update the progress bar
backgroundWorker1.ReportProgress(iProgressPercentage);
}
}
zipEntry = zipInputStream.GetNextEntry();
}
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("File download complete");
}
Im trying to get Images from URL and store it within my isolated storage, and then get the images from the isolated storage
here is my relevant code:
public void GetImages()
{
string uri = "http://sherutnetphpapi.cloudapp.net/mini_logos/" + path;
WebClient m_webClient = new WebClient();
imageUri = new Uri(uri);
m_webClient.OpenReadAsync(imageUri);
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_ImageOpenReadCompleted);
m_webClient.AllowReadStreamBuffering = true;
}
void webClient_ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
string iso_path = "~/SherutApp1;component/" + path;
var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, FileMode.Create, isolatedfile))
{
byte[] buffer = new byte[e.Result.Length];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
i get the exception at the headline on this line:
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, FileMode.Create, isolatedfile))
I don't know what is the problem, although i think that maybe images does not inserted correctly to the isolated storage.
I don't think you need the "~/SherutApp1;component/" part in there. If you the entire path is "test.jpg" or "folderThatExists\\test.jpg" it should work.