Operation not permitted on IsolatedStorageFileStream in WP7 - c#

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.

Related

Windows Phone - Save multiples files IsolatedStorage

My application, the file is downloaded from web server and is saved in IsolatedStorage(with same name from web file).
So, i want save multiple files on IsolatedStorage, from multiple URLs. What better way to do it?
private void sinc(object sender, EventArgs e)
{
client = new WebClient();
url = "http://infassteste.url.ph/json.html";
Uri uri = new Uri(url);
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(uri);
}
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
string strFileName = url.Substring(url.LastIndexOf("/") + 1, (url.Length - url.LastIndexOf("/") - 1));
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
// Path Storage
// *** If File Exists
if (isoStore.FileExists(strFileName))
{
isoStore.DeleteFile(strFileName);
}
IsolatedStorageFileStream dataFile = new IsolatedStorageFileStream(strFileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, isoStore);
long fileLen = e.Result.Length;
byte[] b = new byte[fileLen];
e.Result.Read(b, 0, b.Length);
dataFile.Write(b, 0, b.Length);
dataFile.Flush();
object lenghtOfFile = dataFile.Length;
MessageBox.Show("Arquivo salvo!");
}
Collect all URIs to
List<URI> urls = new List<URI>();
Then go trough them using foreach loop and save files
foreach(Uri uri in urls)
{
// save files... perhaps client.OpenReadAsync(uri); ?
}

WP8 take picture with Nokia Imaging API (real time filter) and save to IsolatedStorage

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?

Null Reference Pointer error at WriteableBitmap when trying to save image in WP7

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();
}
}

How to store and get images in IsolatedStorage?

I want to be able to save images in IsolatedStorage, and later get it.
for this purpose I wrote a helper which I want to access it from everywhere in my app:
for creating an image:
public static void SaveImage(Stream image, string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!isolatedStorage.DirectoryExists("MyImages"))
{
isolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, isolatedStorage))
{
StreamWriter sw = new StreamWriter(fileStream);
sw.Write(image);
sw.Close();
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
and for getting that image again:
public static BitmapImage Get(string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, isolatedStorage))
{
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);
return image;
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
The problem appears when I try to set source of image I get this error message:
The component cannot be found. (Exception from HRESULT: 0x88982F50)
Assuming you have the right Capabilities under your WMAppManifest.xml what you need is:
public static void SaveImage(Stream image, string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("MyImages"))
{
myIsolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}
That should work and store your image as a jpeg into your desired directory. if it doesn't, make sure that the create directory and Path.Combine() methods are being used correctly.

Accessing the header in OpenReadCompleted Method on windows phone 8

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"];

Categories

Resources