Posts

RAII in C++

Spanish version / Versión en Español RAII is an acronym which means "Resource Acquisition Is Initialization". And what's it about? It'a low level design pattern, what some call "idiom". Its aim is to ease and ensure resource deallocation. Resources include file handles, bitmaps, data base connections, heap memory, etc. RAII was created by Bjarne Stroustrup, the face of the team which created C++. Even though RAII was born in C++, it's so general that it can be used in any object oriented language with an exception handling mechanism. It can even be implemented in languages which do not meet these requirements, but it is not so trivial and might not be worth the hassle. The idea is quite simple: allocate the resource ONLY in the constructor and deallocate it ONLY in the destructor. Hence the name RAII: When we initialize the object (call the constructor), we acquire the resource. Initialization is acquisition. Acquisition is Initialization. T...

RAII en C++

Versión en inglés / English version RAII es un acrónimo que significa "Resource Acquisition Is Initialization". ¿Y de qué se trata? Es un patrón de diseño de bajo nivel, lo que algunos teóricos llaman "idiom". El problema que busca resolver es facilitar y asegurar la liberación de recursos (archivos, bitmaps, conexiones a base de datos, memoria del heap, etc). La creación de RAII corresponde a Bjarne Stroustrup, líder del equipo creador de C++. Pese a haber nacido en ese lenguaje, RAII es tan general que puede usarse fácilmente en cualquier lenguaje orientado a objetos con manejo de excepciones. Incluso puede implementarse en otros lenguajes, pero no es tan trivial y por ende puede no valer la pena. La idea es muy simple: adquirir el recurso SÓLO en el constructor y liberarlo SÓLO en el destructor. De ahí el nombre RAII: al inicializar (construir) el objeto, adquirimos el recurso. Esto ata el uso del recurso a la vida del objeto, y nos evita andar pensa...

SQL: Export a SQL Server 2008 DB to SQL Server 2005

Spanish version / Versión en Español Since the 2008 version uses a different format for .bak files, a backup done in 2008 cannot be restored from 2005. A possible workaround is is creating, in 2008, a Script targeted at 2005, and run that scrit in 2005. The steps: Open Managment Studio 2008 and connect to the instance in which the DB we wanna export is. Right click the database, and hit Tasks->Generate Scripts. Hit Next in the initial Dialog. Check "Script all objects in the selected database" before hitting Next. This guarantees that not only the schema is exported, but the contents too. In the next dialog, we have lots of options. The ones we have to set before hitting Next are the following: Script for Server Version : SQL Server 2005. Script Data : True. If the DB to export wasn't created in the 2005 server, which is usually the case, set 'Script Database Create' to 'True'. Select 'Script to File...

SQL: Exportar una Base de Datos de SQL Server 2008 a SQL Server 2005

Versión en inglés / English version Dado que la versión 2008 usa un formato diferente para los .bak, un backup hecho en la versión 2008 no puede ser restaurado desde la 2005. La solución es crear, desde 2008, un Script cuyo target sea la versión 2005 y ejecutar ese script en la instancia del 2005. Para hacerlo: Abrir el Management Studio 2008 donde está la BD que queremos exportar. Darle click derecho a la BD y seleccionar Tasks->Generate Scripts. Darle Next al diálogo inicial. Marcar la checkbox que dice "Script all objects in the selected database" antes de darle Next al diálogo siguiente. Esto garantiza que no sólo se exporte el esquema de tablas sino también su contenido. En el próximo diálogo, hay varias opciones. Las que nos interesa setear antes de darle Next son las siguientes: Script for Server Version : SQL Server 2005. Script Data : True. Si la base de datos a importar aún no existe en el server 2005, hay que poner '...

MSBuild: How to develop a Custom Build Task

Spanish version / Versión en Español My problem: When compiling a VB.NET project, I wanted to read a key from a .config file. According to the value of that key, decide which native dll's to copy to the target directory. My solution: First of all, remember that every C#, VB.NET or C++ Visual studio project is an MSBuild script (I guess F# projects too), which is somewhat similar to a Nant build script. It's an XML file with a special schema defined by Microsoft. The XML tags of interest are Target, which are made up mainly of Task tags. In other words, a Target can call Tasks. The .NET framework offers a bunch of predefined MSBuild Tasks, which are documented in the MSDN. However, if those are not enough, we can quite easily write and use our own tasks. An MSBuild custom task must be defined in a dll, which must be referenced from the MSBuidl script which calls it. We'll see how soon. So, the first step is creating a C# project (I guess VB.NET or any other p...

MSBuild: Cómo hacer una Custom Build Task

Versión en inglés / English version Mi problema: Al compilar, quería ver el valor de una key de un archivo .config (o sea, con la estructura de los app.config que genera el Visual Studio). En base a ese valor, decidir si copiar o no ciertas dlls. Mi solución: Ante todo, recordemos que todo proyecto C#, VB.NET o C++ del Visual Studio es un script de MSBuild, o sea muy parecido a un .build de NAnt. Está compuesto, entre otras cosas, de Targets, que a su vez consisten en invocaciones de Tasks. En .NET, hay varias Tasks predefinidas, pero si uno quiere escribir una propia, el framework provee un mecanismo para hacerlo. Eso es lo que veremos. Una custom task debe ser definida en una dll, la cual debe ser referenciada desde un script de MSBuild (recordemos que todo archivo de proyecto C#, VB.NET o C++ es un script de MSBuild). Entonces, el primer paso es crear un proyecto de C#, de tipo Class Library. En dicho proyecto, debemos crear una clase que herede de Task y que tenga s...

Visual Studio 2010: Find and Replace using Regular Expressions

Image
Spanish version / Versión en Español This is not something introduced by Visual Studio 2010, but I'm a late bloomer. I'm quite sure that at least 2008 and 2005 also have it. Let's say we have a test class which opens a bunch of files, and that it has a lot of hardcoded relative paths like this: class FactoryImage{ public static IEnumerable ImageTestCases{ get{ //9 bits, Signed, Monochrome1 yield return new TestCaseData(new ImageParameters { FileName = ".\\ImagesTest\\DavidClunie\\MONOCHROME1\\Signed\\9SignedMonochrome1_512x512_LE.pix", //Rawdata, example image FileNameWhite = ".\\ImagesTest\\DavidClunie\\MONOCHROME1\\Signed\\9SignedMonochrome1_512x512_LEWhiteImage.pix", //Rawdata, white example image //More fields... }); //9 bits, Unsigned, Monochrome1 yield return new TestCaseData(new ImageParameters{ FileName = ".\\ImagesTest\\Da...