Friday, July 19, 2013

Object seriliazitation with Type attributes in the nodes.

Here is a problem that I had while consuming a service in C#.

What I needed to do:
I got a service from a vendor. This service is an XML post to a PHP page (btw, I hate these).  This vendor provided me with a sample XML that would be the package sent. I need to populate every node with my data and make the call. I would much rather have an object to do this, so I created one. I serialized my object and prepared for the posing of it. When comparing my result with the provided XML I was missing attributes on my object so I started looking on how to add them.

My vendor provided XML was similar to this:

<?xml version="1.0" encoding="utf-16"?>
<user>
  <FirstName Type="string">Soy</FirstName>
  <LastName Type="string">Nerdito</LastName>
  <IsPaying Type="boolean">True</IsPaying>
</user>

My Serialized user object looked like this:

<?xml version="1.0" encoding="utf-16"?>
<user>
  <FirstName>Soy</FirstName>
  <LastName >Nerdito</LastName>
  <IsPaying>True</IsPaying>
</user>

This looks simple enough to add the type to the node on my object so when serialized they are made identical. Duh! could not find a good solution for this. Most posts online were talking about doing a replace on the serialized string of each node to add the type. This requires me to add code to that section every time I create a new object property. Well I'm lazy and did not wanted to do that, so something else was needed.

The Solutions:
Manipulate the XML attributes that I had on my object to allow the serializer to do its job. Well, that was not an easy find either. So here is what I did.
.NET allows you to do this, add attributes to your nodes, but your objects must be constructed a certain way. So let the fun begin.

The Code:
First you need to create an object that will be the type for each one of your properties. Why? because natives will not cut it when the serializer gets a hold of them. So I decided to create a generic object that will accommodate anything I throw at it and it will take the type of the value all by itself (lazy, remember!).

Namespaces:
 You need these.
using System.Xml.Serialization;
using System.Xml;

Each of my nodes will be of this type:


    public class SingleNode<T>
    {
        public SingleNode(){}

        public SingleNode(T val)
        {
            value = val.ToString();
            //This is like so to remove the System. definition from the Type
            Type = val.GetType().ToString().Replace("System.", "").ToLower();
        }

        [XmlText]
        public string value;

        [XmlAttribute("Type")]
        public string Type;
    }

 The XMLText and XMLAttribute define what the serializer will do when working with this. My constructor is generic so I should be able to pass any object type, I want to do ENUMS also but have not tried yet.

Now that you have the base object lets create User:


    [XmlRoot("user")]
    public class user
    {
        [XmlElement("FirstName")]
        public SingleNode FName = null;

        [XmlElement("LastName")]
        public SingleNode LName = null;

        [XmlElement("IsPaying")]
        public SingleNode IsPaying = null;
    }


The XMLRoot defines the name for the root node once is serialized.  The XMLElement attributes defines the node name after is serialized. Note that this is not the property name during design time and run time. You must reference the object in your code as user.FName, user.LName and so on. Each of the properties are defaulted to NULL but you can create the object instance there is you so pleased and assign a default value.

To create an instance of this is quite simple:


            user test = new user();
            test.FName = new SingleNode<string>("Soy");
            test.LName = new SingleNode<string>("Nerdito");
            test.IsPaying = new SingleNode<bool>(true);


You can see the instantiation assigns the object type because the constructor is generic.

The serializer:
If you do not have it, here is how to serialize it.
            XmlSerializerNamespaces xns = new XmlSerializerNamespaces();
            xns.Add(string.Empty, string.Empty); 
            
            //xml format settings
            XmlWriterSettings xmlSettings = new XmlWriterSettings();
            xmlSettings.Indent = true;
            xmlSettings.NewLineOnAttributes = false;
            xmlSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; 
            XmlSerializer mySerializer = new  XmlSerializer(typeof(user));
            StringWriter ms = new StringWriter();
            XmlWriter xw = XmlWriter.Create(ms, xmlSettings);
 
            mySerializer.Serialize(xw, test, xns); 
            string serializedString = ms.ToString();
            ms.Close();

Conclusion:
This is it, simple enough to create the objects when you need to add a particular attribute. The attribute does not have to be the data type, you can change this to be anything you need it to be. .NET can add a DataType but if you service does not "play" with that, here you have an alternative. 

Would there be other ways of doing this, maybe but I could not find it. Please let me know if you have any improvements.

Why with all the new ways of creating web services people still write services that work with a post and do not have a WSDL or at least provide XSDs is beyond me, but hey not everyone can be a Nerdito.




Sunday, July 14, 2013

Escribiendo acentos en Linux

He utilizado varias versiones de Linux y en todas he tenido problemas escribiendo acentos. Hablo español pero siempre he utilizado los operativos y teclados en inglés.
Si te pasa como a mí la solución es bien simple.
Linux Mint 14
Solo ve a:
Control Panel - Keyboard - Layout y añadir el teclado "English (US) English (International AltGr dead keys)"
Eso es todo lo que hace falta cambiar.
Luego de esto con solo hacer un:
RightAlt + n = ñ
RightAlt + a = á
RightAlt + e = é
RightAlt + i = í
....

La información de como hacer esto la pude tener por la comunidad de Linux en español de Google+, si esto te sirvió pasa por el Google+ y aclara cualquier otra duda que tengas, a mi me ayudaron bien rápido espero que tengas la misma experiencia. A compartir conocimiento!!!

Ahora soy feliz y espero que este escrito le sirva a alguien. O al menos a mi mismo para cuando cambie de versión y se me olvide que fue lo que hice.

Sunday, March 17, 2013

Pepita Board soon to be a reality

Pepita V1
A few weeks ago decided to get some experience under my belt on PCB designing. So I just decided to build a variation of the Metaboard. All began with the name, for that I turned to my wife and asked for a name. Without any hesitation she said "We shall call it Pepita", so Pepita it is then.

Pepita Goals:
1. Create a multipurpose micro-controller board with an Atmega328.
2. Cheap
3. Get the experience of PCB designing.

Pepita Challenge:
1. Make it fit on a 5cm x 5cm board. (cheapest size).

As you may see, this board will not make any revolution but for me it is a needed step.
I do not create here any tutorial, cause I just sent it out for manufacturing. Still I do not know how many mistakes I made or what could be better designed. Probably in two months or what ever it takes to get back to me I will know.
Anyhow, I post here the link of the Eagle Cad schematic and board files.

Schematic pepita.sch
Board Files pepita.brd

Hope to write something once I get the actual board and post some successful pictures of it.
If you want to build something, make up your mind and do it. No need to wait for everything to be perfect, if you keep waiting it will never get done. Like the comercial, just do it!

Here is a short video of the board after it came back from manufacturing.
There are no surface mount components, so far so good. It is working great, and I am continuing adding code and devices to it, just to expore the posibilities.




Monday, January 7, 2013

Programming for my network android (MK802)


Christmas came and with it a new nerd toy. In my case it was in the for of a Rikimagic MK802II android minipc.

Wanted to debug apps directly into the device but the device is plugged via HDMI to the TV and it would be hard for me to place a laptop near the TV just to debug a simple app. Knowing that you can use the Android Development Bridge over network by running a few shell commands, I decided to do that precisely. Instead of typing each time and being the nerd I am. Just put a few lines together to activate this via simple app click. Also to install for first time easy I uploaded the app to the market.

The app turns out to be great for my phone (Motorola Atrix 2 rooted) as well.

The link for the app is:
https://play.google.com/store/apps/details?id=com.soynerdito.adbnetworkenabler&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5zb3luZXJkaXRvLmFkYm5ldHdvcmtlbmFibGVyIl0.

Your PC should be in the same network as the device.
Steps to Develop Via Network (WIFI):
1. Download the app from the play store into the device
2. On the Device Run the app and click on Toggle once. (it enable and if it is enable it tries disable). It is not intelligent at all, so it just toggle, click it once and keep count so you know if enable or disable.
3. On the PC (get the IP from the device app) open a shell or command prompt and run
adb connect <DEVICE_IP_ADDRESS>

You should see a connection confirmation on the shell. Alfter just run your Eclipse or other environment and debug as a regular device.


I have not uploaded the code for this app still but could be if somebody want's it.Anyhow soon the code will be uploaded just to save it for future reference.

The app requires the device to be rooted and the super user app be installed. Could not make it to work without the super user (also I do not have a non rooted phone). If learn how to do un-rooted will be better, that could be an upgrade.

This post describes the commands to connect the ADB over network (from here I got the commands to run)
http://stackoverflow.com/questions/2604727/how-can-i-connect-to-android-with-adb-over-tcp