[#VS11] HowTo: Include and des serialize a XML file in a #METRO application
Publicado por elbruno en EnglishPost, HowTo, Metro, Visual Studio 11, Windows 8 el 17 mayo, 2012
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
[#VS11] HowTo: Incluir y des serializar un archivo XML en una aplicación #METRO
Publicado por elbruno en HowTo, Metro, Visual Studio 11, Windows 8 el 17 mayo, 2012
Buenas,
hoy toca poner un ejemplo de código bastante simple, pero que puede traerte un par de dolores de cabeza si no sabes por donde empezar. La idea es simple:
Incluir un archivo XML en una aplicación METRO y des serializar el mismo para trabajar en una aplicación.
Esto que parece tan simple, se complica un poco en METRO ya que los tan namespaces tan populares como System.IO y otros con los que estamos acostumbrados a trabajar ya no están disponibles.
Si a eso le sumamos, que la mayoría de las acciones son en modo asíncrono, pues la programación cambia bastante. Pero claro, Visual Studio 11 llega a nuestro rescate con las nuevas sentencias ASYNC y AWAIT que realmente nos ayudan a programar en modo asíncrono.
Vamos por partes, en el proyecto de ejemplo tenemos una clase sample data con 2 propiedades definidas como el siguiente ejemplo:
1: namespace Application1
2: {
3: public class SampleData
4: {
5: public string Id { get; set; }
6: public string Name { get; set; }
7: }
8: }
Luego incluimos un archivo XML dentro de una carpeta XML, con la siguiente información dentro del mismo
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>
Así a simple vista, podemos ver que este XML es una serialización de un Array de elementos de tipo SampleData.
Luego queda la parte interesante, que es leer de este archivo. El siguiente código muestra un ejemplo donde la función LoadSampleData() retorna una colección de elementos del tipo SampleData leyendo un archivo llamado “data.xml” de un directorio de la aplicación llamado “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: }
Un par de detalles a tener en cuenta es que la función LoadSampleData() está definida con un prefijo async, que denota que la misma se puede ejecutar de modo asíncrono. Esto es posible ya que la lectura del directorio de trabajo (línea 12) se realiza en modo asíncrono.
En este punto merecen un especial detalle las sentencias donde para la ejecución de la función asíncrona se utiliza await. La forma más simple de definir a await es pensar en que con esta sentencia podremos llamar a funciones asíncronas y cuando se terminen las mismas, await retornará al flujo de trabajo indicado.
Ahora vamos a la parte interesante que es la desserialización del archivo XML. Para esto utilizamos la función LoadFromXmlFile que internamente, una vez que ha leido el contenido del archivo, des serializa el mismo en memoria (líneas 3 a 6). El siguiente código muestra un ejemplo de este funcionamiento:
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: }
Voy a intentar separar el código del pedazo de POC que estoy construyendo y después de un poco de refactoring subiré un ejemplo más completo.
Saludos @ Home
El Bruno
[# WP] HowTo: Install Microsoft.Xna.Framework reference for Windows Phone development in # Windows8
Publicado por elbruno en EnglishPost, HowTo, Visual Studio 2010, Windows 8, Windows Phone el 14 mayo, 2012
Buenas,
I am not a developer of Windows Phone applications, so are the cracks (@ RafaSermed or @ JosueYerayfor example), but since I have Windows 8 installed as main working platform, because I missed in face to finish a few touches to an application of WP.
Now that we have the Windows Phone SDK 7.1.1 Update that already allows us to install WP on Windows 8 development tools, because I thought that it was all fixed. But… zas! the first on the face, to the point of wanting to compile the project, because I realize that I’m lacking in XNA.
So ignorant of me, I think that installing Microsoft XNA Game Studio 4.0 it would solve my problems, but of course
trying to install XNA in Windows 8 is just as easy to scratch the back with knee
So he plays a little read installation logs, and after a while I realise that the fundamental problem seems to be related to a product that did not know until the day of today: Game for Windows Client.
And of course, the problem is the following:
- The installer of Windows Phone tries to install a version of XNA, but cannot
- Actually it can not, because the XNA Installer tries to install a version of Game for Windows Client and Windows 8 says NOT IN MY WATCH!
So slowly and lovingly, the steps to get everything to work are as follows:
- Uninstall everything from XNA if you tried until the update of Windows Phone 7.
- Download and install the latest version of Game for Windows Client.
- Now yes, install Windows Phone SDK 7.1.1 Update and if we need it, because also Microsoft XNA Game Studio 4.0
That Yes, the interesting evening of Logs that I noticed today the does me anyone ![]()
Downloads:
Saludos @ Home
El Bruno
[#WP] HowTo: Install Microsoft.Xna.Framework reference for Windows Phone development in #Windows8
Publicado por elbruno en HowTo, Visual Studio 2010, Windows 8, Windows Phone el 14 mayo, 2012
Buenas,
no soy un desarrollador de aplicaciones de Windows Phone, para eso están los cracks (@RafaSermed o @JosueYeray por ejemplo), pero desde que tengo Windows 8 instalado como plataforma principal de trabajo, pues echaba en cara poder terminar de dar unos toques a una aplicación de WP.
Ahora que tenemos el Windows Phone SDK 7.1.1 Update que ya nos permite instalar las herramientas de desarrollo de WP sobre Windows 8, pues pensé que tenía todo solucionado. Pero … zas! la primera en la cara, al momento de querer compilar el proyecto, pues me doy cuenta de que ando falto de XNA.
Así que ignorante de mí, pienso que instalando Microsoft XNA Game Studio 4.0 solucionaría mis problemas, pero claro
intentar instalar XNA en Windows 8 es igual de fácil que rascarse la espalda con la rodilla
Así que toca leer un poco los logs de instalación, y después de un rato me doy cuenta de que el problema de fondo parece que está relacionado con un producto que no conocía hasta el día de hoy: Game for Windows Client.
Y claro, el problema es el siguiente:
- El instalador de Windows Phone intenta instalar una versión de XNA, aunque no puede
- En realidad no puede, porque el instalador de XNA intenta instalar una versión de Game for Windows Client y Windows 8 dice NOT IN MY WATCH !!!
Así que de a poco y con cariño, los pasos para lograr que todo funcione son los siguientes:
- Desinstalar todo, desde XNA si lo intentaste hasta el update de Windows Phone 7.
- Descargar e instalar la última versión de Game for Windows Client.
- Ahora sí, instalar Windows Phone SDK 7.1.1 Update y si lo necesitamos, pues también Microsoft XNA Game Studio 4.0
Eso sí, la tarde interesante de Logs que me he dado hoy no me la quita nadie ![]()
Descargas:
Saludos @ Home
El Bruno
[# VS11] NUnit plugin updated (Yahooo!)
Publicado por elbruno en EnglishPost, Visual Studio 11, Visual Studio Gallery el 13 mayo, 2012
Buenas,
today I was watching / updating a little code viejuno where used NUnit as a framework for my testing unit and clear, as we are now using 100% Visual Studio 11 development, so I decided to use the plugin to NUnit.
The good thing about VS11 is that it allows to use different plugins for unit testing (something already talked here), but better was my surprise when I found myself with a new version of the adapter for NUnit.
As in the Visual Studio Gallery PlugIn page there is no much information thereon, because I sign the following links to see innovations, because among other things that you there is no Active Bug brightens as developer ![]()
Best regards
- Download
http://visualstudiogallery.msdn.Microsoft.com/6ab922d0-21c0-4f06-ab5f-4ecd1fe7175d - More Information
http://NUnit.org/index.php?p=vsTestAdapter & r = 2. 6
Saludos @ Home
El Bruno
[#VS11] Actualizado el plugin para NUnit (yahooooo !!!)
Publicado por elbruno en Visual Studio 11, Visual Studio Gallery el 13 mayo, 2012
Buenas,
hoy me encontraba mirando/actualizando un poco de código viejuno donde utilizaba NUnit como framework para mis pruebas unitarias y claro, como ahora estamos utilizando 100% Visual Studio 11 para el desarrollo, pues me decidí a utilizar el plugin para NUnit.
Lo bueno de VS11 es que permite utilizar diferentes plugins para pruebas unitarias (algo de lo que ya hablé aquí), pero fue mejor mi sorpresa cuando me encontré con una nueva versión del adaptador para NUnit.
Como en la página del PlugIn de Visual Studio Gallery no hay mucha información al respecto, pues me apunto los siguientes enlaces para ver las novedades, porque entre otras cosas ver que no hay ningún Bug activo me alegra como developer ![]()
Saludos
- Descarga
http://visualstudiogallery.msdn.microsoft.com/6ab922d0-21c0-4f06-ab5f-4ecd1fe7175d - More Information
http://nunit.org/index.php?p=vsTestAdapter&r=2.6
Saludos @ Home
El Bruno
[#VS11] Windows 8 and the Speech Recognition are brutal enemies when you are developing #METRO applications
Publicado por elbruno en EnglishPost, Visual Studio 11, Windows 8 el 11 mayo, 2012
Buenas,
today is I’ll try to share an experience of a typical Friday. Almost at the end of the development of a METRO application (cool not?), and doing a couple of tests in environments like laptops, tablets, touch. When I try some configurations and tests in the emulator I find the following error:
Note: if you’re wondering why I had to use the emulator of Windows 8, I encourage you to try to move from landscape to portrait a 5 Kilos HP Touch .
So taht’s it, the emulator can’t launch everything ok if you have activated Microsoft Speech and in case you need both, you’ll take a good annoyance.
But of course, is Friday better dig between encouraging phrases of Friday and move forward with a
Problems are always showing up, but solutions are also always showing up.
The more objective solution is to chante to a new religion “the creationism” and try to create an extension for the emulator that supports audio device. The more realistic option, is to test the application in the emulator without the audio features and remember the mother of Sinofsky (or as type the name of the boss of W8).
That Yes, with any of the 2 options already can have the application running with all the features we need.
Saludos @ Home
El Bruno
[#VS11] Porque Windows 8 y el speech recognition se llevan de los pelos si desarrollas aplicaciones Metro
Publicado por elbruno en Visual Studio 11, Windows 8 el 11 mayo, 2012
Buenas,
hoy toca compartir una experiencia de las que te pasan los viernes. Casi al final del desarrollo de una aplicación METRO (a que mola no?), y haciendo un par de pruebas en entornos no portátiles, tablets, touch, en el momento de probar algunas configuraciones en el emulador me encuentro con el siguiente error:
Nota: si te estás preguntando porqué tuve que utilizar el emulador de Windows 8, te animo a que intentes mover de landscape a portrait un HP Touch de 5 kilos.
Pues bien, el emulador no se puede lanzar si tienes activado el Microsoft Speech y en caso de que necesites ambos, te puedes llevar un buen disgusto.
Pero claro, es viernes mejor rebuscar entre frases alentadoras de viernes y salir adelante con un
Los problemas nunca se acaban, pero las soluciones tampoco.
La solución más objetiva consiste en convertirse al creacionismo e intentar crear una extensión para el emulador que soporte dispositivo de audio. La opción más realista, es probar la aplicación en el emulador sin las features de audio y acordarse de la madre de Sinofsky (o como se escriba el nombre del jefazo de W8).
Eso sí, con cualquiera de las 2 opciones ya podremos tener la aplicación en funcionamiento con todas las features que necesitamos.
Saludos @ Home
El Bruno
[#RESHARPER] ReSharper 7 EAP for Visual Studio 11 expired? Not problem
Publicado por elbruno en EnglishPost, JetBrains, ReSharper, Visual Studio 11 el 9 mayo, 2012
Buenas,
If you has expired the trial of the EAP of 7 ReSharper for Visual Studio 11 and when you open Visual Studio you are with
You’ll see that the link proposes to upgrade to a new version does not work. So the best thing is to uninstall 7 Resharperhandmade from "add and remove programs"
And once uninstalled, are again going to the list of night-time compilations of ReSharper 7 which you can access fromhttp://confluence.jetbrains.net/display/ReSharper/ReSharper+7+EAP+for+VS11+Beta, downloaded the version that puts us more happy and ready to reinstall ![]()
In 10 minutes we have the help of ReSharper embedded within the IDE.
Saludos @ Home
El Bruno
[#RESHARPER] Ha caducado ReSharper 7 EAP para Visual Studio 11? No problem
Publicado por elbruno en ReSharper, Visual Studio 11 el 9 mayo, 2012
Buenas,
si se te ha vencido el trial del EAP de ReSharper 7 para Visual Studio 11 y cuando abres Visual Studio te encuentras con
Verás que el link que propone para actualizar a una nueva versión no funciona. Así que lo mejor es desinstalar Resharper 7 a mano desde “add and remove programs”
Y una vez desinstalado, vamos nuevamente al listado de compilaciones nocturnas de ReSharper 7 que se puede acceder desde http://confluence.jetbrains.net/display/ReSharper/ReSharper+7+EAP+for+VS11+Beta, descargamos la versión que nos ponga más felices y listo a instalar nuevamente ![]()
En 10 minutos ya tenemos la ayuda de ReSharper embebida dentro del IDE.
Saludos @ Home
El Bruno




SocialVibe