Archive for category HowTo

[#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

Dejar un comentario

[#VS11] HowTo: Incluir y des serializar un archivo XML en una aplicación #METRO

image

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

image image image

Dejar un comentario

[# WP] HowTo: Install Microsoft.Xna.Framework reference for Windows Phone development in # Windows8

image

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.

image

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:

That Yes, the interesting evening of Logs that I noticed today the does me anyone Risa

Downloads:

Saludos @ Home

El Bruno

image image image

5 comentarios

[#WP] HowTo: Install Microsoft.Xna.Framework reference for Windows Phone development in #Windows8

 image

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.

image

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:

Eso sí, la tarde interesante de Logs que me he dado hoy no me la quita nadie Risa

 

Descargas:

 

Saludos @ Home

El Bruno

image image image

3 comentarios

[#WINDOWS8] HowTo: Enable Hyper-V in Windows8

image

Buenas,

While it is true that Microsoft was always a step (or two) behind in relation to virtualization technology, with Windows 8 has been a big change, and I think that it is for the better:

They have decided to unify the virtualization technology in operating systems for server and client in Hyper-v.

Often golazo! As well, now already we can begin using 64-bit virtual machines, without having to resort to VirtualBox, and finally we move away from the unmentionable VirtualPC.

Enable the Hyper-V role is very simple:

1 Press Win – W to access the Search Settings

2 Write "features"

3. In the form of Windows features, select "Hyper-V"

image

4. We expect the features to be installed.

5 Restart a couple of times (16 seconds clock!)

6. Now we can already launch Hyper-v. To do this press the Windows key, write "Hyper", and will have access to "Hyper-V Manager"

image

From here the Hyper-V for Windows 8 options are quite similar to other products, management of disks, virtual machines, etc.

However it is a great platform to work with virtual machines, which fortunately is already part of the operating system Risa

 

Saludos @ Home

El Bruno

image image image

Dejar un comentario

[#WINDOWS8] HowTo: Habilitar Hyper-V en Windows8

image

Buenas,

si bien es cierto que Microsoft estaba siempre un paso (o dos) por detrás en lo referido a tecnología de virtualización, con Windows 8 han dado un gran cambio, y que creo que es para mejor:

Han decidido unificar la tecnología de virtualización en sistemas operativos de servidor y de cliente en Hyper-V.

Menudo golazo! Pues bien, ahora ya podemos comenzar a utilizar máquinas virtuales de 64 bits, sin tener que recurrir a VirtualBox, y por fin nos alejamos del innombrable VirtualPC.

La forma de habilitar el rol de Hyper-V es muy simple:

1. Presionamos Win-W para acceder a las búsquedas de Settings

2. Escribimos “features”

3. En el formulario de features de Windows, seleccionamos “Hyper-V”

image

4. Esperamos que se instalen las features.

5. Reiniciamos un par de veces (16 segundos de reloj!!!)

6. Ahora ya podemos lanzar Hyper-V. Para esto presionamos la tecla de Windows, escribimos “Hyper”, y tendremos acceso a “Hyper-V Manager”

image

A partir de aquí las opciones de Hyper-V para Windows 8 son bastante similares a otros productos, gestión de discos, de máquinas virtuales, etc.

Sin embargo es una gran plataforma para poder trabajar con máquinas virtuales que por suerte ya es parte del Sistema Operativo Risa

 

Saludos @ Home

El Bruno

image image image

2 comentarios

[#KINECT] HowTo: Buy Kinect for Windows in Spain

image

Buenas,

today I get to answer a question that I do in every event of Kinect:

Where can I buy a Kinect sensor for Windows?

Until recently, the only way to get it was contacting someone from Microsoft or that will bring it someone from the outside.

Now we have access to a (Acuista) provider that can sell it to individuals directly. If we are going to the official website ofKinect for Windows, section Spain Resellers can see access to the site of sale of the product

http://www.acuista.com/x/1312765-Microsoft-kinect-for-Windows-l6m-00003/

So well, you just have to raise €192,95 and expect a little stock to buy a sensor Sonrisa

Saludos @ Home

El Bruno

image image image

Dejar un comentario

[# MTM] HowTo: Use MTM2010 with # TFS11

image

Buenas,

today I was asked if it was possible to use Microsoft Test Manager 2010 (MTM2010) with a Team Foundation Server 11 server.

The answer is Yes, it is only necessary to install an extension from this link.

Then if what we want is the mixed stage but in reverse, Microsoft Test Manager 11 with Team Foundation Server 2010, then this scenario this supported by default.

Saludos @ Home

El Bruno

image image image

Download: http://support.microsoft.com/kb/2662296

Dejar un comentario

[#MTM] HowTo: Utilizar MTM2010 con #TFS11

image

Buenas,

hoy me preguntaron si era posible utilizar Microsoft Test Manager 2010 (MTM2010) con un server Team Foundation Server 11.

La respuesta es SI, solo es necesario instalar una extensión desde este link.

Luego si lo que queremos es el escenario mixto pero al revés, Microsoft Test Manager 11 con Team Foundation Server 2010, pues este escenario esta soportado by default.

 

Saludos @ Home

El Bruno

image image image

Descarga: http://support.microsoft.com/kb/2662296

Dejar un comentario

[# WINDOWS8] HowTo: Open a command prompt with administrator privileges

image

Buenas,

today is to describe a few small to launch a console with administrator privileges. This HowTo is valid in Windows Vista, Windows 7 and Windows 8 obviously.

1. On the desktop, display the contextual menu and select the option "New Shortcut".

2 Write the command "cmd.exe" to the program to launch for the shortcut.

3. Once created the shortcut, select the same, display the contextual menu and access the properties of the shortcut.

image

4 Select the "Shortcut" tab

5 Press the "Advanced" button

6. In the form of advanced properties, select the option "Run as administrator".

image

7 Done!

Saludos @ Home

El Bruno

image image image

Dejar un comentario

Seguir

Get every new post delivered to your Inbox.

Únete a otros 908 seguidores