Visualizzazione post con etichetta c#. Mostra tutti i post
Visualizzazione post con etichetta c#. Mostra tutti i post

mercoledì 31 luglio 2013

C# - Convertire un numero in una base qualsiasi

Recentemente ho dovuto sviluppare un'integrazione con il servizio di spedizioni SDA. Per la generazione di alcuni Tracking Number ho dovuto creare dei progressivi, utilizzando una sequenza di numeri e lettere, secondo le specifiche di SDA.

Questo mi ha portato a voler creare una funzione di supporto per poter convertire un numero in una base qualsiasi, determinata da ad un array di caratteri.


        /// <summary>
        /// Converts a value to a custom base.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="baseChars">The base chars.</param>
        /// <returns></returns>
        private static string ConvertToBase(int value, char[] baseChars)
        {
            string result = string.Empty;
            int targetBase = baseChars.Length;

            do
            {
                result = baseChars[value % targetBase] + result;
                value = value / targetBase;
            }
            while (value > 0);

            return result;
        }


Per convertire ad esempio un numero es 8258, in base 2 basta scrivere


int value = 8258;
string baseTwoResult = ConvertToBase(value, new char[] { '0', '1' });


Il risultato sarà "10000001000010"



Per convertire un numero secondo la base di SDA ho dovuto fare così:

int value = 8258;
var chars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
string baseSDAResult = ConvertToBase(value, chars);

Il risultato è : "GNO"


Spero possa essere utile anche a qualcun altro.

sabato 22 giugno 2013

.NET - Errori comuni - Concatenazione di stringhe

Buongiorno a tutti.
oggi volevo condividere con voi uno di quegli "errori" che comunemente si commettono nella programmazione .NET. La concatenazione di stringhe. Spesso, per distrazione o per fretta, la concatenazione di stringhe viene fatta in ambiente .NET usando l'operatore "+". Il risultato che si ottiene è ovviamente quello desiderato, ma potrebbe avere gravi ripercussioni sulle performance del nostro applicativo. Mi spiego meglio:


  • Nel framework .NET le stringhe sono oggetti IMMUTABILI e pertanto le operazioni di modifica ad esse applicate non modificano la stringa di partenza, ma ne creano una nuova.
  • L'oggetto che deve essere usato per la manipolazione delle stringhe è "System.Text.StringBuilder", il quale non lavora con stringhe, ma con Stream di dati.

provate a creare una Console Application e sostituire il metodo main con il seguente:


 static void Main(string[] args)
        {
            /* test with + operator */
            DateTime start = System.DateTime.Now;

            string resultString = string.Empty;

            for (int i = 0; i < 50000; i++)
            {
                resultString += "123456789abcdefghilmnopqrstuvz";
            }
            TimeSpan t = (System.DateTime.Now - start);

            Console.WriteLine(string.Format("Test with + operator. Time : {0}:{1}:{2}:{3}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds));


            /* Test with StringBuilder */
            start = System.DateTime.Now;

            StringBuilder resultStringBuilder = new StringBuilder();

            t = (System.DateTime.Now - start);
            
            for (int i = 0; i < 50000; i++)
            {
                resultStringBuilder.Append("123456789abcdefghilmnopqrstuvz");
            }

            Console.WriteLine(string.Format("Test with StringBuilder. Time : {0}:{1}:{2}:{3}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds));

            Console.ReadLine();
        }


il risultato ottenuto sul mio computer è il seguente:


Senza parole vero?


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)