Tag Archives: .Net

Remove duplicated whitespaces on C#

The Trim method on C# only removes whitespaces at the beginning and at the end of a string, but it does not remote duplicated whitespaces inside the string (like the Trim function on VB for Apps), which is very handy sometimes.

One of the ways to do it on C#, is using Regular Expressions. This method will not only remove whitespaces but also tabs and line breaks, and will replace them with one whitespace.

string s1 = "He saw   a cute\tdog.\nThere\n\twas another sentence.";
Regex r = new Regex(@"\s+");
string s2 = r.Replace(s1, @" ");
// The result would be: He saw a cute dog. There was another sentence.

You will need to add the reference to System.Text.RegularExpressions to your namespace.
Source: Dot Net Perls

Concatenate text on NVelocity

There is no operator to concatenate two strings in NVelocity (the .Net version of Velocity) like we can do on other languages like C# or PHP, with the plus (+) operator for the first one and dot (.) for the second one. For example, in C# we would do:

string strHello = "Hello " + "World";

And in PHP:

$hello = "Hello " . "World";

But in NVelocity, what we must do if we need to do this same thing would be:

#set ($str1 = "Hello ")
#set ($str2 = "World")
The concatenated string would be: $str1$str2

Source: Velocity User Guide

Convert a String to a Stream

In C#, to convert a String into a Stream object, we need to use the GetBytes method (from the Encoding.ASCII package), this way:

byte[] bytes = Encoding.ASCII.GetBytes(xmlContent);

And then, use that byte array when instantiate a Stream (for example, MemoryStream or FileStream):

MemoryStream stream = new MemoryStream(bytes);

Convertir un IList en un Array

Existen algunas formas de hacerlo, acá les dejo un par.

Primera forma:

//list es del tipo IList
ArrayList arr = new ArrayList(list);
Item[] items = (Item[])arr.ToArray(typeof(Item));

Otra forma:

Item[] items = new Item[list.Count];
list.CopyTo(items, 0);

SQL Server’s nvarchar(max) on Castle ActiveRecord

I’m using the new SQL Server 2005’s data type nvarchar(max) on a .Net project (ntext has been deprecated in this version) in conjuction with Castle ActiveRecord. For a complete integration (including schema creation), ActiveRecord property should looks like this:

[Property("description", ColumnType = "StringClob", SqlType = "nvarchar(MAX)")]

ColumnType = “StringClob” avoids text to be truncated if it gets too long. SqlType = “nvarchar(MAX)” forces the field to be created as that data type, otherwise, it will be created as nvarchar(255).

A more detailed explanation can be found here and here.

Diferencia entre ICollection e IList en C#

Los elementos dentro de un ICollection (para ser más exactos, los elementos dentro de una clase que implemente una interfaz ICollection) no tienen un orden específico. En un momento pueden estar ordenados de una manera, y en otro, sin alguna razón aparente, ordenados de otra forma.

En cambio, los elementos de un IList si tienen un orden establecido y relevante, como un arreglo. Esto permite agregar elementos en una ubicación específica. Además, los elementos van a permanecer en la posición asignada hasta que decidamos moverlos.

Además de estas dos interfaces, existe también IDictionary, que exitiende a ICollection. Este permite almacenar parejas de elementos (clave, valor), similar a como lo hace un diccionario de palabras (cada palabra tiene un significado). Al igual que en el ICollection, estos elementos no tienen un orden específico.

Obtener el MimeType de un archivo desde C#

No he encontrado una manera directa de hacerlo, pero encontré esta función que busca la extensión del archivo en el registro de windows y si está registrada, obtiene su tipo mime.

private string getMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

Aún no la pruebo, pero según loque leí, funciona bien. Los post originales están acá y acá.