Visualizzazione post con etichetta Extension methods. Mostra tutti i post
Visualizzazione post con etichetta Extension methods. Mostra tutti i post

mercoledì 12 giugno 2013

Serializing and deserializing classes in C#

When we send data to a different system, is usual to use xml formats. If we use C # as a programming language, there are some framework methods that help us a lot. In the version 3.5 of the framework we can use the "exstension Method" and can equip any class of additional methods, in relation to the type.
Combining the two things you can write methods for serializing and deserializing classes and make them generic.
For example:

With the following "Extension Method"


        /// <summary>
        /// Serializes to XML.
        /// </summary>
        /// <param name="value">The object to serialize.</param>
        /// <returns>
        /// a XElement rappresenting the class serialization
        /// </returns>
        public static XElement SerializeToXML(this object value)
        {
            XmlSerializer x = new XmlSerializer(value.GetType());
            XDocument doc = new XDocument();
            using (XmlWriter xw = doc.CreateWriter())
            {
                x.Serialize(xw, value);
                xw.Close();
            }
            return doc.Root;
        }


        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this string value)
        {
            XElement xElement = XElement.Parse(value);

            return xElement.Deserialize<T>();

        }

        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this XElement value)
        {
            XmlSerializer x = new XmlSerializer(typeof(T));
            T result;
            using (XmlReader xr = value.CreateReader())
            {
                result = (T)x.Deserialize(xr);
                xr.Close();
            }
            return result;
        }









In this way, you'll just have to serialize a class writing







MyClass a = new MyClass();

XElement xml = a.SerializeToXML();
MyClass b = xml.Deserialize<MyClass>(xml)

Extract the first characters of a text.

Good morning to everybody

What I propose today is a simple function to extract the first characters of a text.
Even in this simple function we have some requirements:

  • must be extracted whole words only.
  • if the text exceeds the size you want, we have to append some points of suspension.
  • the suspension points contribute to the number of desired characters.

Here's the function:


  public string GetAbstract(string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }



If we really want to esagereare we can also create an extension method for object "String".
In this way we can easily extract text from each string.


public static class Extensions
    {
  public static string GetAbstract(this string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }
}

Enjoy!

martedì 11 giugno 2013

Estrarre le prime lettere di un testo

Buongiorno a tutti.

Quello che vi propongo oggi è una semplice funzione per estrarre i primi caratteri di un testo.
Anche in una funzione così semplice debbono essere tenuti presenti alcuni requisiti:


  • devono essere estratte solo parole intere
  • se il testo supera la grandezza desiderata devono essere accodati dei punti di sospensione.
  • i punti di sospensione concorrono al conto del numero di caratteri



Ecco la funzione:



  public string GetAbstract(string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }



Se vogliamo proprio esagereare possiamo anche crearne un extension method per l'oggetto "String".
In questo modo possiamo estrarre un testo da ogni stringa.


public static class Extensions
    {
  public static string GetAbstract(this string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }
}

Divertitevi!

lunedì 4 febbraio 2013

Serializzazione e deserializzazione in c#

Nell'interscambio di dati è usuale utilizzare formati xml. Se usiamo c# come linguaggio di programmazione, ci sono dei metodi del framework che ci aiutano parecchio. Inoltre dalla versione 3.5 del framework potete usare gli "Exstension Method", ovvero potete dotare qualsiasi classe di metodi aggiuntivi, in relazione al tipo.
Combinando le due cose potete scrivere dei metodi per la serializzazione e deserializzazione di classi e renderli generici. Ad esempio:

Con i seguenti "Extension Method"


        /// <summary>
        /// Serializes to XML.
        /// </summary>
        /// <param name="value">The object to serialize.</param>
        /// <returns>
        /// a XElement rappresenting the class serialization
        /// </returns>
        public static XElement SerializeToXML(this object value)
        {
            XmlSerializer x = new XmlSerializer(value.GetType());
            XDocument doc = new XDocument();
            using (XmlWriter xw = doc.CreateWriter())
            {
                x.Serialize(xw, value);
                xw.Close();
            }
            return doc.Root;
        }


        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this string value)
        {
            XElement xElement = XElement.Parse(value);

            return xElement.Deserialize<T>();

        }

        /// <summary>
        /// Deserializes the specified string to an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value containing an xml.</param>
        /// <returns>
        /// an object of type T
        /// </returns>
        public static T Deserialize<T>(this XElement value)
        {
            XmlSerializer x = new XmlSerializer(typeof(T));
            T result;
            using (XmlReader xr = value.CreateReader())
            {
                result = (T)x.Deserialize(xr);
                xr.Close();
            }
            return result;
        }







In questo modo, per serializzare una classe dovrete semplicemente scrivere






MyClass a = new MyClass();

XElement xml = a.SerializeToXML();
MyClass b = xml.Deserialize<MyClass>(xml)