[#VS11] HowTo: Include and des serialize a XML file in a #METRO application

image

Buenas,

today touches give an example of fairly simple code, but that can bring you a couple of headaches if you don’t know where to start. The idea is simple:

Include an XML file in a METRO application and des serialize it to work in an application.

This seems so simple, is complicated somewhat by METRO as the so so popular as System.IO namespaces and others with which we are accustomed to work because they are not available.

If add you to that, that the majority of the shares are in asynchronous mode, since the programming changes fairly. But of course, Visual Studio 11 comes to our rescue with new sentences ASYNC and AWAIT that really help us to program in asynchronous mode.

We split in the sample project we have a class sample data with 2 properties defined as the following example:

   1: namespace Application1

   2: {

   3:     public class SampleData

   4:     {

   5:         public string Id { get; set; }

   6:         public string Name { get; set; }

   7:     }

   8: }

We then include an XML file within a folder XML with the following information within the same file name:

   1: <?xml version="1.0"?>

   2: <ArrayOfSampleData 

   3:     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

   4:     xmlns:xsd="http://www.w3.org/2001/XMLSchema">

   5:   <SampleData>

   6:     <Id>El</Id>

   7:     <Name>Bruno</Name>

   8:   </SampleData>

   9: </ArrayOfSampleData>

So at a glance, we can see that this XML is a serialization of an Array of elements of type SampleData .

Then is the interesting part, which is read from this file. The following code shows an example where theLoadSampleData() function returns a collection of elements of type SampleData reading a file called "data.xml" of an application directory called "XML".

   1: private async void BtnGetClick(object sender, RoutedEventArgs e)

   2: {

   3:     var collection = LoadSampleData();

   4:     await collection;

   5:     var item = collection.Result[0];

   6:     txtId.Text = item.Id;

   7:     txtName.Text = item.Name;

   8: }

   9:  

  10: public async Task<ObservableCollection<SampleData>> LoadSampleData()

  11: {

  12:     var storageFolder = await Package.Current.InstalledLocation.GetFolderAsync("XML");

  13:     var sampleDataItems = await LoadFromXmlFile<ObservableCollection<SampleData>>("data.xml", storageFolder);

  14:     return sampleDataItems;

  15: }

A couple of details to keep in mind is that the function LoadSampleData() is defined with a prefix async, denotes that it can run in asynchronous mode. This is possible because the reading of the working (line 12) directory is done in asynchronous mode.

At this point sentences where awaitis used for the execution of the asynchronous function deserve a special detail. The simplest define await is think that with this statement we can call asynchronous functions and when completion of them, await will return to the specified workflow.

Now for the interesting part which is desserialización in the XML file. For this use the function LoadFromXmlFile to internally, once he has read the contents of the file, des serializing it in memory (lines 3 to 6). The following code shows an example of this operation:

   1: public static async Task<T> LoadFromXmlFile<T>(string fileName, StorageFolder folder = null)

   2: {

   3:     var xmlString = await ReadFromFile(fileName, folder);

   4:     var ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(xmlString));

   5:     var ser = new XmlSerializer(typeof(T));

   6:     T result = (T)ser.Deserialize(ms);

   7:     return result;

   8: }

   9:  

  10: public static async Task<string> ReadFromFile(string fileName, StorageFolder folder = null)

  11: {

  12:     folder = folder ?? ApplicationData.Current.LocalFolder;

  13:     var file = await folder.GetFileAsync(fileName);

  14:     using (var accessStream = await file.OpenAsync(FileAccessMode.Read))

  15:     {

  16:         using (var inStream = accessStream.GetInputStreamAt(0))

  17:         {

  18:             using (var reader = new DataReader(inStream))

  19:             {

  20:                 await reader.LoadAsync((uint)accessStream.Size);

  21:                 var data = reader.ReadString((uint)accessStream.Size);

  22:                 reader.DetachStream();

  23:                 return data;

  24:             }

  25:         }

  26:     }

  27: }

I’m going to try to separate the code of the piece of POC that I am building, and after a bit of refactoring go up a more complete example.

 

Saludos @ Home

El Bruno

image image image
About these ads

Un pensamiento en “[#VS11] HowTo: Include and des serialize a XML file in a #METRO application

  1. “[#VS11] HowTo: Include and des serialize a XML file
    in a #METRO application El Bruno” ended up being a great
    blog. If perhaps it included alot more photographs it would probably be possibly even a lot better.
    Regards ,Christel

Deja un comentario

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s