there was a lot of question about this error, but i couldn't find the problem i'm facing with it.
I have 2 buttons: 1 to save some string into the isolatedStorage, and 1 to read it.
when i try to read it i get the errorMessage written in the title.
Button1.Click is:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
System.IO.FileMode.Append,
System.IO.FileAccess.ReadWrite,
store))
{
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine("something");
writer.Close();
stream.Close();
}
and the Button 2:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
System.IO.FileMode.Open,
System.IO.FileAccess.ReadWrite,
store))
{
StreamReader sr = new StreamReader(stream);
string text = sr.ReadToEnd();
MessageBox.Show(text);
sr.Close();
stream.Close();
}
The problem you are facing is connected with the fact that as MSDN says::
FileMode.Append can only be used in conjunction with Write.
So it will work if you had changed it to:
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
FileMode.Append, FileAccess.Write, store))
On the other hand you don't need to close stream when you have it in using(), after leaving using() the steream is Disposed automatically. And it will better to put StreamWriter also into using():
private void first_Click(object sender, RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt", FileMode.Append, FileAccess.Write, store))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine("something");
}
}
private void second_Click(object sender, RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt", FileMode.Open, FileAccess.ReadWrite, store))
using (StreamReader sr = new StreamReader(stream))
{
string text = sr.ReadToEnd();
MessageBox.Show(text);
}
}
Related
I'm having 10 image urls. I want to download those images and htmls to local folder and replace the image paths in corresponding image source of htmls. How to download 10 images from urls. below code for single image download.
var webClient = new WebClient();
webClient.OpenReadCompleted += WebClientOpenReadCompleted;
webClient.OpenReadAsync(new Uri(webimages["image url"], UriKind.Absolute));
void WebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
const string tempJpeg = "TempJPEG";
var streamResourceInfo = new StreamResourceInfo(e.Result, null);
var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication();
if (userStoreForApplication.FileExists(tempJpeg))
{
// userStoreForApplication.DeleteFile(tempJpeg);
MessageBox.Show("Image Already Exists");
}
var isolatedStorageFileStream = userStoreForApplication.CreateFile(tempJpeg);
var bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
bitmapImage.SetSource(streamResourceInfo.Stream);
var writeableBitmap = new WriteableBitmap(bitmapImage);
writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);
isolatedStorageFileStream.Close();
isolatedStorageFileStream = userStoreForApplication.OpenFile(tempJpeg, FileMode.Open, FileAccess.Read);
// Save the image to the camera roll or saved pictures album.
var mediaLibrary = new MediaLibrary();
// Save the image to the saved pictures album.
mediaLibrary.SavePicture(string.Format("SavedPicture{0}.jpg", DateTime.Now), isolatedStorageFileStream);
isolatedStorageFileStream.Close();
}
In my application I have a map for which the first thing I do (on launching) is to add a custom MapLayer (which I populate with many MapOverlays/pushpins).
When I browse to another page of the app and then return to the map page, everything (ie the MapLayer that was drawn on my map) is gone.
It takes time to add it all over again each time the user navigates to the map page so I would like it to be fixed, drawn/added just once.
Any suggestions?
edit, added the code [I removed some details, the structure remains the same]:
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}
You can try to create your MapLayer as a public property in App.xaml.cs and set it only when your app is running first time.
Then create an instance of app inside page with your map and add your MapLayer to your Map layers inside OnNavigatedTo event.
Define a flag in app level. here is the sample
// In App.xaml.cs
public static bool IsLaunched = false;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsLaunched =true;
}
//In your map screen
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(App.IsLaunched)
{
drawStations();
//Set App flage to false
App.IsLaunched = false;
}
}
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}
I need to do the following:
Convert base64 image string into Bitmapimage
from BitmapImage in (1), convert it to byteArray
The problem:
how to solve the step(2)
Your help is greatly appreciated. Thanks
public async Task Base64StringToBitmap(string Base64source,string Filenm)
{
var bytes = Convert.FromBase64String(Base64source);
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
ims.Seek(0);
//----- Create Bitmapimage ---------------
var bm = new BitmapImage();
bm.CreateOptions = BitmapCreateOptions.None;
bm.SetSource(ims);
// Update : added this
byte[] pixelBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wb = new WriteableBitmap(200, 300);
wb.SetSource(ims);
//-- Problem here :
Stream stm = wb.PixelBuffer.AsStream();
int len = (int)stm.Length;
byte[] pixels = new byte[len];
await stm.ReadAsync(pixels, 0, pixels.Length);
stm.CopyTo(ms);
pixelBuffer = ms.ToArray();
}
}
Check this method
public static byte[] ConvertToBytes(BitmapImage bitmapImage)
{
byte[] data = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
ms .Seek(0, SeekOrigin.Begin);
data = stream.GetBuffer();
}
return data;
}
I want to update my live tile by creating and saving a writable bitmap image in scheduled task agent.my code works inside the app but in background task, it breaks into the debugger
I'm using this simple code:
protected override void OnInvoke(ScheduledTask task)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif
CreateWideTile();
NotifyComplete();
}
and my code to create and save image is this:
private void CreateWideTile()
{
int width = 691;
int height = 336;
string imagename = "WideBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
//Created background color as Accent color
SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "Example text";
textBlock.FontWeight = FontWeights.Normal;
textBlock.TextAlignment = TextAlignment.Left;
textBlock.Margin = new Thickness(20, 20, 0, 0);
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
when I test the app, after executing background task, an error comes that point to Debugger.Break();
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
I don't understand the reason. my code works in foreground app but not in background ...
any solution ????
You should use dispatcher, because WriteableBitmap.Render should be used in the UI thread:
protected override void OnInvoke(ScheduledTask task)
{
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
CreateWideTile();
NotifyComplete();
} );
}
I'm using WriteableBitmap.Render to convert an InkPresenter control to a byte array and Image.
This is my code:
var bitmap = new WriteableBitmap(element, null);
bitmap.Render(element, null);
bitmap.Invalidate();
BitmapImage img;
using (var ms = new MemoryStream())
{
bitmap.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 85);
// byte[] bytes = ms.ToArray();
img = new BitmapImage();
img.SetSource(ms);
}
If I save the result (byte array or Image) into IsoladtedStorage, the Image has the correct size but is only black.
I don't have an idea why it does not work because I've already used this method with the Map control.
using (var stream = new MemoryStream())
{
WriteableBitmap dd = new WriteableBitmap(ink, null);
dd.SaveJpeg(stream, dd.PixelWidth, dd.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var ml = new MediaLibrary();
ink.Background = new SolidColorBrush(Colors.White);
ml.SavePicture(string.Format("Images\\{0}.jpg", Guid.NewGuid()), stream);
ink.Background = new SolidColorBrush(Colors.Transparent);
}