Extracting XML Schemas from XML

28 01 2010

This is a simple post do announce a tool that I’ve made today for creating XML Shemas from XML documents from the command line.

Well for my simplicity, the tool is not fully command line-like, but later I’ll fix that. The good use I’ve found was to pipe the schema produced to a file on the cmd.

This sounded me as a good tool to be avaliable on PowerShell. A future enhancement to be done.

Download Here!

References:

[1] http://msdn.microsoft.com/en-us/library/xz2797k1.aspx

[2] http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx





Introdução ao P/Invoke

25 01 2010

Segue abaixo um vídeo q fiz (nos moldes da série How do I que a Microsoft anda promovendo nos seus sites de aprendizado) para falar um pouco sobre interoperabilidade entre .NET Framework (C#) e DLL’s nativas escritas em C/C++.

Este será o primeiro vídeo de uma série sobre o tema. Opinem!





Ultra-som de Gabriel

29 10 2009

Uma das últimas dele. Ansioso demais pra que ele venha logo ao mundo!

Agora, o bico é da mamãe! kkkkkkkkk





Mail on PHP

28 10 2009

Many people have posted about this before, but exactly because is a basic matter, is good to post my opinion on this subject.

About 4 years ago, I had to create a PHP code to send e-mail, but may lack of know how made me forget to make the mail function to work out. Besides, not everytime you can make such fixes on your server. This lead me to create the mail using sockets and sending commands to the smtp server of my preference.

In that time, hotmail, yahoo and gmail allowed the use of the smtp commands by telnet without worries. They hadn’t implemented at all the security protocols, like ssl or tls. That’s a good thing they had implemented security, of course. But,… and programming? What’s the difference now?

You cant say that the old code will still work out fine. It really can’t! if you try the correct commands on the telnet, all you’ll get is the client disconnection on the 3rd command sent to server. Fortunately, PEAR have a implementation of the SMTP protocol and have everything there to be used.

To install the package on your development machine, just type on the console (as a root if you are on linux)

  1. pear install Net_SMTP
  2. pear install Mail

Then its just to use some code like the one below:

require_once 'Mail.php';

class MyMail{
	private $to;
	private $from;
	private $subject = "Testando envio autenticado pelo Google";
	private $body = "Teste efetuado com sucesso!";
	private $host = "ssl://smtp.gmail.com";
	private $port = 25;
	private $username;
	private $password;
	public function getTo(){
		return $this->to;
	}
	public function setTo($t){
		$this->to = $t;
	}
	public function getFrom(){
		return $this->from;
	}
	public function setFrom($f){
		$this->from = $f;
	}
	public function getSubject(){
		return $this->subject;
	}
	public function setSubject($s){
		$this->subject = $s;
	}
	public function getBody(){
		return $this->body;
	}
	public function setBody($b){
		$this->body = $b;
	}
	public function getHost(){
		return $this->host;
	}
	public function setHost($h){
		$this->host = $h;
	}
	public function getPort(){
		return $this->port;
	}
	public function setPort($p){
		$this->port = $p;
	}
	public function getUsername(){
		return $this->username;
	}
	public function setUsername($un){
		$this->username = $un;
	}
	public function getPassword(){
		return $this->password;
	}
	public function setPassword($p){
		$this->password = $p;
	}
	public function send(){
		$headers = array ('From' => $this->getFrom(),
                            'To' => $this->getTo(),
                            'Subject' => $this->getSubject());

		$smtp = Mail::factory("smtp", array ('host' => $this->getHost(),
                                          'port' => $this->getPort(), // SMTPS(para mais detalhes ver /etc/services
                                          'auth' => true,
                                          'debug' => true, // Debug ligado
                                          'username' => $this->getUsername(),
                                          'password' => $this->getPassword())
		);
		$rc = $smtp->send($this->;to, $headers, $this->body);
		if(PEAR::isError($rc)){
			echo("<h1>Error " . $rc->getMessage(). "</h1>");
		} else {
			echo("Email enviado com sucesso!!");
		}
	}
}

It’s a preliminary class, so, many enhancements can be made to make the class better, but it just works as expected. Example to use? see below:

        if(isset($_POST)){
            require_once 'MyMail.class.php';
            $ms = new MyMail();
            $ms->setFrom('me@gmail.com');
            $ms->setTo('noone@gmail.com');
            $ms->setHost('smtp.google.com');
            $ms->setPort('25');
            $ms->setUsername('me@gmail.com');
            $ms->setPassword('p@ssw0rd');
            $ms->setBody('Test Message using PHP');
            $ms->setSubject('Test');
            $ms->send();
	}

This will produce the following stream to be sent to the server:

DEBUG: Recv: 220 mx.google.com ESMTP 23sm733843qyk.3
DEBUG: Send: EHLO localhost

DEBUG: Recv: 250-mx.google.com at your service, [189.70.93.58]
DEBUG: Recv: 250-SIZE 35651584
DEBUG: Recv: 250-8BITMIME
DEBUG: Recv: 250-STARTTLS
DEBUG: Recv: 250-ENHANCEDSTATUSCODES
DEBUG: Recv: 250 PIPELINING
DEBUG: Send: STARTTLS

DEBUG: Recv: 220 2.0.0 Ready to start TLS
DEBUG: Send: EHLO localhost

DEBUG: Recv: 250-mx.google.com at your service, [189.70.93.58]
DEBUG: Recv: 250-SIZE 35651584
DEBUG: Recv: 250-8BITMIME
DEBUG: Recv: 250-AUTH LOGIN PLAIN
DEBUG: Recv: 250-ENHANCEDSTATUSCODES
DEBUG: Recv: 250 PIPELINING
DEBUG: Send: AUTH LOGIN

DEBUG: Recv: 334 VXNlcm5hbWU6
DEBUG: Send: ZmFiaW8uY2VzYXIubWVkZWlyb3NAZ21haWwuY29t

DEBUG: Recv: 334 UGFzc3dvcmQ6
DEBUG: Send: ZG1hdGRtYXQwMQ==

DEBUG: Recv: 235 2.7.0 Accepted
DEBUG: Send: MAIL FROM:<sender-mail@gmail.com>

DEBUG: Recv: 250 2.1.0 OK 23sm733843qyk.3
DEBUG: Send: RCPT TO:<receiver-email@gmail.com>

DEBUG: Recv: 250 2.1.5 OK 23sm733843qyk.3
DEBUG: Send: DATA

DEBUG: Recv: 354  Go ahead 23sm733843qyk.3
DEBUG: Send: From: sender-email@gmail.com
To: receiver-email@gmail.com
Subject: Teste de e-mail

Teste de E-mail via Sockets
.

DEBUG: Recv: 250 2.0.0 OK 1256749304 23sm733843qyk.3
DEBUG: Send: QUIT

DEBUG: Recv: 221 2.0.0 closing connection 23sm733843qyk.3




First (?) Announcement of Windows 7 Failure

8 09 2009

Today on twitter, @lauromoura has tweet a report about a Windows 7 failure. See the link:

http://seclists.org/fulldisclosure/2009/Sep/0039.html

Worth to see, what Steve Ballmer said on Vista’s release and the press opinions: here.

Fact: no Windows (and no Operating System) will be totally secure. It’s all just a matter of time.





Microsoft Training Kits

3 09 2009




Searching columns by type

16 06 2009

Today I went to review the SQL Server 2008 enhancements on XML support. To test the queries on AdventureWorks, the first thing I needed to know was: “Where are the XML data columns?”

I don’t actually have the graphic on the database model to search for and wasn’t on the mood to create the database diagram to search visually for the XML columns.

Then, I’ve got the idea of searching on the catalog for that. It should be simple to do (and it was!) but worth the post, as many people may have the need to use the same thing, not only on AdventureWorks, but on large (I mean many tables) databases:

Here is the script:

SELECT t.name, c.name, ty.name
  FROM sys.tables t INNER JOIN sys.columnsON
          (t.object_id = c.object_id)
      INNER JOIN sys.systypes ty ON
          (c.system_type_id = ty.xtype)
WHERE ty.name = ‘xml’

With this script, you can create a procedure that returns the table name and the column name that uses a type that’s passed by a parameter. Or even create a PowerShell function to achieve this. Let’s see the latter:

param([string] $typeName, [string] $server, [string] $database)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection "server=$server;database=$database;Integrated Security=sspi"
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "SELECT t.name [Table], c.name [Column]
                                                  FROM sys.tables t INNER JOIN sys.columns c
                                                          ON (t.object_id = c.object_id) 
                                                                           INNER JOIN sys.systypes ty 
                                                          ON (c.system_type_id = ty.xtype)
                                               WHERE ty.name = ‘$typename ‘"
$sqlReader = $sqlCommand.ExecuteReader()
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($sqlReader);
$sqlConnection.Close()
Write-Output $dataTable

Interesting, huh?





MCTS: SQL Server 2005

16 06 2009

Bem, um pouquinho tarde, mas enfim, passei nesse sábado na prova 70-431: Microsoft SQL Server 2005 – Implementation and Maintenance, inaugurando a minha intenção de me especializar em banco de dados.

A prova é composta de duas partes, uma com 35 questões objetivas, e outra com 12 questões de simulação. A parte objetiva é bem tradicional, e pelo menos as questões que foram selecionadas na minha prova foram bem distribuídas nos assuntos. Houveram questões de XML, de desenvolvimento com CLR, backup/restore, … acho que só não caiu de Service Broker. Na parte prática, tive sorte e das 12 questões, 4 foram sobre backup/restore (para configurar um backup de acordo com algumas características pedidas).

Agora é estudar pra atualizar pra MCTS: SQL Server 2008!





Windows 7 RC is released

5 05 2009

Yeah testers, the new Windows has just been released for testing. It’s avaliable here.

Microsoft recommends that you don’t upgrade from beta to RC, but reinstall from scratch.

Enjoy it! Test it!





Backup no SQL Server 2008

25 04 2009

Este vai ser um post sobre um tema introdutório para administradores de banco de dados. Uma tarefa comum que deve ser realizada de tempos em tempos e pela sua importância, é importante que ocorra com frequência, para que se tenha segurança com relação a algum desastre que possa acontecer… ninguém sabe quando um erro pode ocorrer, ou quando os dados podem ficar corrompidos, por esse ou aquele motivo.

Dentro do SQL Server 2008, os backups podem ser feitos de algumas formas:

  • Full
    • Faz o backup de todo o banco de dados. Isso inclui não somente o arquivo de dados mas também o log de transações, e com isso representam todo o banco de dados num determinado momento do tempo.
    • Sintaxe: BACKUP DATABASE <NOME_DO_DATABASE> TO DISK =<CAMINHO_PRO_ARQUIVO_DE_BACKUP>;
    • Ex.: BACKUP DATABASE teste TO DISK = N’C:\Backups\teste.bak’;
  • Differential
    • Não confundir com backup incremental. Este backup diz respeito as diferenças ocorridas no banco de dados após o último full backup. Um backup incremental armazenaria as diferenças entre o momento atual e o último backup (que não necessariamente seria full);
    • De acordo com o que foi exposto acima, não é possível então, fazer um backup diferencial sem antes ter feito um backup full;
    • Por manipularem somente as diferenças entre um backup full e o estado atual, tendem a ser sempre backups mais rápidos de serem executados, e menores no espaço em disco ocupado;
    • Sintaxe: BACKUP DATABASE <NOME_DO_DATABASE> TO DISK <CAMINHO_PRO_ARQUIVO_DE_BACKUP> WITH DIFFERENTIAL;
    • Ex.: BACKUP DATABASE teste TO DISK = N’C:\Backups\teste.bak’ WITH DIFFERENTIAL;
  • Log Full
    • Realiza o backup total do log de transações;
    • Sintaxe: BACKUP LOG <NOME_DO_DATABASE> TO DISK <CAMINHO_PRO_ARQUIVO_DE_BACKUP>;
    • Ex.: BACKUP LOG teste TO DISK = N’C:\Backups\teste.trn’ WITH DIFFERENTIAL;
  • Log Differential
    • Realiza o backup diferencial do log de transações;
    • Sintaxe: BACKUP LOG <NOME_DO_DATABASE> TO DISK <CAMINHO_PRO_ARQUIVO_DE_BACKUP> WITH DIFFERENTIAL;
    • Ex.: BACKUP LOG teste TO DISK = N’C:\Backups\teste.trn’ WITH DIFFERENTIAL;

Apesar de usarmos as extensões bak e trn, não há obrigatoriedade dessas extensões, sendo somente uma boa prática as que foram usadas nos exemplos.

No SQL Server 2008 foi introduzida uma novidade que é a compressão de backup. Por default este é um recurso que está desativado. Para poder usar como um recurso padrão para todos os backups, primeiro é preciso reconfigurar a base de dados, com:

sp_configure ‘backup compression default’, 1;
go

reconfigure;

Com isso, habilitamos no servidor a compressão de backup por default, o que significa que todo banco de dados terá backups comprimidos. Foi então adicionada a query de backup a opção do with COMPRESSION ou NO_COMPRESSION, para que se possa escolher na query se se deseja um backup comprimido ou não.

Além destas formas, também é possível usar a simples estratégia de Attach/Detach que é extremamente conveniente, quando se pode deixar o banco off-line por algum tempo.

[1] White Paper sobre compressão de backup no SQL Server 2008
[2] Backing Up and Restoring How-to Topics
[3] Copy-Only Backups
[4] Full Database Backups
[5] Differential Database Backups