How to save data in xml file in windows phone 7 - windows-phone-7

Hello Everyone,
I am working on an application in which i need to save some data in IsolatedStorage .
while my application is running i am able to see data from file. Once i close my application and restarting my application its not showing my data.
public static IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
public static IsolatedStorageFileStream xyzStrorageFileStream = new IsolatedStorageFileStream("/category.xml", System.IO.FileMode.OpenOrCreate, isstore);
public static XDocument xmldoc = XDocument.Load("category.xml");
favouriteDoc.Save(rssFavouriteFileStream);
rssFavouriteFileStream.Flush();
Any one having any idea? How to do this?

In order to save structured data you need to use XML Writer or XML Serializer.
For example to save data:
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("People2.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartElement("p", "person", "urn:person");
writer.WriteStartElement("FirstName", "");
writer.WriteString("Kate");
writer.WriteEndElement();
writer.WriteStartElement("LastName", "");
writer.WriteString("Brown");
writer.WriteEndElement();
writer.WriteStartElement("Age", "");
writer.WriteString("25");
writer.WriteEndElement();
// Ends the document
writer.WriteEndDocument();
// Write the XML to the file.
writer.Flush();
}
}
}
To read it back:
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("People2.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.tbx.Text = reader.ReadToEnd();
}
}
}
catch
{ }
Answer is taken from this article, so all the credits go to WindowsPhoneGeek. Also, see other examples in the aforementioned article header.

Related

Change Content Type for files in Azure Storage Blob

I use only Microsoft Azure Storage and no other Azure products/services. I upload files to my storage blob via ftp type client (GoodSync), and I need to change the content type of all the files based on their file extension after they are already in the Blob. I have looked around and have not found out how to do this without having one of their VPS with PowerShell. What are my options and how do I accomplish this? I really need step by step here.
I recently had the same issue so I created a simple utility class in order to "fix" content type based on file's extension. You can read details here
What you need to do is parse each file in your Azure Storage Containers and update ContentType based on a dictionary that defines which MIME type is appropriate for each file extension.
// Connect to your storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
// Load Container with the specified name
private CloudBlobContainer GetCloudBlobContainer(string name)
{
CloudBlobClient cloudBlobClient = _storageAccount.CreateCloudBlobClient();
return cloudBlobClient.GetContainerReference(name.ToLowerInvariant());
}
// Parse all files in your container and apply proper ContentType
private void ResetContainer(CloudBlobContainer container)
{
if (!container.Exists()) return;
Trace.WriteLine($"Ready to parse {container.Name} container");
Trace.WriteLine("------------------------------------------------");
var blobs = container.ListBlobs().ToList();
var total = blobs.Count;
var counter = 1;
foreach (var blob in blobs)
{
if (blob is CloudBlobDirectory) continue;
var cloudBlob = (CloudBlob)blob;
var extension = Path.GetExtension(cloudBlob.Uri.AbsoluteUri);
string contentType;
_contentTypes.TryGetValue(extension, out contentType);
if (string.IsNullOrEmpty(contentType)) continue;
Trace.Write($"{counter++} of {total} : {cloudBlob.Name}");
if (cloudBlob.Properties.ContentType == contentType)
{
Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (skipped)");
continue;
}
cloudBlob.Properties.ContentType = contentType;
cloudBlob.SetProperties();
Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (reset)");
}
}
_contentTypes is a dictionary that contains the appropriate MIME type for each file extension:
private readonly Dictionary _contentTypes = new Dictionary()
{
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg" }
};
Full list of content types and source code can be found here.
Here you are a refreshed version for latest Azure.Storage.Blobs SDK. I'm using .Net 5 and console app.
using Azure.Storage.Blobs.Models;
using System;
using System.Collections.Generic;
using System.IO;
var contentTypes = new Dictionary<string, string>()
{
{".woff", "font/woff"},
{".woff2", "font/woff2" }
};
var cloudBlobClient = new BlobServiceClient("connectionstring");
var cloudBlobContainerClient = cloudBlobClient.GetBlobContainerClient("fonts");
await cloudBlobContainerClient.CreateIfNotExistsAsync();
var blobs = cloudBlobContainerClient.GetBlobsAsync();
await foreach (var blob in blobs)
{
var extension = Path.GetExtension(blob.Name);
contentTypes.TryGetValue(extension, out var contentType);
if (string.IsNullOrEmpty(contentType)) continue;
if (blob.Properties.ContentType == contentType)
{
continue;
}
try
{
// Get the existing properties
var blobClient = cloudBlobContainerClient.GetBlobClient(blob.Name);
var properties = await blobClient.GetPropertiesAsync();
var headers = new BlobHttpHeaders
{
ContentType = contentType,
CacheControl = properties.CacheControl,
ContentDisposition = properties.ContentDisposition,
ContentEncoding = properties.ContentEncoding,
ContentHash = properties.ContentHash,
ContentLanguage = properties.ContentLanguage
};
// Set the blob's properties.
await blobClient.SetHttpHeadersAsync(headers);
}
catch (RequestFailedException e)
{
Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}

storing a project folder in isolated storage

I am creating a windows phone project with static html files in a folder called "webapplication". i want to store all contents of "webapplication" folder in the isolated storage. Can some one help to resolve this?
Check out windows phone geek at http://windowsphonegeek.com/tips/all-about-wp7-isolated-storage-files-and-folders for information on Isolated Storage.
To create a folder do the following:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
myIsolatedStorage.CreateDirectory("NewFolder");
If you want to create a file inside the folder then:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
If you are looking to copy the files to IsolatedStorage, then you need to run the following code the 1st time your application executes:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = System.IO.Directory.GetFiles(folderPath);
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile("NewFolder\\SomeFile.txt", FileMode.CreateNew, Storage))
{
int chunkSize = 102400;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}

how to save a variable include image into isolate storage in windowsphone

i've been doing a essay about windowsphone. i created a address variable include a uri to add a image into address. There is a error when i use Isolate storage to save data. I don't know why.
Please help me!
Thank you so much.
class Address
{
private string name;
private Uri icon;
.....
}
......
public void save()
{
XmlWriterSettings xmlwritersetting = new XmlWriterSettings();
xmlwritersetting.Indent = true;
using (IsolatedStorageFile myisolatedstiragefile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myisolatedstiragefile.FileExists(filename))
{
myisolatedstiragefile.DeleteFile(filename);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, System.IO.FileMode.OpenOrCreate, myisolatedstiragefile))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Adress>));
using (XmlWriter writer = XmlWriter.Create(stream, xmlwritersetting))
{
serializer.Serialize(writer, listadress);
}
}
}
}
It's a little difficult for me to understand your question, but I'll try. You really should indicate what error you specifically get in the debugger and where it occurs.
But just by looking, it seems that you might be trying to use the XmlSerializer to write binary image data to iso-storage and that probably won't work. You can find many examples of using iso-storage for various purposes including writing image files here:
http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images
For example, it shows that you can save a JPG image to isolated storage by doing this:
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
if (myIsolatedStorage.FileExists(tempJPEG)) {
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close();
}

Operation not permitted on IsolatedStorageFileStream

using (EntityDataContext amdb = new EntityDataContext(StrConnectionString))
{
if (amdb.DatabaseExists())
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(databaseName))
{
copyDatabase = true;
}
else
{
using (IsolatedStorageFileStream databaseStream = isoStore.OpenFile(databaseName, FileMode.Open, FileAccess.Read)) // error here
{
using (Stream db = Application.GetResourceStream(new Uri(databaseName, UriKind.Relative)).Stream)
{
if (databaseStream.Length < db.Length)
copyDatabase = true;
}
}
}
}
}
else
{
//error with the database that has been packaged
}
if (copyDatabase)
new Worker().Copy(databaseName);
}
Check that you precise, in isolated storage access mode parameters, the possibility to write data in there instead of just be able to read.
Did you test with a device?
From what i can tell you're trying to read the database file, while you still have a database connection open. Since the a DataContext locks the database (and thus the file), you're not allowed to read it at the same time.
In order to close the database connection try to close the EntityDataContext object (by calling amdb.Close() or by closing the using statement
Try something like this:
bool shouldCopyDatabase = false;
bool databaseExists = false;
using (EntityDataContext amdb = new EntityDataContext(StrConnectionString))
{
databaseExists = amdb.DatabaseExists();
}
if (databaseExists == true)
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(databaseName))
{
copyDatabase = true;
}
else
{
using (IsolatedStorageFileStream databaseStream = isoStore.OpenFile(databaseName, FileMode.Open, FileAccess.Read)) // error here
{
using (Stream db = Application.GetResourceStream(new Uri(databaseName, UriKind.Relative)).Stream)
{
if (databaseStream.Length < db.Length)
copyDatabase = true;
}
}
}
}
}
if (copyDatabase)
new Worker().Copy(databaseName);
By moving the isolated storage access functionality outside of the using (EntityDataContext amdb = new EntityDataContext(StrConnectionString)) scope, you allow the database connection to be closed first.

multi lining files in IsolatedStorage # Windows Phone 7

i have created some files in the IO
in the "car" files, i would like to put some other reference like model, color etc...
so my question is : is it possible to have a multi-lining files in the IO
if yes how can i get them in the streamreader
// i want to storage many parameters in a file and find them again with the streamreader
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//reception des parametres de la listbox
base.OnNavigatedTo(e);
string parameter = this.NavigationContext.QueryString["parameter"];
this.tbTitre.Text = parameter;
try
{
//Create a new StreamReader
StreamReader editionDevisReader = null;
IsolatedStorageFile probyOrange = IsolatedStorageFile.GetUserStoreForApplication();
//Read the file from the specified location.
editionDevisReader = new StreamReader(new IsolatedStorageFileStream("devis\\"+parameter+".txt", FileMode.Open, probyOrange));
//Read the contents of the file .
string textFile = editionDevisReader.ReadLine();
//Write the contents of the file to the TextBlock on the page.
tbTitre.Text = textFile;
while (editionDevisReader != null)
{
RowDefinition rowdefinition = new RowDefinition();
TextBlock textblock = new TextBlock();
textblock.HorizontalAlignment = new System.Drawing.Size(48, 20);
}
editionDevisReader.Close();
}
catch
{
//If the file hasn't been created yet.
tbTitre.Text = "veuillez d abord creer le fichier";
}
thx a lot all
Yes, you can save anything (up to a point) in a file:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(isfs))
{
sw.Write("anything really. Here it's just a string but could be a serialized object, etc.");
sw.Close();
}
}
}
You can then read the file with:
var result = string.Empty;
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.FileExists("myfile.txt"))
{
return result;
}
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.Open, store))
{
using (var sr = new StreamReader(isfs))
{
string lineOfData;
while ((lineOfData = sr.ReadLine()) != null)
{
result += lineOfData;
}
}
}
}
}
catch (IsolatedStorageException)
{
result = string.Empty; // may have partial data/file before error
}
return result;
You can use
StreamReader.Writeline
and
StreamRead.ReadLine
to write and read blocks of text seperated by line feeds.

Resources