Simple C# Serialization

2012-06-18 1 comment

(Kudos if you noticed the alliterated title)
(Edit: this is an old article I never published. Until now! I hope it serves as a nice introduction to beginners).

Serialization is a thing I had (until recently) left untouched. For too long. Well, no more. Here are the basics.

What is serialization?
Simply put, it’s taking an object’s value(s) and writing them to a file (or a buffer, but I’m not covering that here) for transmission or storage.

What is deserialization?
It’s the reverse, building an object from a file (or buffer).

Why serialize?
Serialization can be used for various reasons, such as transmitting data to another computer or storing it. Storage could potentially be done with a database, but even something portable like SQLite is another thing to maintain, whereas for minimal needs, serialization offers quick and dirty clean storage for later use. For example, I’m using it for storing a few sets of parameters for batch processing.

Here’s how. I will be using the simplest form of XML serialization (that is, writing to, and naturally reading from XML), not Soap, but with the very vanilla System.Xml.Serialization namespace.

First, add System.Xml to your project’s references.

Now, we’ll design the basic class we want to serialize. First, the class without the serialization attributes:

public class ClientInfo
{
    public string ClientName { get; set; }
    public int ClientId { get; set; }
    public DateTime ProcessTime { get; set; }

    public ClientInfo (string clientName, int clientId)
    {
        ClientName = clientName;
        ClientId = clientId;
    }
}

To serialize, we’ll need the proper namespace, so add:

using System.Xml.Serialization;

in your using block at the top.

Next, we’ll decide what we want to serialize. Let’s say ClientName and ClientId, but ProcessTime shouldn’t be serialized at all (for some reason. Hey, I just needed the example).

So, we’ll need to tell the compiler that the class is serializable, simply by adding the attribute above the class declaration:

[Serializable]
public class ClientInfo
{/...

By default, all fields become serializable. Let’s specify the field to ignore appropriately:

    public string ClientName { get; set; }
    public int ClientId { get; set; }
    [XmlIgnore] //Tells C# to forget about that value for serialization
    public DateTime ProcessTime { get; set; }

Serialization also requires a default constructor. And the nice thing is that it does not have to be public, so your class logic can remain the same from outside (i.e. no default instantiation if you don’t want it):

    private ClientInfo()
    { }

The final result:

using System.Xml.Serialization;

[Serializable]
public class ClientInfo
{
    public string ClientName { get; set; }
    public int ClientId { get; set; }
    [XmlIgnore]
    public DateTime ProcessTime { get; set; }

    public ClientInfo (string clientName, int clientId)
    {
        ClientName = clientName;
        ClientId = clientId;
    }

    private ClientInfo()
    { }
}

And we’re done for that part! Now, suppose you want to serialize that into an Xml file. Use a function like so:

public static bool SaveConfig(ClientInfo clientInfo, string filePath)
{
    bool success = false;
    using (FileStream flStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
        try
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List));
            xmlSerializer.Serialize(flStream, clientInfo);
            success = true;
        }
        //do add proper handling of possible stream exceptions here
        finally
        {
            flStream.Close();
        }
    }
    return success;
}

And reading, essentially taking the XML class and making it into an object is just as easy, it’s called deserialization:

public ClientInfo LoadConfig(string filePath)
{
    if (!File.Exists(filePath))
        return null; //Or ClientInfo.Default if you made one

    ClientInfo clientInfo = null;
    using (FileStream flStream = new FileStream(destFileName, FileMode.Open, FileAccess.Read))
    {
        try
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ClientInfo));
            clientInfo = xmlSerializer.Deserialize(flStream) as ClientInfo;
        }
        //do add proper handling of possible stream exceptions here
        finally
        {
            flStream.Close();
        }
    }
    return clientInfo;
}

This is just the tip of the iceberg. You can serialize/deserialize sub-objects, collections, etc. This is very useful for reading and writing back. And of course if you need to serialize/deserialize something large, there are better ways, like binary serialization!

Advertisements
Categories: Basics, Programming Tags:

La promesse Agile

(yup, this one’s in French!)

Agile, ou l’Agilité, est une méthodologie de gestion à la mode en informatique. On se veut Agile, on se dit Agile, mais l’est-on vraiment? Ou est-on réellement prêt à le devenir?

Cette méthodologie est basée sur des valeurs qui tendent vers une meilleure organisation du travail de développement logiciel. Dans ce but, elle accorde beaucoup d’importance à l’équipe de développement. Elle vise à valoriser

  • les individus et leurs interactions plutôt que les processus et les outils
  • des logiciels opérationnels plutôt qu’une documentation exhaustive
  • la collaboration avec les clients plutôt que la négociation contractuelle
  • l’adaptation au changement plutôt que le suivi d’un plan

Elle prévoit divers mécanismes pour concentrer les efforts, le plus connu étant le Scrum.

Le Scrum est une brève rencontre quotidienne qui permet de s’assurer de la progression d’un projet. Cinq minutes, et debout! On est loin du traditionnel meeting de la haute direction. Il est dirigé par un ScrumMaster, qui se fait le protecteur de l’équipe en éloignant les interruptions et en maintenant le contact avec le client.

Le but avoué d’Agile est de concentrer le talent et le travail pour satisfaire les demandes du client. Mais son but ultime est de favoriser le développement humain. La nature même du travail dans le domaine du logiciel demande un apprentissage perpétuel. Le développement n’est pas un ouvrage de production constante. En effet, ce n’est pas une chaîne de montage : c’est un processus on ne peut plus humain, centré sur ce qui qualifie l’homo sapiens, la pensée. Mais c’est justement dans l’obligation de livrer un produit qu’on peut perdre l’aspect humain. Alors intervient Agile!

Présentée dans le manifeste Agile, le manifeste tient compte des réalités du monde des affaires : les besoins changent et grandissent rapidement. Il y a une foule de détails et d’étapes à produire dans une solution logicielle. L’élément central de tout cela n’est pas la productivité, ou même l’ordinateur, c’est le facteur humain. En laissant les développeurs s’autogérer (dans le cadre du projet), on ne tombe pas dans les pièges du micro-management. Les développeurs prennent conscience de leur capacité, de leur utilité et deviennent (ou demeurent) proactifs par rapport au développement, plutôt que réactifs. Le stress diminue, les dossiers se règlent, le produit se développe. Mais surtout, les développeurs sont heureux, ils s’épanouissent dans leur travail.

Et tout cela se fait sans lunettes roses, parce que le client est en contact constant! Ce que plusieurs gens retiennent de l’Agilité, ce sont les cycles courts. Petit ajout au logiciel, mise à jour, informer le client. Le rythme n’est pas une fin en soi, c’est la réalisation en continu de ce que le client a besoin.

Bien entendu, on ne devient pas Agile pour simplement le devenir. Ce n’est pas une finalité, c’est un changement constant. C’est une adaptation des êtres humains dans l’organisation à une méthodologie. Devenir Agile est un processus… Agile!

Categories: Agile

C/C++ inline keyword

2012-02-12 2 comments

It’s always been fuzzy in my mind what inline does. An ex-colleague who had discovered it said it was to make things faster, but I was certain it wasn’t just a magic word. Now it’s a bit clearer.

Suppose you have a very simple function:

int add(int a, int b)
{
    return a + b;
}

That’s not very processing intensive, right? But when this is compiled, what happens? Well, it’s a function, and a function has a place in memory. When the function is called in execution, the context is changed to reach that “add” function, execute it, and return the result (my simplification of the wording betrays my lack of knowledge of assembly, I know). So that’s basically three operations for a simple addition. One way to speed that up is to tell the compiler to make this function inline, that is to say, to not leave the context for when it is called. In other words, the function’s code replaces each call.

inline int add(int a, int b)
{
    return a + b;
}

It keeps the logic nice and tidy, but at the same time speeds up execution. There is a downside, however: the program will have a larger memory footprint. That means it could, in the end, slow down execution (if there are many inline functions).

One nice way to use this is for C++ accessors:

// myclass.h
class MyClass
{
private:
    int m_int;
public:
    int GetInt() const;
    void SetInt(int);
}

inline int MyClass::GetInt() const
{
    return m_int;
}
inline void MyClass::SetInt(int value)
{
    m_int = value;
}

Put the inline functions in your header file, and you’re all set.

Categories: Learning Tags: ,

Initialization lists in C++

New thing learned! This is actually a really nice one.

Suppose a class with three properties:

class MyClass
{
public:
    MyClass(int property1, char property2, float property3);
private:
    int m_property1;
    char m_property2;
    float m_property3;
}

A constructor that’s essentially trivial (no validation) would look like this:

MyClass::MyClass(int property1, char property2, float property3)
{
    m_property1 = property1;
    m_property2 = property2;
    m_property3 = property3;
}

There is, however, a more concise way to write this with something called an initializer list:

MyClass::MyClass(int property1, char property2, float property3)
: m_property1(property1), m_property2(property2), m_property3(property3)
{
}

Much cleaner. If some elements require validation, they don’t need to be in the list.

There’s a whole lot more here: http://www.cprogramming.com/tutorial/initialization-lists-c++.html

UPDATE (2012-02-09):

For this course I’m taking, I’m using GCC to compile. One of the differences I found with Visual Studio’s compiler is that with GCC requires that the elements initialized be listed in the same order as properties (in the class’ private section) and in the constructor.

UPDATE (2012-03-26)

One thing I had not caught on originally is beyond the syntax. Yes, it’s a clean syntax, but the main feature is that there is no pre-assignment. In C++, at the start of the constructor (in laymen’s terms, right after the opening bracket), all class attributes are assigned. What you’re doing with this:

m_property1 = property1;

is basically the second assignment of m_property1, the first being its default. If it’s a simple type, there’s no harm done, but if it’s an object of a class, that means the default constructor was called. Worst, if it’s a class you wrote, it means you have to give it a default constructor. If your class doesn’t naturally need a default constructor, this is bad. The extra instantiation alone, the hidden one, is bad, you’re wasting valuable resources. In an initialization list, the property is assigned directly. Waste not, want not.

Categories: Learning Tags:

typedef and structs

Another thing I learned in the C introduction to “Advanced C++ Programming”, typedef used with structs. Every teacher (and everyone else) I asked before kept saying typedef was “sorta complicated”, which meant they either didn’t know or didn’t want to explain it to me.

As I understand it, typedef is an instruction which tells the compiler to treat what is defined as a type.

For example, given a defined structure:

struct MyStruct
{
    int var1;
    char var2;
};

Using this struct means carrying the struct keyword everywhere.

//Anywhere it is declared
struct MyStruct my;
//And in function parameters too
void MyFunc(struct MyStruct my);

typedef simplifies this greatly:

typedef struct
{
    int var1;
    char var2;
} MyStruct;

//Declaration
MyStruct my;
//Parameter declaration
void MyFunc(MyStruct my);
Categories: Learning Tags:

C blocks and variable declaration

First thing I learned in the “I’m supposed to know this already!” class (Advanced C++ Programming) is actually about C.

In C++ variables can be declared anywhere in the scope of a function (well, anywhere before they’re used). In C, however, they have to be declared at the beginning of the function. Or so I thought. It’s actually at the top of the block. And a block is delimited by curly braces.

In other words, declaring at the top of a function:

void MyFunction(void)
{
    int myVar;
    //...
}

Inside a control structure:

void MyFunction(void)
{
    if(/*some condition*/)
    {
        int myVar;
        //...
    }
}

or

void MyFunction(void)
{
    for(/*start, end, iteration*/)
    {
        int myVar;
        //...
    }
}

or even

void MyFunction(void)
{
    switch (/*expression*/)
    {
        case 1:
        {
            int myVar;
            //...
        }
    }
}

And even just out of the blue:

void MyFunction(void)
{
    //some code
    {
        int myVar;
        //...
    }
}

Although this last form should arguably be used sparingly. And here I thought I had to list it all at the very beginning of the function. I’m ashamed, but I’m glad I know now.

Add-on: I forgot to mention the scope. The variable exists in the block. It’s a local declaration only valid in it. Outside the block, the variable no longer exists. Your compiler will tell you if you refer to a variable declared in a block outside of it.

Categories: Learning Tags:

Look at me, I’m learning!

Time to dust off this place and bring it back to life!

I have a course this semester, called Advanced C++ Programming. It’s mandatory, and I know most of what’s being taught. I still enjoy it, the prof. is no-nonsense, and drops bombs like:

If a code base cannot be maintained, it might as well just not work.

which resonates strongly with what I’m working with. So there’s a lot of focus on code clarity and re-usability. I’m loving that discourse.

At the same time, I do learn some tiny bits here and there, and for as long as it’s manageable, I will post them here.

Categories: Learning