XNA: serializing object to isolated storage - windows-phone-7

I have a class that defines my level. I have an XML file in my Content Project that stores the details of the level.
I can load the details of the XML file from the Content Project with LoadContent(). This creates an object with all the details from the XML file.
Now, I want to save that game level into isolated storage.
All the examples that I've seen, indicate that I need to use XMLWriter and XMLSerializer. Why is that? Can I not use the mechanism that the XNA framework uses to load from the Content Pipeline?

You don't need an XMLWriter or XMLSerializer, but you do need a serializer.
Below is an example of a my Generic IsolatedStorage Utilty
public static void Save<T>(string fileName, T item)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fileStream, item);
}
}
}
public static T Load<T>(string fileName)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(fileStream);
}
}
}
When YOU reference the XML as an XNA content it is compiled throught the ContentPipeline. So when you load the Content you do it through the ContentManager. This XML file referenced should NOT be in the ContentPipeline because then it cannot be modified. You should leave Static files referenced through the ContentPipline and leave all Dynamic files saved in IsolatedStorage. Once files are comiled they cannot be changed thats why it cant be saved to the ContentPipeline.

Related

Acess file from isolated storage using its full path as URI

I want to use the file in isolated storage using its full path(like URI), I know there is sandboxed api to access isolated storage. But i have to load the images using their paths.
So is it possible ?
I got it like this:
public string GetAbsolutePathOfFile(string filePath)
{
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isfs = storage.OpenFile(filePath, FileMode.Open, FileAccess.ReadWrite,
FileShare.ReadWrite))
{
return isfs.Name; // this return the absolute path.
}
}
}

How to convert rad controls to images in silverlight

I'm using rad controls(charts and gridview) for developing an application,which i need to export the controls(each) into image.I have tried each control converting them into bytes format and send to webservice and converting them to images but sometime sending the byte data to service throws an error.Is any other way to convert each control into image.I have tried another way like.
Stream fileStream = File.OpenRead(#"\\HARAVEER-PC\TempImages\FlashPivot.png");
//PART 2 - use the stream to write the file output.
productChart.ExportToImage(fileStream, new Telerik.Windows.Media.Imaging.PngBitmapEncoder());
fileStream.Close();
It throwing me an error like cannot access to the folder TempImages.I have given sharing permissions to everyone but it doesn't access the folder.
Any solution is much appreciated.
private BitmapImage CreateChartImages()
{
Guid photoID = System.Guid.NewGuid();
string photolocation = #"D:\Temp\" + photoID.ToString() + ".jpg";
BitmapImage bi = new BitmapImage(new Uri(photolocation, UriKind.Absolute));
using (MemoryStream ms = new MemoryStream())
{
radChart.ExportToImage(ms, new PngBitmapEncoder());
bi.SetSource(ms);
}
return bi;
}

In C# on windows phone Attempt to access the method failed: System.IO.FileStream..ctor(System.String, System.IO.FileMode)

FileStream FS = new FileStream("MyFolder\\MyFile.txt", FileMode.Open);
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("MyFolder\\MyFile.txt", FileMode.Append, myIsolatedStorage));
using (writeFile)
{
FS.Seek(0, SeekOrigin.End);
writeFile.WriteLine(txtWrite.Text);
writeFile.Close();
System.Diagnostics.Debug.WriteLine("Now I am here");
}
When I am trying to run this code(trying to append data into an existing text file), getting exception
"Attempt to access the method failed:
System.IO.FileStream..ctor(System.String, System.IO.FileMode)"
What is the mistake I have done here?
Don't use the FileStream class directory. Get your streams via the methods on IsolatedStorageFile:
IsolatedStorageFile myIsolatedStorage =
IsolatedStorageFile.GetUserStoreForApplication();
using (var writeFile = myIsolatedStorage.OpenFile("MyFolder\\MyFile.txt", FileMode.Append))
using (var writeFileStream = new StreamWriter(writeFile))
{
writeFileStream.WriteLine(txtWrite.Text);
System.Diagnostics.Debug.WriteLine("Now I am here");
}
Could it be that you're attempting to open the same file twice?
A version of your question (with an answer) can be seen at How to append data into the same file in IsolatedStorage for Windows Phone
Finally I made it working after struggling for 4 hrs:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("MyFolder\\MyFile.txt", FileMode.Append, myIsolatedStorage));
writeFile.Flush();
System.Diagnostics.Debug.WriteLine(txtWrite.Text);
writeFile.WriteLine(txtWrite.Text);
writeFile.Close();
System.Diagnostics.Debug.WriteLine("Now I am here");
I removed the file stream method and did some modifications. Its started to work.
Thanks to everybody who tried to help me with your suggestions

Win Phone 7 quiz app

Could any1 please suggest a method by which i can store all my questions , Multiple Choice answers and the correct answer. So that i can call them and then display in a text box and radio buttons . And as when the user answers a question correctly i should be able to move to the next question.
This was my approach. Used data serialization, created a class with Data memebers which will store question id , questions and answers. then created an object for it in while page is loading. But i am unable to display the questions. Please help me out.
Depending on the number of questions, you might find it easier and faster to use a local database.
I am a little confused at your approach. Serialization by itself doesnt actually persist data. Perhaps that is your problem. I have found that storing the XML to IsolatedStorage is one of the easier ways to persist data.
I created an IsolatedStorage class that looks like this for saving an XDocument object.
public static void SaveDataToIsolatedStorage(string filePath, FileMode fileMode, XDocument xDoc)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream location = new IsolatedStorageFileStream(filePath, fileMode, storage))
{
System.IO.StreamWriter file = new System.IO.StreamWriter(location);
xDoc.Save(file);
}
}
}
Here is my reader.
private static XDocument ReadDataFromIsolatedStorageXmlDoc()
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.FileExists(filePath))
{
return new XDocument();
}
using (var isoFileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, storage))
{
using (XmlReader reader = XmlReader.Create(isoFileStream))
{
return XDocument.Load(reader);
}
}
}
}

Windows Azure: Creation of a file on cloud blob container

I am writing a program that will be executing on the cloud. The program will generate an output that should be written on to a file and the file should be saved on the blob container.
I don't have a idea of how to do that
Will this code
FileStream fs = new FileStream(file, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
generate a file named "file" on the cloud...
Oh.. then how to store the content to the blob..
Are you attempting to upload a Page blob or a Block blob? Usually block blobs are what are required, unless you are going to create a VM from the blob image, then a page blob is needed.
Something like this works however. This snippet taken from the most excellent Blob Transfer Utility Check it out for all your upload and download blob needs. (Just change the type from Block To Page if you need a VHD)
public void UploadBlobAsync(ICloudBlob blob, string LocalFile)
{
// The class currently stores state in class level variables so calling UploadBlobAsync or DownloadBlobAsync a second time will cause problems.
// A better long term solution would be to better encapsulate the state, but the current solution works for the needs of my primary client.
// Throw an exception if UploadBlobAsync or DownloadBlobAsync has already been called.
lock (WorkingLock)
{
if (!Working)
Working = true;
else
throw new Exception("BlobTransfer already initiated. Create new BlobTransfer object to initiate a new file transfer.");
}
// Attempt to open the file first so that we throw an exception before getting into the async work
using (FileStream fstemp = new FileStream(LocalFile, FileMode.Open, FileAccess.Read)) { }
// Create an async op in order to raise the events back to the client on the correct thread.
asyncOp = AsyncOperationManager.CreateOperation(blob);
TransferType = TransferTypeEnum.Upload;
m_Blob = blob;
m_FileName = LocalFile;
var file = new FileInfo(m_FileName);
long fileSize = file.Length;
FileStream fs = new FileStream(m_FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
ProgressStream pstream = new ProgressStream(fs);
pstream.ProgressChanged += pstream_ProgressChanged;
pstream.SetLength(fileSize);
m_Blob.ServiceClient.ParallelOperationThreadCount = 10;
asyncresult = m_Blob.BeginUploadFromStream(pstream, BlobTransferCompletedCallback, new BlobTransferAsyncState(m_Blob, pstream));
}

Resources