Oct 6, 2007

New challenges.

This week I've joined db4objects team to contribute with the .Net development side (but I'm pretty sure I'll do a lot of Java development also). Indeed it has been a busy week; lots of new concepts and code to get to know, new management style, new tools, etc. I'll be working from my home (cool!!), collaborating with a distributed (talented) development team through skype. Some may call me crazy but db4objects have a cool product to work with and this opportunity will let me dedicate more time to my family, to study new topics (related to computers, of course), to watch movies, etc (I know, studies proved that working in home means to work more, but I'll get some spare time cause I'll not be required to go to jammed traffic :) Also, you can expect to see more posts on this blog covering db4o ;) Well, that's it. Adriano

Sep 18, 2007

Minor db4o tutorial problem

Some time ago I started playing with db4objects, an object oriented database for Java and .Net.

After installing db4o it started this tutorial (C:\Program Files (x86)\Db4objects\db4o-6.3\doc\tutorial\Db4objects.Db4o.Tutorial.exe, on my 64 bits Windows Vista Box) and everything went as smooth as possible but, when I tried to restarted it in the next day, it failed and the following dialog was shown:


Looking at this dialog we can see that the program failed to delete a file called formula1.yap under C:\Program Files (x86)\Db4objects\db4o-6.3\doc\tutorial\ folder; so I launched Process Monitor and pushed Reset button in tutorial program again.


It just confirms that the tutorial is failing to delete the file but why? Worse, why have it worked when we started it for the first time?

The .Net tutorial that comes with db4o has some minor bugs related to the way Windows Vista x64 handles writes to some specific paths, more specifically to %ProgramFiles% and %ProgramFiles(x86)% folders.

It's a Windows Vista feature called UAC (for detailed information about this topic please refer to this technet article) that prevents standard users (non administrators) from writing to some folders/registry keys, basically to keep the system more stable and secure. Actually it worked in the first time because

Ok, so how to fix this problem?

Basically there are 3 different approaches that can be applied:
  • The "Quick and Dirty" way (probably the easiest and fastest one) is to run the tutorial as an administrator. To do this just right click on the tutorial program and select "run as administrator".




  • The second one consists in adding a manifest next to the tutorial program ( (warning: Windows Vista/.Net will cache the tutorial program and will not pick you fresh manifest :(. In this case you can just "touch" the tutorial program -- or move it to another folder -- and Windows will load the manifest in the next time you start it as explained here). This simply instructs Windows to start the program with administrator rights.



  • The last one (and in my opinion the correct one) consists in fixing the tutorial in order to save this file under %LocalAppData% (or %AppData%) instead of its installation folder (thats the recommended action by Microsoft).



That's all folks ;)

In a future post I'll discuss a bit more about a UAC feature called File System and Registry Virtualization and why it wasn't applied in this case.

Sep 10, 2007

Another post in the series RTFM :)

As I've said in my last post, I'm reading C# 3.0 specification. Well, it's amazing what you can learn when you do take the time to learn more about the tools (in this case, the language) you use all day long :). This time I've find out that it's possible to use reserved words as identifiers! Amazing! (and of course, dangerous as it make it harder to read your code.) But this isn't a new feature of C# 3.0; it works with C# 2.0 (.Net Framework 2.0)! Just copy the following sample and compile it using CSharp compiler from .Net Framework 2.0!
public class @class
{
   private static void Main()
   {
      int @int = 10;
      int @delegate = @int + 30;;
      System.Console.WriteLine("Values {0} {1}", @int, @delegate);
   }
}
What do you think about using reserved words as identifiers? Let the world know your opinion! :) Adriano

Sep 4, 2007

?? Operator.. What is it good for?

Hi, Other day I was poking around C# 2.0 documentation and noted a different operator I had never seen before, ?? so I thought with myself: what is it good for? Well, after reading the documentation (remember, RTFM :) I couldn't believe I didn't known this before! The ?? operator is a binary operator that checks the left operand against null. If it is null, the expression result is the right operand value otherwise (left operand is not null) it will be the left operand value. See a sample:
string name = null;
Console.WriteLine("Value: {0}", name ?? "(null)"); // Writes: Value: (null)

name = "Adriano";
Console.WriteLine("Value: {0}", name ?? "(null)"); // Writes: Value: Adriano

Also, it is useful when used in conjunction to nullable value types.
int? i = null;
Console.WriteLine("Value: {0}", i ?? -1); // Writes: Value: (null)

i = 20;
Console.WriteLine("Value: {0}", i ?? -1); // Writes: Value: 20
PS: I've just started to play with
C# 3.0 (Visual Studio 2008 beta 2) and it seams to be a very strong language. PS2: Finally I managed to get SyntaxHighlighter to work with blogger (thanks to this post) As soon as I got more information I'll post my impressions here :) See you soon!

Mudanças

Depois de ponderar algum tempo sobre o assunto estou considerando utilizar o inglês nos próximos posts. Porque esta decisão?
  • Basicamente entendo que a maioria das pessoas que possam vir a se interessar pelo conteúdo deste blog não teriam problemas para ler conteúdo (pelo menos técnico) em inglês.
  • Escrever em inglês me ajudaria a melhorar meus conhecimentos neste idioma.
  • Adotar o inglês tornaria este blog mais acessível a outras pessoas que não conhecem o português
Se você acompanha este blog e prefere que o conteúdo continue em português deixe um comentário. Dependendo do número de pessoas posso não mudar para o inglês ou então posso postar nos dois idiomas :) Adriano.

Aug 28, 2007

Silencio...

Já faz algum tempo que não posto nada... o motivo, como todos já devem saber, é a absoluta falta de tempo, afinal de contas, tenho que me dedicar à obra de Deus, minha esposa, filha e aos jogos (need for speed rules!) ;) Como estou um pouco sem tempo para escrever um post mais interessante vou apenas listar algumas coisas com a qual tenho me envolvido atualmente:
  • Object Mocking em .Net (comecei a utilizar o Rhino.Mocks)
  • OODB, ou seja, Object Oriented Databases (estou estudando o DB4O)
  • Estou escrevendo um artigo sobre um dos novos recursos do Windows Vista (e também do Windows Server 2008), o KTM, ou, gerenciador de transações do Kernel, para uma revista sobre .Net.
  • Lendo alguns livros, principalmente um sobre WCF.
  • Etc.
É mais ou menos isso :) []'s Adriano

Jun 15, 2007

Stream de dados alternativas

Para muitos usuários (e mesmo desenvolvedores) do Windows o conceito de arquivo esta tão sedimentado que muitas vezes melhorias significativas no sistema de arquivos deste sistema operacional (no caso o NTFS) são ignoradas.

Neste post apresento um dos recursos mais desconhecidos, stream alternativas de dados ou ADS (do inglês, Alternate Data Stream).

Para compreendermos este recurso é necessário primeiro definirmos (ou relembrarmos) alguns conceitos:

  • Uma stream de dados nada mais é que um conjunto de bytes arranjados de forma seqüencial.
  • Um arquivo é composto por uma ou mais streams de dados.
  • Streams de dados possuem um nome associado através do qual a mesma é referenciada. A regra básica para formação do nome de streams é: nome-arquivo.ext:nome-stream:tipo-stream
  • O nome da stream pode conter qualquer caracter válido para um nome de arquivo.

Como o Windows não possui meios (tanto no Explorer quanto no console) para detectar / mostrar arquivos que possuem ADS, abaixo listei algumas ferramentas úteis para tal finalidade:

Usando ADSs

A forma mais simples para demonstrarmos este conceito é através do console do Windows. Abra o console (cmd.exe) e digite:

echo teste de streams > teste.txt:dados

Simples assim! O comando acima cria uma stream chamada dados com o conteúdo teste de streams.

Agora você pode conferir que o arquivo teste.txt foi criado mas o comando dir reporta o mesmo com 0 (zero) bytes.

Finalmente, para visualisar o conteúdo da stream digite

more < teste.txt:dados

Abaixo apresento um pequeno programa de exemplo para criar ADSs (note que o mesmo não possui nenhum tratamento especial, ou seja, a forma de acessar data streams alternativas é idêntica à utilizada para acessar a data stream default).

#include "stdio.h"
#include "Windows.h" 
void main(int argc, char *argv[])
{
    HANDLE handle;
    if (argc < 3)
    {
        printf("Nome da stream (formato: arquivo.ext:stream) ou dados nao especificados.\r\nUso: ads.exe nome-stream dados");
        return;
    }
    else    
    {
        printf("\r\nGravando dados em %s", argv[1]);
    }
    
    handle = CreateFile(argv[1], 
                        GENERIC_WRITE, 
                        0, 
                        NULL, 
                        OPEN_ALWAYS, 
                        0, 0);
                        
    if (handle != INVALID_HANDLE_VALUE)
    {
        DWORD numberOfBytesWritten;
        int n = WriteFile(  handle, 
                            argv[2], 
                            strlen(argv[2]), 
                            &numberOfBytesWritten, 
                            NULL);
                            
        printf("\r\n%ld bytes gravados", numberOfBytesWritten);
        
        CloseHandle(handle);
    }
    else
    {
        printf("Não foi possivel criar a stream de dados.");
    }
}
[Editado: Correção de um erros de português]

experimente executar o programa com alguns parâmetros como por exemplo:

ads teste.txt:dados "Teste de streams"

É isso ai.

Até a próxima.