quarta-feira, 21 de julho de 2010

Listando arquivos de um diretório especificado

DirectoryInfo dir = new DirectoryInfo("C:\\");
FileInfo[] arquivos = dir.GetFiles("*.*");
foreach (FileInfo arquivo in arquivos)
    Console.Write(arquivo.Name);

Listando sub-diretórios de um diretório especificado

DirectoryInfo dir = new DirectoryInfo("C:\\");
DirectoryInfo[] diretorios = dir.GetDirectories();
foreach (DirectoryInfo diretorio in diretorios)
   Console.Write(diretorio.Name);

Listando drivers disponíveis

string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
      Console.Write(drive);

Reduzindo o tamanho de uma imagem

Fonte:
http://social.msdn.microsoft.com/Forums/pt-BR/aspnetpt/thread/0bb016f3-9260-489e-b5b0-0b44df66dfa7

Obs.:
Adaptado por Marcos Guedes (Programação Brasil).


Como utilizar:
TrataImagem objImg = new TrataImagem();
// Reduz o tamanho da imagem com 25% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino25.jpg", 25);

// Reduz o tamanho da imagem com 50% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino50.jpg", 50);

// Reduz o tamanho da imagem com 100% de qualidade
objImg.reduzir("c:\\caminhoImagemOrigem.png", "c:\\caminhoImagemDestino100.jpg", 100);



Código da Classe:
using System;
using System.Drawing;
using System.Drawing.Imaging;

class TrataImagem
{
    public void reduzir(string caminhoArquivoOriginal, string caminhoArquivoDestino, long qualidade)
    {
        Bitmap myBitmap;
        ImageCodecInfo myImageCodecInfo;
        Encoder myEncoder;
        EncoderParameter myEncoderParameter;
        EncoderParameters myEncoderParameters;

        // Create a Bitmap object based on a BMP file.
        myBitmap = new Bitmap(caminhoArquivoOriginal);

        // Get an ImageCodecInfo object that represents the JPEG codec.
        myImageCodecInfo = GetEncoderInfo("image/jpeg");

        // Create an Encoder object based on the GUID

        // for the Quality parameter category.
        myEncoder = Encoder.Quality;

        // EncoderParameter object in the array.
        myEncoderParameters = new EncoderParameters(1);

        // Save the bitmap as a JPEG file with quality level 25.            
        myEncoderParameter = new EncoderParameter(myEncoder, qualidade);
        myEncoderParameters.Param[0] = myEncoderParameter;
        myBitmap.Save(caminhoArquivoDestino, myImageCodecInfo, myEncoderParameters);
    }

    private static ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }
}

Excluindo um diretório e todo o seu conteúdo

string caminho = @"C:\seuDiretorio";
DirectoryInfo diretorio = new DirectoryInfo(caminho);
diretorio.Delete(true);

ProperCase

public string properCase(string entrada)
{
    entrada = entrada.ToLower();
    string sProper = "";

    char[] seps = new char[] { ' ' };
    foreach (string ss in entrada.Split(seps))
    {
        sProper += char.ToUpper(ss[0]);
        sProper +=
        (ss.Substring(1, ss.Length - 1) + ' ');
    }
    return sProper;
}
Fonte:
http://java2s.com/Code/CSharp/Data-Types/Showstringinpropercase.htm

Verificando conexão com a internet

Como chamar:
if (isConnectedDLL())
{
    // Com internet!
}
else
{
    // SEM internet!
}


A função:
using System.Runtime.InteropServices;

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        
public bool isConnectedDLL()
{
    ///
    /// Fonte: http://social.msdn.microsoft.com/Forums/pt-BR/vscsharppt/thread/837efe78-19c3-4cd1-a4f9-93df16d16acb
    ///
    
    int desc;
    return InternetGetConnectedState(out desc, 0);            
}

Verifica se existe uma url está acessível

Como usar:
if (isConnectadURL())
{
    // URL acessível!
}
else
{
    // URL não acessível!
}

A função:
using System.Net;

public bool isConnectadURL()
{
    ///
    /// Fonte: http://www.portugal-a-programar.org/forum/index.php?topic=34048.0
    ///
    bool fail;

    System.Uri Url = new System.Uri("http://www.google.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

    WebRequest WebReq;
    WebResponse Resp;

    WebReq = WebRequest.Create(Url);

    try
    {
        Resp = WebReq.GetResponse();
        Resp.Close();
        WebReq = null;
        fail = true; //consegue conexão à internet                
    }

    catch
    {
        WebReq = null;
        fail = false; //falhou a conexão à internet                
    }            

    return fail;            
}


Nota: pode ser usado para verificar conexão com a internet

Utilizando a função ShellExecute

Como utilizar:
abrirURL("http://forum.programacaobrasil.com");
abrirURL("C:\\arquivo.doc");

A função:
using System.Runtime.InteropServices;

[DllImport("shell32.dll")]
private extern static int ShellExecute(int HWND, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

public int abrirURL(string url)
{
    ///
    /// Autor: Marcos Guedes
    /// Email: [Você precisa estar registrado e conectado para ver este link.]
    ///
    return ShellExecute(0, "open", url, "", "", 1);
}

Obtendo IP na internet

public string GetIpRemoto(string url)
{
    //Cria uma requisição para a URL
    WebRequest rq = WebRequest.Create(url);

    //obtém o response a partir do request
    HttpWebResponse rp = (HttpWebResponse)rq.GetResponse();
    //obtém um stream contendo a resposta retornada pelo servidor
    Stream ds = rp.GetResponseStream();
    //Cria um StreamReader para leitura
    StreamReader rd = new StreamReader(ds);
    //Lê os dados
    string responseFromServer = rd.ReadToEnd();
    //fecha os objetos
    rd.Close();
    ds.Close();
    rp.Close();
    //procura por indexafor fixo no resultado 
    string URL = "IP";
    int i = responseFromServer.IndexOf(URL) + URL.Length + 2;
    //captura o IP descoberto
    URL = string.Empty;
    while (!(responseFromServer[i].ToString() == "<"))
    {
        URL += responseFromServer[i];
        i += 1;
    }      

    return URL.Trim();
}

Lendo arquivos texto

Solução por Marcos Guedes (Programação Brasil):
public string lerArquivo(string caminhoArquivo)
{
  int counter = 0;
  string line;
  string conteudo = "";

  System.IO.StreamReader file = new System.IO.StreamReader(caminhoArquivo);
  while ((line = file.ReadLine()) != null)
  {
      conteudo += line +  (char)13 + (char)10 ;
      counter++;
  }

  file.Close();
  return conteudo;
}

Solução por Rubem Rocha (Programação Brasil) :

public string LerArquivoTexto(string nomeArquivo)
{
  if (File.Exists(nomeArquivo))
      return File.ReadAllText(nomeArquivo);
  else
      return String.Empty;
}

ou

public static string[] LerArquivoTexto(string nomeArquivo)
{
  if (!File.Exists(nomeArquivo)) return (new string[] {});
  string buffer = File.ReadAllText(nomeArquivo, Encoding.Default);
  return (buffer.Split(new string[] { "\r\n" }, StringSplitOptions.None));
}

Retira acentos de textos

public string TirarAcentos(string texto)
{
   string textor = "";
   
   for (int i = 0; i < texto.Length; i++)
   {
       if (texto[i].ToString() == "ã") textor += "a";
       else if (texto[i].ToString() == "á") textor += "a";
       else if (texto[i].ToString() == "à") textor += "a";
       else if (texto[i].ToString() == "â") textor += "a";
       else if (texto[i].ToString() == "ä") textor += "a";
       else if (texto[i].ToString() == "é") textor += "e";
       else if (texto[i].ToString() == "è") textor += "e";
       else if (texto[i].ToString() == "ê") textor += "e";
       else if (texto[i].ToString() == "ë") textor += "e";
       else if (texto[i].ToString() == "í") textor += "i";
       else if (texto[i].ToString() == "ì") textor += "i";
       else if (texto[i].ToString() == "ï") textor += "i";
       else if (texto[i].ToString() == "õ") textor += "o";
       else if (texto[i].ToString() == "ó") textor += "o";
       else if (texto[i].ToString() == "ò") textor += "o";
       else if (texto[i].ToString() == "ö") textor += "o";
       else if (texto[i].ToString() == "ú") textor += "u";
       else if (texto[i].ToString() == "ù") textor += "u";
       else if (texto[i].ToString() == "ü") textor += "u";
       else if (texto[i].ToString() == "ç") textor += "c";
       else if (texto[i].ToString() == "Ã") textor += "A";
       else if (texto[i].ToString() == "Á") textor += "A";
       else if (texto[i].ToString() == "À") textor += "A";
       else if (texto[i].ToString() == "Â") textor += "A";
       else if (texto[i].ToString() == "Ä") textor += "A";
       else if (texto[i].ToString() == "É") textor += "E";
       else if (texto[i].ToString() == "È") textor += "E";
       else if (texto[i].ToString() == "Ê") textor += "E";
       else if (texto[i].ToString() == "Ë") textor += "E";
       else if (texto[i].ToString() == "Í") textor += "I";
       else if (texto[i].ToString() == "Ì") textor += "I";
       else if (texto[i].ToString() == "Ï") textor += "I";
       else if (texto[i].ToString() == "Õ") textor += "O";
       else if (texto[i].ToString() == "Ó") textor += "O";
       else if (texto[i].ToString() == "Ò") textor += "O";
       else if (texto[i].ToString() == "Ö") textor += "O";
       else if (texto[i].ToString() == "Ú") textor += "U";
       else if (texto[i].ToString() == "Ù") textor += "U";
       else if (texto[i].ToString() == "Ü") textor += "U";
       else if (texto[i].ToString() == "Ç") textor += "C";
       else textor += texto[i];
   }
   return textor;
}

Retornando o conteúdo de uma página web

public string GetContent(string url)
{
    string result = "Error communicating with server";
    System.Net.HttpWebRequest wreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
    wreq.Method = "GET";
    wreq.Timeout = 3000;
    System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wreq.GetResponse();

    if (wr.StatusCode == System.Net.HttpStatusCode.OK)
    {
        System.IO.Stream s = wr.GetResponseStream();
        System.Text.Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        System.IO.StreamReader readStream = new System.IO.StreamReader(s, enc);
        result = readStream.ReadToEnd();
    }
    return result;
}

Enviando Email

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.Net.Mail;

///
/// Summary description for EnviaEmail
///

namespace EnvioEmail
{
    public class EnviaEmail
    {
        #region valores padrões
        private string host = "smtp.gmail.com";
        private int porta = 587;
        private bool SSL = true;
        //
        private string nomeRemetente = "Nome do Remetente";
        private string emailRemetente = "email@remetente.com";
        private string nomeDestinatario = "Nome do Destinatário";
        private string emailDestinatario = "email@destinatario.com.br";
        //
        private bool isHTML = false;
        private string conteudo = "";
        private string assunto = "";
        //
        private string emailCredenciado = "teste@dominio.com";
        private string senhaCredenciada = "senha";
        #endregion

        #region métodos set para alteração dos valores padrões
        public void setHost(string host) { this.host = host; }
        public void setPorta(int porta) { this.porta = porta; }
        public void setSSL(bool SSL) { this.SSL = SSL; }
        public void setNomeRemetente(string nome) { this.nomeRemetente = nome; }
        public void setEmailRemetente(string email) { this.emailRemetente = email; }
        public void setNomeDestinatario(string nome) { this.nomeDestinatario = nome; }
        public void setEmailDestinatario(string email) { this.emailDestinatario = email; }
        public void setIsHTML(bool HTML) { this.isHTML = HTML; }
        public void setConteudo(string conteudo) { this.conteudo = conteudo; }
        public void setAssunto(string assunto) { this.assunto = assunto; }
        public void setEmailCrendeciado(string email) { this.emailCredenciado = email; }
        public void setSenhaCredenciada(string senha) { this.senhaCredenciada = senha; }
        #endregion

        public EnviaEmail()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public bool enviar()
        {
            // Enviar o email
            bool enviado = false;
            try
            {
                SmtpClient cliente = new SmtpClient(this.host, this.porta);
                cliente.EnableSsl = this.SSL; ;

                MailAddress remetente = new MailAddress(this.emailRemetente, this.nomeRemetente);
                MailAddress destinatario = new MailAddress(this.emailDestinatario, this.nomeDestinatario);
                MailMessage mensagem = new MailMessage(remetente, destinatario);
                mensagem.IsBodyHtml = this.isHTML; // define se será em formato html, ou não
                mensagem.Body = this.conteudo;
                mensagem.Subject = this.assunto;

                NetworkCredential credenciais = new NetworkCredential(this.emailCredenciado, this.senhaCredenciada, "");
                cliente.Credentials = credenciais;
                //
                cliente.Send(mensagem);
                enviado = true;
            }
            catch { }

            return enviado;
        }

        public bool enviar2()
        {
            // Use esta, se a função acima não funcionar
            bool enviado = false;
            try
            {
                SmtpClient cliente = new SmtpClient(this.host);
                NetworkCredential credenciais = new NetworkCredential(this.emailCredenciado, this.senhaCredenciada);
                //
                cliente.EnableSsl = this.SSL; ;
                cliente.UseDefaultCredentials = false;
                cliente.Credentials = credenciais;
                //
                MailAddress remetente = new MailAddress(this.emailRemetente);
                MailAddress destinatario = new MailAddress(this.emailDestinatario);
                MailMessage mensagem = new MailMessage(remetente, destinatario);
                //
                mensagem.IsBodyHtml = this.isHTML; // define se será em formato html, ou não
                mensagem.Body = this.conteudo;
                mensagem.BodyEncoding = System.Text.Encoding.UTF8;
                mensagem.Subject = this.assunto;
                mensagem.SubjectEncoding = System.Text.Encoding.UTF8;                
                //
                cliente.Send(mensagem);
                enviado = true;
            }
            catch { }

            return enviado;
        }
    }
}

FTP

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;

public class AcessoFTP
{
    #region Varáveis privadas
    private string addressFTP;
    private string userFTP;
    private string passwordFTP;
    private string filePathFTP;
    private string filePathLocal;
    private string msgStatus;

    private bool modoPassivo = true;

    private List listaFTP;
    private DataTable tbListaFTP;
    #endregion

    #region Variáveis públicas
    /// Endereço FTP
    public string ftpEndereco
    {
        get { return this.addressFTP; }
        set { this.addressFTP = value; }
    }
    /// Usuário FTP
    public string ftpUsuario
    {
        get { return this.userFTP; }
        set { this.userFTP = value; }
    }
    /// Senha FTP
    public string ftpSenha
    {
        get { return this.passwordFTP; }
        set { this.passwordFTP = value; }
    }
    ///
    /// Upload: Caminho do arquivo que será armazenado no servidor.
    /// Download: Caminho onde o arquivo será armazenado quando baixado do servidor FTP.
    ///
    public string ftpCaminhoArquivoLocal
    {
        get { return this.filePathLocal; }
        set { this.filePathLocal = value; }
    }
    ///
    /// Upload: Nome com o qual o arquivo que será armazenado no servidor.
    /// Download: Nome do arquivo que será baixado do servidor.
    ///
    public string ftpArquivoFTP
    {
        get { return this.filePathFTP; }
        set { this.filePathFTP = value; }
    }
    /// Status da última operação
    public string mensagemStatus
    {
        get { return this.msgStatus; }
    }

    ///
    /// True -> Modo Passivo; False -> Modo Ativo
    ///
    public bool ftpModoPassivo
    {
        set { this.modoPassivo = value; }
    }

    /// Armazena numa lista, o conteúdo do diretório filtrado.
    public List ftpDiretorioFTP
    {
        get { return this.listaFTP; }
    }
    /// Armazena num DataTable, o conteúdo do diretório filtrado.
    public DataTable ftpTbListaFTP
    {
        get { return this.tbListaFTP; }
    }
    #endregion

    #region Métodos que compõem a rotina
    /// Realiza upload de arquivos via FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpUpload()
    {
        bool sucesso;
        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/nomeArquivo.ext
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);
            //Cria uma solicitação FTP
            FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(caminho);

            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpRequest.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            ftpRequest.UsePassive = this.modoPassivo;
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = false;

            //Carrega o arquivo que será enviado para o servidor FTP
            FileStream arquivo = File.OpenRead(this.filePathLocal);
            byte[] buffer = new byte[arquivo.Length];

            arquivo.Read(buffer, 0, buffer.Length);
            arquivo.Close();

            //Upload file
            Stream reqStream = ftpRequest.GetRequestStream();
            reqStream.Write(buffer, 0, buffer.Length);
            reqStream.Close();

            this.msgStatus = "";
            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }
        return sucesso;
    }

    /// Realiza download de arquivos via FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpDownload()
    {
        bool sucesso;
        byte[] downloadedData = new byte[0];

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/arquivo.txt
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            //Now get the actual data
            request = (FtpWebRequest)FtpWebRequest.Create(caminho);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false; // Fechar a conexão quando concluído

            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            Stream reader = response.GetResponseStream();

            // Transfere para a memória
            // Nota: ajustar os fluxos aqui para fazer o download diretamente para o disco rígido
            MemoryStream memStream = new MemoryStream();
            byte[] buffer = new byte[1024]; //downloads in chuncks

            while (true)
            {
                // Tenta ler os dados
                int bytesRead = reader.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }
                else
                {
                    //Escreve o conteúdo baixado
                    memStream.Write(buffer, 0, bytesRead);
                }
            }

            // Converter o fluxo baixado para um array de bytes
            downloadedData = memStream.ToArray();

            reader.Close();
            memStream.Close();
            response.Close();

            // Escreve os bytes do arquivo
            FileStream newFile = new FileStream(this.filePathLocal, FileMode.Create);
            newFile.Write(downloadedData, 0, downloadedData.Length);
            newFile.Close();

            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        return sucesso;
    }

    /// Preenche uma lista e DataTable com os dados do diretório FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpListarDiretorios()
    {
        List files = new List();
        bool sucesso;
        string conteudo;

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/pastaDestino
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false;

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);

            this.tbListaFTP = new DataTable();
            this.tbListaFTP.Columns.Add("Descrição", typeof(string));
            this.tbListaFTP.Columns.Add("Caminho", typeof(string));

            while (!reader.EndOfStream)
            {
                conteudo = reader.ReadLine();

                this.tbListaFTP.Rows.Add(conteudo, conteudo);
                files.Add(conteudo);
            }

            reader.Close();
            responseStream.Close();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }

        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        this.listaFTP = files;

        return sucesso;
    }

    /// Preenche uma lista e DataTable com os dados do diretório FTP
    /// Extensão dos arquivos (*.ext)
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpListarDiretorios(string extensao)
    {
        List files = new List();
        bool sucesso;
        string conteudo;

        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/pastaDestino
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);

            //Cria uma solicitação FTP
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(caminho);

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            request.UsePassive = this.modoPassivo;
            request.UseBinary = true;
            request.KeepAlive = false;

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);

            this.tbListaFTP = new DataTable();
            this.tbListaFTP.Columns.Add("Descrição", typeof(string));
            this.tbListaFTP.Columns.Add("Caminho", typeof(string));

            while (!reader.EndOfStream)
            {
                conteudo = reader.ReadLine();
                // Se a extensão for a exigida.
                if (Path.GetExtension(conteudo).ToUpper() == extensao.ToUpper())
                {
                    this.tbListaFTP.Rows.Add(conteudo, conteudo);
                    files.Add(conteudo);
                }
            }

            reader.Close();
            responseStream.Close();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }

        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }

        this.listaFTP = files;

        return sucesso;
    }

    /// Deleta um arquivo de um diretório FTP
    /// Retorna true se a operação for bem sucedida, em caso contrário, retorna false
    public bool ftpDeletarArquivo()
    {
        bool sucesso;
        try
        {
            //O endereço deverá estar no seguinte formato: ftp://servidor.com/nomeArquivo.ext
            string caminho = this.addressFTP + "/" + Path.GetFileName(this.filePathFTP);
            //Cria uma solicitação FTP
            FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(caminho);

            ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
            ftpRequest.Credentials = new NetworkCredential(this.userFTP, this.passwordFTP);
            ftpRequest.UsePassive = this.modoPassivo;
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = false;

            // Deleta o arquivo
            FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
            response.Close();

            this.msgStatus = "";
            sucesso = true;
        }
        catch (Exception oErro)
        {
            this.msgStatus = oErro.Message;
            sucesso = false;
        }
        return sucesso;
    }
    #endregion
}

Lendo uma descrição de uma determinada linha num DataTable

string descricao;
int qualLinha = 0; // Primeira Linha
int qualColuna = 0; // Primeira Coluna

descricao = oDataTable.Rows[qualLinha].ItemArray.GetValue(qualColuna).ToString();

Abrindo a janela de salvar de arquivos

SaveFileDialog salvar = new SaveFileDialog();
//Tipo de arquivos que serão salvos
salvar.Filter = "Todos (*.*)|*.*|Texto (*.txt)|*.txt";
salvar.ShowDialog();

Abrindo a janela de seleção de arquivos

OpenFileDialog arquivo = new OpenFileDialog();
// Tipo de arquivos que serão filtrados
arquivo.Filter = "Todos (*.*)|*.*|Texto (*.txt)|*.txt"; 
arquivo.ShowDialog();

Obtendo Dados do Browser

ActiveXControls
Request.Browser.ActiveXControls

AOL
Request.Browser.AOL

BackgroundSounds
Request.Browser.BackgroundSounds

Beta
Request.Browser.Beta

Browser
Request.Browser.Browser

CDF
Request.Browser.CDF

ClrVersion
Request.Browser.ClrVersion

Cookies
Request.Browser.Cookies

Crawler
Request.Browser.Crawler

EcmaScriptVersion
Request.Browser.EcmaScriptVersion

Frames
Request.Browser.Frames

JavaApplets
Request.Browser.JavaApplets

JavaScript
Request.Browser.JavaScript

MajorVersion
Request.Browser.MajorVersion

MinorVersion
Request.Browser.MinorVersion

MSDomVersion
Request.Browser.MSDomVersion

Platform
Request.Browser.Platform

Tables
Request.Browser.Tables

Type
Request.Browser.Type

VBScript
Request.Browser.VBScript

Version
Request.Browser.Version

W3CDomVersion
Request.Browser.W3CDomVersion

Win16
Request.Browser.Win16

Win32
Request.Browser.Win32

terça-feira, 20 de julho de 2010

Acessando Tabela DBF

/*
   Autor: suhas hegde
   Fonte: http://www.foxite.com/archives/c-and-dbf-0000222619.htm
*/
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Drawing;

class vfpData
{
    static void Main()
    {
        string strConn = @"Provider=VFPOLEDB;Data source=
 C:\Program Files\Microsoft Visual FoxPro 9\Samples\Data;";

        OleDbConnection cn = new OleDbConnection(strConn);
        cn.Open();

        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = cn;
        cmd.CommandText = "delete from customer";
        cmd.ExecuteNonQuery();

        OleDbCommand cmd1 = new OleDbCommand();
        cmd1.Connection = cn;
        cmd1.CommandText = "Set Deleted off";
        cmd1.ExecuteNonQuery();
        cmd1.CommandType = CommandType.Text;
        cmd1.CommandText = "select deleted() as isdeleted ,* from customer";

        OleDbCommand cmd2 = new OleDbCommand();
        cmd2.CommandType = CommandType.TableDirect;
        cmd2.Connection = cn;
        cmd2.CommandText = "customer";

        DataTable tbl1 = new DataTable();
        DataTable tbl2 = new DataTable();

        OleDbDataReader rdr1 = cmd1.ExecuteReader();
        tbl1.Load(rdr1);
        OleDbDataReader rdr2 = cmd2.ExecuteReader();
        tbl2.Load(rdr2);
        cn.Close();

        Form f = new ShowDataForm(tbl1, "Select command");
        f.ShowDialog();
        f = new ShowDataForm(tbl2, "Table direct");
        f.ShowDialog();
    }
}

public class ShowDataForm : Form
{
    public ShowDataForm(DataTable tbl, string caption)
    {
        this.dgv = new System.Windows.Forms.DataGridView();
        this.dgv.Location = new System.Drawing.Point(0, 0);
        this.dgv.Dock = DockStyle.Fill;
        this.dgv.DataSource = tbl;
        this.Text = caption + " Records fetched " + tbl.Rows.Count.ToString();
        this.Controls.Add(this.dgv);
        this.ClientSize = new System.Drawing.Size(1024, 768);
    }
    private System.Windows.Forms.DataGridView dgv;
}

Criptografia MD5

MD5:
///
/// Fonte: Help do Microsoft Visual Studio 2008
///
using System;
using System.Security.Cryptography;
using System.Text;

class Example
{
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i <>
{
sBuilder.Append(data[i].ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}

// Verify a hash against a string.
static bool verifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = getMd5Hash(input);

// Create a StringComparer an comare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;

if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}


static void Main()
{
string source = "Hello World!";

string hash = getMd5Hash(source);

Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");

Console.WriteLine("Verifying the hash...");

if (verifyMd5Hash(source, hash))
{
Console.WriteLine("The hashes are the same.");
}
else
{
Console.WriteLine("The hashes are not same.");
}

}
}
///
/// This code example produces the following output:
///
/// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
/// Verifying the hash...
/// The hashes are the same.
///


MD5CryptoServiceProvider:
///
/// Fonte: Help do Microsoft Visual Studio 2008
///

using System;
using System.Security.Cryptography;
using System.Text;

class Example
{
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i <>
{
sBuilder.Append(data[i].ToString("x2"));
}

// Return the hexadecimal string.
return sBuilder.ToString();
}

// Verify a hash against a string.
static bool verifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = getMd5Hash(input);

// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;

if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}


static void Main()
{
string source = "Hello World!";

string hash = getMd5Hash(source);

Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");

Console.WriteLine("Verifying the hash...");

if (verifyMd5Hash(source, hash))
{
Console.WriteLine("The hashes are the same.");
}
else
{
Console.WriteLine("The hashes are not same.");
}

}
}
///
/// This code example produces the following output:
///
/// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
/// Verifying the hash...
/// The hashes are the same.
///


Função Simples: 
public string MD5(string Valor)
{
    return FormsAuthentication.HashPasswordForStoringInConfigFile(Valor, "MD5");            
}

Serviços do Windows

/*
* Fonte: http://goo.gl/W3Ku
*/

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Servicos
{
public class InstalarServico
{
private string caminhoServico = "";
private string nomeServico = "";
private string nomeExibicao = "";
private string mensagemStatus = ""; // Armazena o status da operação
private TextBox txtStatus = null;


#region Importando DLL's
[DllImport("advapi32.dll")]
private static extern IntPtr OpenSCManager(string lpMachineName, string lpSCDB, int scParameter);

[DllImport("Advapi32.dll")]
private static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName,
int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName,
string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);

[DllImport("advapi32.dll")]
private static extern void CloseServiceHandle(IntPtr SCHANDLE);

[DllImport("advapi32.dll")]
private static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string lpServiceArgVectors);

[DllImport("advapi32.dll", SetLastError = true)]
private static extern IntPtr OpenService(IntPtr SCHANDLE, string lpSvcName, int dwNumServiceArgs);

[DllImport("advapi32.dll")]
private static extern int DeleteService(IntPtr SVHANDLE);

[DllImport("kernel32.dll")]
private static extern int GetLastError();
#endregion

public void setCaminhoServico(string caminho)
{
/**
* Altera o caminho do serviço
*/
this.caminhoServico = caminho;
}
public void setNomeServico(string nome)
{
/**
* Altera o nome do serviço
*/
this.nomeServico = nome;
}

public void setNomeExibicao(string nome)
{
/**
* Altera o nome para exibição
*/
this.nomeExibicao = nome;
}

public void setTxtStatus(TextBox txtStatus)
{
this.txtStatus = txtStatus;
}

public string getMensagemStatus()
{
/**
* Retorna a mensagem de status da operação.
*/
return this.mensagemStatus;
}

public bool instalarServico()
{
/**
* Instala o serviço
*/
#region Verifica se as variáveis necessárias estão preenchidas
if (
(this.caminhoServico.Length == 0) ||
(this.nomeServico.Length == 0) ||
(this.nomeExibicao.Length == 0)
)
{
this.mensagemStatus = "Campos não preenchidos";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

this.mensagemStatus = "Campos não preenchidos";
return false;
}
#endregion

#region Declaração de constantes
int SC_MANAGER_CREATE_SERVICE = 0x0002;
int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
//int SERVICE_DEMAND_START = 0x00000003;
int SERVICE_ERROR_NORMAL = 0x00000001;
int STANDARD_RIGHTS_REQUIRED = 0xF0000;
int SERVICE_QUERY_CONFIG = 0x0001;
int SERVICE_CHANGE_CONFIG = 0x0002;
int SERVICE_QUERY_STATUS = 0x0004;
int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
int SERVICE_START = 0x0010;
int SERVICE_STOP = 0x0020;
int SERVICE_PAUSE_CONTINUE = 0x0040;
int SERVICE_INTERROGATE = 0x0080;
int SERVICE_USER_DEFINED_CONTROL = 0x0100;
int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
SERVICE_QUERY_CONFIG |
SERVICE_CHANGE_CONFIG |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_CONTINUE |
SERVICE_INTERROGATE |
SERVICE_USER_DEFINED_CONTROL);
int SERVICE_AUTO_START = 0x00000002;
#endregion Constants declaration.

try
{
IntPtr sc_handle = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (sc_handle.ToInt32() != 0)
{
IntPtr sv_handle = CreateService(sc_handle, this.nomeServico, this.nomeExibicao,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
this.caminhoServico, null, 0, null, null, null);
if (sv_handle.ToInt32() == 0)
{
CloseServiceHandle(sc_handle);
this.mensagemStatus = "Não foi possível instalar o serviço";
if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
else
{
// Inicia o serviço
int i = StartService(sv_handle, 0, null);
// Se o valor de i for zero, então houve um erro ao iniciar o serviço.
// Obs: O erro pode ocorrer se o serviço já esteja funcionando ou algum outro problema.
if (i == 0)
{
this.mensagemStatus = "Não foi possível iniciar o serviço";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
this.mensagemStatus = "Serviço iniciado com sucesso";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

CloseServiceHandle(sc_handle);
return true;
}
}
else
{
this.mensagemStatus = "SCM não foi aberto com sucesso";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
}
catch (Exception oErro)
{
this.mensagemStatus = oErro.Message;

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
}

public bool desinstalarServico()
{
/**
* Desinstala o serviço
*/
#region Verifica se as variáveis necessárias estão preenchidas
if (this.nomeServico.Length == 0)
{
this.mensagemStatus = "Campos não preenchidos";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
#endregion

int GENERIC_WRITE = 0x40000000;
IntPtr sc_hndl = OpenSCManager(null, null, GENERIC_WRITE);
if (sc_hndl.ToInt32() != 0)
{
int DELETE = 0x10000;
IntPtr svc_hndl = OpenService(sc_hndl, this.nomeServico, DELETE);
//Console.WriteLine(svc_hndl.ToInt32());
if (svc_hndl.ToInt32() != 0)
{
int i = DeleteService(svc_hndl);
if (i != 0)
{
CloseServiceHandle(sc_hndl);

this.mensagemStatus = "Serviço deletado com sucesso";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return true;
}
else
{
CloseServiceHandle(sc_hndl);

this.mensagemStatus = "Não foi possível excluir o serviço especificado";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
}
else
{
this.mensagemStatus = "Não foi possível excluir o serviço especificado";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
}
else
{
this.mensagemStatus = "Não foi possível excluir o serviço especificado";

if (this.txtStatus != null)
this.txtStatus.Text += "\r\n" + this.mensagemStatus;

return false;
}
}

/*
public static void Main()
{
string caminhoServico = @"C:\servico\servico.exe";
string nomeServico = "Nome do Serviço";
string nomeExibicao = "Nome para exibição";

InstalarServico obj = new InstalarServico();
obj.setCaminhoServico(caminhoServico);
obj.setNomeServico(nomeServico);
obj.setNomeExibicao(nomeExibicao);
obj.instalarServico();
}
*/
}
}

Arquivo Texto (Classe)

/*
* Autor: Marcos Guedes
* Fonte: http://forum.programacaobrasil.com/-t294.htm
*/

using System;
using System.IO;
using System.Windows.Forms;

namespace Arquivos
{
public class ArquivosTXT
{
private int quantasLinhas = 0;
private bool formatoTexto = true;
private string conteudoArquivo = "";
private string mensagemErro = "";
private string caminho = "";

public bool lerArquivo()
{
/**
* Lê um arquivo texto,
* retornando valores possíveis para copiar para outro arquivo texto,
* ou para web.
*/
if (!this.arquivoExiste())
{
this.mensagemErro = "Arquivo não existe!";
return false;
}

// Verifica se a extensão é .txt
if (!this.getExtensaoValida(this.caminho))
{
this.mensagemErro = "Formato inválido!";
return false;
}

bool sucesso;

try
{
StreamReader sr = new StreamReader(this.caminho);
string linha = sr.ReadLine();
int quantos = 0;
string conteudo = "";

// Preenche a variável com os dados do arquivo.
while (linha != null)
{
conteudo += linha.ToString();
linha = sr.ReadLine();

quantos += 1;
if (this.formatoTexto)
conteudo += "\r\n";
else
conteudo += "
";
}

// Fecha o arquivo
sr.Close();

this.quantasLinhas = quantos;
this.conteudoArquivo = conteudo;

this.mensagemErro = "";
sucesso = true;
}
catch(Exception oErro)
{
this.mensagemErro = oErro.Message;
sucesso = false;
}
return sucesso;
}

public bool escreverArquivo()
{
/**
* Escreve um novo arquivo texto.
* Utilize o método "setConteudoArquivo()" para definir o
* conteúdo que será escrito no arquivo.
* Obs: Se o arquivo já existir, será sobrescrito.
*/

// Verifica se a extensão é .txt
if (Path.GetExtension(this.caminho).ToUpper() != ".TXT")
{
this.mensagemErro = "Formato inválido!";
return false;
}

bool sucesso;

try
{
StreamWriter sw = new StreamWriter(this.caminho);
sw.WriteLine(this.conteudoArquivo);
// Fecha o arquivo
sw.Close();

this.mensagemErro = "";
sucesso = true;
}
catch (Exception oErro)
{
this.mensagemErro = oErro.Message;
sucesso = false;
}

return sucesso;
}
#region Métodos SET's
public void setFormatoTexto(bool formatoTexto)
{
/**
* Se for "true" a quebra de linha será "\n".
* Se for "false" a quebra de linha será "
"
*/
this.formatoTexto = formatoTexto;
}

public void setCaminhoArquivo(string caminho)
{
/**
* Altera/Define o caminho do arquivo o qual será trabalhado.
*/
this.caminho = caminho;
}

public void setConteudoArquivo(string conteudo)
{
/**
* Define o conteúdo do arquivo que será escrito.
* Obs: Este método deverá ser usado para definir o conteúdo do arquivo
* antes de se usar o método "escreverArquivoNovo()" e/ou "escreveArquivoVelho()".
*/
this.conteudoArquivo = conteudo;
}
#endregion

#region Métodos Get's
public int getQuantasLinhas()
{
/**
* Retorna a quantidade de linhas
* existente no arquivo selecionado.
*/
return this.quantasLinhas;
}

public string getConteudoArquivo()
{
/**
* Retorna o conteúdo do arquivo lido.
* Obs: Este método é usado para se obter o conteúdo do arquivo
* após ter usado o método "lerArquivo()".
*/
return conteudoArquivo;
}

public string getMensagemErro()
{
/**
* Rtorna a última mensagem de erro armazenada.
* No caso de operações bem sucessididas,
* o retorno será uma string vazia.
*/
return this.mensagemErro;
}
#endregion

public bool getExtensaoValida(string caminho)
{
// Verifica se a extensão é .txt
return (Path.GetExtension(caminho).ToUpper() == ".TXT");
}
private bool arquivoExiste()
{
/**
* Verifica se um arquivo existe.
*/
return File.Exists(this.caminho);
}
}
}

Acesso a Banco de Dados

/*
* Autor: Marcos Guedes
* Fonte: http://forum.programacaobrasil.com/-t291.htm
*/

using System;
using System.Data;

public abstract class BancoDados
{
protected string strConexao = ""; // String de conexão
protected string mensagemErro = ""; // Última mensagem de erro armazenada.
protected bool conectado = false; // Status de conexão com o banco de dados
protected int quantos = 0; // Quantidade de registros filtrados no último SELECT

protected DataTable objDt;

public void setStrConexao(string strConexao)
{
/**
* Altera o valor da string de conexão
*/
this.strConexao = strConexao;
}

public bool getConectado()
{
/*
* Retorna o status de conexão com o banco de dados
*/
return this.conectado;
}

public string getMensagemErro()
{
/**
* Retorna a última mensagem de erro.
* No caso de uma operação bem sucessidade,
* o retorno é uma string vazia.
*/
return this.mensagemErro;
}

public DataTable getObjDt()
{
/**
* Retorna um DataTable contendo os registros do último select
*/
return this.objDt;
}

public int getQuantos()
{
/**
* Retorna a quantidade de do último select
*/
return this.quantos;
}
}

namespace AcessoODBC
{
using System.Data.Odbc;

public class BancoODBC : BancoDados
{
private OdbcConnection objConexao; // Objeto de conexão com o banco através do driver odbc
private OdbcCommand objComando;

public BancoODBC(){ }

public BancoODBC(string strConexao)
{
/* Sobrecarga de construtor, permitindo a opção de passar a
* string de conexão no momento em que o objeto for instanciado*/
this.strConexao = strConexao;
}

public void conectar()
{
/**
* Tenta realizar uma conexão com um Banco de Dados
*/
bool conectado;
try
{
this.objConexao = new OdbcConnection(this.strConexao);
this.objConexao.Open(); // Abre a conexão com o banco de dados
this.mensagemErro = "";

conectado = true;
}
catch(Exception oErro)
{
this.mensagemErro = oErro.Message;
conectado = false;
}
this.conectado = conectado;
}

public void desconectar()
{
/**
* Desconecta-se do banco de dados
*/
this.objConexao.Close();
this.conectado = false;
}

public bool executar(string comando)
{
/**
* Executa comandos SQL.
*/
bool sucesso;
try
{
this.objComando = new OdbcCommand(comando, this.objConexao);
this.objDt = new DataTable();
OdbcDataReader dr = this.objComando.ExecuteReader();
objDt.Load(dr);

this.quantos = dr.RecordsAffected; // Filtra a quantidade de registros afetados
this.mensagemErro = "";
sucesso = true;
}
catch (Exception oErro)
{
this.quantos = -1;
this.mensagemErro = oErro.Message;
this.objDt = null;
sucesso = false;
}
return sucesso;
}
}
}

namespace AcessoBancoOLEDB
{
using System.Data.OleDb;

public class BancoOLEDB : BancoDados
{
private OleDbConnection objConexao; // Objeto de conexão com o banco através do driver odbc
private OleDbCommand objComando;
public void conectar()
{
/**
* Tenta realizar uma conexão com um Banco de Dados
*/
bool conectado;
try
{
this.objConexao = new OleDbConnection(this.strConexao);
this.objConexao.Open(); // Abre a conexão com um banco de dados
this.mensagemErro = "";

conectado = true;
}
catch (Exception oErro)
{
this.mensagemErro = oErro.Message;
conectado = false;
}
this.conectado = conectado;
}

public void desconectar()
{
/**
* Desconecta-se do banco de dados
*/
this.objConexao.Close();
this.conectado = false;
}

public bool executar(string comando)
{
/**
* Executa comandos SQL.
*/
bool sucesso;

try
{
this.objComando = new OleDbCommand(comando, this.objConexao);
this.objDt = new DataTable();

OleDbDataReader dr = this.objComando.ExecuteReader();
objDt.Load(dr);

this.quantos = dr.RecordsAffected; // Filtra a quantidade de registros afetados
this.mensagemErro = "";
sucesso = true;
}
catch (Exception oErro)
{
this.quantos = -1;
this.mensagemErro = oErro.Message;
this.objDt = null;
sucesso = false;
}
return sucesso;
}
}
}

namespace AcessoBancoSQL
{
using System.Data.SqlClient;

public class BancoSQL : BancoDados
{
private SqlConnection objConexao; // Objeto de conexão com o banco através do driver odbc
private SqlCommand objComando;

public void conectar()
{
/**
* Tenta realizar uma conexão com um Banco de Dados
*/
bool conectado;
try
{
this.objConexao = new SqlConnection(this.strConexao);
this.objConexao.Open(); // Abre a conexão com um banco de dados
this.mensagemErro = "";

conectado = true;
}
catch (Exception oErro)
{
this.mensagemErro = oErro.Message;
conectado = false;
}
this.conectado = conectado;
}

public void desconectar()
{
/**
* Desconecta-se do banco de dados
*/
this.objConexao.Close();
this.conectado = false;
}

public bool executar(string comando)
{
/**
* Executa comandos SQL.
*/
bool sucesso;

try
{
this.objComando = new SqlCommand(comando, this.objConexao);
this.objDt = new DataTable();

SqlDataReader dr = this.objComando.ExecuteReader();
objDt.Load(dr);

this.quantos = dr.RecordsAffected; // Filtra a quantidade de registros afetados
this.mensagemErro = "";
sucesso = true;
}
catch (Exception oErro)
{
this.quantos = -1;
this.mensagemErro = oErro.Message;
this.objDt = null;
sucesso = false;
}
return sucesso;
}
}
}