Posts

C++: Capture Windows Messages from an MFC app without using MFC

Spanish version / Versión en Español Let's say you need your C++ dll to communicate with a third party dll which uses MFC and Windows Messages to send data and notifications. The easiest way out would be to write an MFC application with a dialog which handled those messages. But let's say your C++ dll is at a very low layer and you don't want GUI code there. At least not openly. Well, there is no avoiding the Windows Messages, so we'll be using, at least, the Win32 unmanaged API. So how do we capture Windows Messages without showing a window? Some basic things you should know first: To capture Windows Messages, you must create a window (associated with a HWND) and use its message loop There is one message loop per thread. This implies that the message-handling window must live in the same thread as the message-generating code A window can be created as a Message-Only window , in MSDN jargon. And that's what we'll do Once I learned all of ...

C++: Capturar Windows Messages de una aplicación MFC sin usar MFC

Versión en inglés / English version Supongamos que necesitamos que nuestra dll C++ se comunique con una biblioteca externa que use MFC y Windows Messages para enviar datos y notificaciones. La forma más sencilla de establecer esa comunicación sería escribiendo una aplicación MFC con un diálogo (una clase que herede de CDialog) que maneje los mensajes generados por la biblioteca externa. Pero supongamos que nuestra dll C++ está en una capa de bajo nivel y no queremos meter una interfaz de usuario ahí. Al menos, no abiertamente. No hay forma de evitar los Windows Messages, así que tendremos que usar, mínimamente, la API Win32 nativa. Entonces, ¿Cómo capturamos Windows Messages sin mostrar una ventana? Antes de seguir, debemos saber lo siguiente: Para capturar Windows Messages, hay que crear una ventana (asociada a un HWND) y usar su message loop Hay uno y sólo un message loop por thread. Esto implica que la ventana que atrape los mensajes y su message loop deben vivir ...

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...