Desenvolvedores.Net - TechBlog

Tag Archives: CSharp

Recuperando métodos e propriedades (C#)

0
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (2 votos, média: 5,00 de 5)
Loading ... Loading ...
18 de novembro de 2011

 A dúvida.

Como recuperar os nomes de métodos e propriedades de um objeto em C#?

Simples. Usando System.Reflection.

Para conhecer mais o namespace http://msdn.microsoft.com/pt-br/library/system.reflection.aspx.

Exemplo para recuperar métodos e propriedades.

Crie uma nova aplicação console e utilize o código abaixo.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication
{
    class MinhaClasse
    {
        #region Propriedades
        public string Nome { get; set; }
        public string Sobrenome { get; set; }
        #endregion

        #region Fields
        public int Idade;
        public int Ano;
        #endregion

        #region Métodos
        public void Salvar()
        {
            Console.WriteLine("Nome      : {0}\nSobrenome : {1}\nRegistro salvo", Nome, Sobrenome);
        }

        public int Somar(int v1, int v2)
        {
            return v1 + v2;
        }
        #endregion

        #region Privados
        private void Privado()
        {
            Console.WriteLine("Eu sou um método privado");
        }
        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            #region Criando objeto
            MinhaClasse mc = new MinhaClasse();
            mc.Nome = "Desenvolvedores";
            mc.Sobrenome = "Net";
            mc.Idade = 8;
            mc.Ano = 2004;
            #endregion

            #region Recuperando as propriedades
            Console.WriteLine("Recuperando a propriedade nome");
            //recuperando as propriedades quando se sabe o nome
            PropertyInfo pi = mc.GetType().GetProperty("Nome");
            Console.WriteLine(pi.GetValue(mc, null).ToString());

            Console.WriteLine("");
            Console.WriteLine("Percorrendo as propriedades");
            //percorrendo as propriedades
            PropertyInfo[] pis = mc.GetType().GetProperties();

            foreach (PropertyInfo p in pis)
            {
                Console.WriteLine("Propriedade:{0} - Valor: {1}", p.Name, p.GetValue(mc, null));
            }
            #endregion

            #region Recuperando os campos
            Console.WriteLine("");
            Console.WriteLine("Recuperando o campo Idade");
            //recuperando o canmpo quando se sabe o nome
            FieldInfo fi = mc.GetType().GetField("Idade");
            Console.WriteLine(fi.GetValue(mc).ToString());

            Console.WriteLine("");
            Console.WriteLine("Percorrendo os campos");
            //percorrendo as propriedades
            FieldInfo[] fis = mc.GetType().GetFields();

            foreach (FieldInfo p in fis)
            {
                Console.WriteLine("Campo:{0} - Valor: {1}", p.Name, p.GetValue(mc));
            }
            #endregion

            #region Recuperando métodos
            Console.WriteLine("");
            Console.WriteLine("Recuperando o método salvar");
            //quando se sabe o nome
            MethodInfo mi = mc.GetType().GetMethod("Salvar");

            Console.WriteLine("");
            Console.WriteLine("Executando método salvar");
            mi.Invoke(mc, null);

            Console.WriteLine("");
            Console.WriteLine("Percorrendo métodos");

            //nao sei os nomes
            MethodInfo[] mis = mc.GetType().GetMethods();

            foreach (MethodInfo m in mis)
            {
                Console.WriteLine("Método:{0} - Parâmetros: {1} - Retorno: {2}", m.Name, m.GetParameters().Count(), m.ReturnType);
            }

            //executando métodos com parâmetros
            Console.WriteLine("");
            Console.WriteLine("Executando métodos com parâmetros e recebendo um retorno");

            mi = mc.GetType().GetMethod("Somar");
            Console.WriteLine("Resultado do método somar: {0}", mi.Invoke(mc, new object[] { 26, 29 }));

            Console.WriteLine("");
            Console.WriteLine("Recuperando um método privado e executando");

            mi = mc.GetType().GetMethod("Privado", BindingFlags.Instance |
                                                       BindingFlags.NonPublic);
            mi.Invoke(mc, null);

            #endregion
            Console.ReadKey();
        }
    }
}

É isso ai pessoal :)
Até o próximo
♦ Marcelo

About Marcelo

Nascido em Juruaia/MG em uma fazenda de criação de búfalos. Está perdido em São Paulo trabalhando com desenvolvimento de aplicações desde os 17 anos. Atualmente é arquiteto de software, é um cara meia boca que fica entre a equipe de desenvolvimento e o gerente de projetos, no meio da ponte. Para saber mais ... http://desenvolvedores.net/marcelo []'s

CSharp com SQLite

1
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (1 votos, média: 5,00 de 5)
Loading ... Loading ...
2 de maio de 2011

Olá Pessoal.

Neste artigo eu vou falar sobre um banco de dados embarcado que eu acho muito prático de usar o nome dele é SQLite.

O que é o SQLite?

SQLite é uma biblioteca C que implementa um banco de dados SQL embutido. Programas que usam a biblioteca SQLite podem ter acesso ao banco de dados SQL sem executar um processo RDBMS separado.
SQLite não é uma biblioteca de cliente usada para conectar com um grande servidor de banco de dados. SQLite é o servidor.

A biblioteca SQLite lê e escreve diretamente para e do arquivo do banco de dados no disco.
O uso do SQLite é recomendado onde a simplicidade da administração, implementação e manutenção são mais importantes que incontáveis recursos que SGBDs mais voltados para aplicações complexas possivelmente implementam.

Entretanto situações onde a simplicidade é a melhor escolha são muito mais freqüentes do que pode-se imaginar.

Exemplos de uso do SQLite são:

  • Não restrito à sites (com menos de cem mil requisições por dia);
  • Dispositivos e sistemas embarcados;
  • Aplicações desktop;
  • Ferramentas estatísticas e de análise;
  • Aprendizado de banco de dados;
  • Implementação de novas extensões à SQL.

Não se recomenda o uso do SQLite para:

  • Sites com muitos acessos;
  • Grande quantidades de dados (talvez maior que algumas dúzias de gigabytes);
  • Sistemas com grande concorrência;
  • Aplicações cliente/servidor.

Algumas características do SQLite:

  • Software livre/domínio público e Multiplataforma;
  • Mecanismo de armazenamento seguro com transações ACID;
  • Não necessita de instalação, configuração ou administração;
  • Implementa a maioria do SQL92;
  • O Banco de Dados é guardado em um único arquivo;
  • Suporta bases de dados acima de 2 terabytes;
  • Sem dependências externas.

No artigo irei criar a base de dados e as tabelas “Programaticamente” (não achei uma palavra melhor para descrever isso.) mas se você quiser usar uma ferramenta recomendo o uso do SQLite Studio, é gratuita (http://sqlitestudio.one.pl/index.rvt)

Vou assumir que você já sabe o que é uma base de dados embarcada (embedded, embutido) e que tenha conhecimentos em C#.

Primeiramente temos que preparar o nosso ambiente. Para isso iremos fazer o download do provider para .NET. Descompacte o arquivo em uma pasta, iremos usar este caminho mais tarde.

Feito o download iremos criar um novo projeto do tipo windows form e chamar de SQLiteEmbedded.

Renomearemos o form1 para frmMain.

Vamos colocar seis botões em nosso form, segue os nomes e o texto para cada botão

Nome Botão Texto
btnCriarBase Criar Base
btnCriarTabelas Criar Tabelas
btnInsert Insert
btnUpdate Update
btnSelect Select
btnDelete Delete

Com estes botões iremos implementar as operações básicas, desde a criação da base de dados, criação das tabelas e a manipulação dos dados.

Iremos colocar agora um dataGridView e alguns campos de texto e data para montar o nosso form, não se preocupe com o form, ao final do artigo terá um link para download do projeto. Mas se quiser fazer o form.

A tela do meu form ficou assim:

 

Se quiser poupar trabalho, segue o código para colar no designer (frmMain.Designer.cs) troque o código que tem lá, por este.

namespace SQLiteEmbedded
{
    partial class frmMain
    {
        ///
        /// Required designer variable.
        ///
        private System.ComponentModel.IContainer components = null;

        ///
        /// Clean up any resources being used.
        ///
        /// <param name="disposing" />true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        ///
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///
        private void InitializeComponent()
        {
            this.btnCriarBase = new System.Windows.Forms.Button();
            this.btnCriarTabelas = new System.Windows.Forms.Button();
            this.btnInsert = new System.Windows.Forms.Button();
            this.Update = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.dataGridView = new System.Windows.Forms.DataGridView();
            this.label1 = new System.Windows.Forms.Label();
            this.txtID = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.txtNome = new System.Windows.Forms.TextBox();
            this.txtTelefone = new System.Windows.Forms.TextBox();
            this.dtDataNascimento = new System.Windows.Forms.DateTimePicker();
            this.btnSelect = new System.Windows.Forms.Button();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
            this.SuspendLayout();
            //
            // btnCriarBase
            //
            this.btnCriarBase.Location = new System.Drawing.Point(12, 12);
            this.btnCriarBase.Name = "btnCriarBase";
            this.btnCriarBase.Size = new System.Drawing.Size(103, 23);
            this.btnCriarBase.TabIndex = 0;
            this.btnCriarBase.Text = "Criar Base";
            this.btnCriarBase.UseVisualStyleBackColor = true;
            this.btnCriarBase.Click += new System.EventHandler(this.btnCriarBase_Click);
            //
            // btnCriarTabelas
            //
            this.btnCriarTabelas.Location = new System.Drawing.Point(121, 12);
            this.btnCriarTabelas.Name = "btnCriarTabelas";
            this.btnCriarTabelas.Size = new System.Drawing.Size(103, 23);
            this.btnCriarTabelas.TabIndex = 1;
            this.btnCriarTabelas.Text = "Criar Tabelas";
            this.btnCriarTabelas.UseVisualStyleBackColor = true;
            this.btnCriarTabelas.Click += new System.EventHandler(this.btnCriarTabelas_Click);
            //
            // btnInsert
            //
            this.btnInsert.Location = new System.Drawing.Point(348, 51);
            this.btnInsert.Name = "btnInsert";
            this.btnInsert.Size = new System.Drawing.Size(75, 23);
            this.btnInsert.TabIndex = 2;
            this.btnInsert.Text = "Insert";
            this.btnInsert.UseVisualStyleBackColor = true;
            this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click);
            //
            // Update
            //
            this.Update.Location = new System.Drawing.Point(348, 81);
            this.Update.Name = "Update";
            this.Update.Size = new System.Drawing.Size(75, 23);
            this.Update.TabIndex = 3;
            this.Update.Text = "Update";
            this.Update.UseVisualStyleBackColor = true;
            this.Update.Click += new System.EventHandler(this.Update_Click);
            //
            // btnDelete
            //
            this.btnDelete.Location = new System.Drawing.Point(348, 111);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(75, 23);
            this.btnDelete.TabIndex = 4;
            this.btnDelete.Text = "Delete";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            //
            // dataGridView
            //
            this.dataGridView.AllowUserToAddRows = false;
            this.dataGridView.AllowUserToDeleteRows = false;
            this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView.Location = new System.Drawing.Point(12, 182);
            this.dataGridView.Name = "dataGridView";
            this.dataGridView.ReadOnly = true;
            this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataGridView.Size = new System.Drawing.Size(537, 267);
            this.dataGridView.TabIndex = 6;
            this.dataGridView.SelectionChanged += new System.EventHandler(this.dataGridView_SelectionChanged);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 51);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(21, 13);
            this.label1.TabIndex = 7;
            this.label1.Text = "ID:";
            //
            // txtID
            //
            this.txtID.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtID.Location = new System.Drawing.Point(96, 51);
            this.txtID.Name = "txtID";
            this.txtID.ReadOnly = true;
            this.txtID.Size = new System.Drawing.Size(100, 20);
            this.txtID.TabIndex = 8;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 81);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(38, 13);
            this.label2.TabIndex = 9;
            this.label2.Text = "Nome:";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 111);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(52, 13);
            this.label3.TabIndex = 10;
            this.label3.Text = "Telefone:";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(12, 141);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(70, 13);
            this.label4.TabIndex = 11;
            this.label4.Text = "Data Nascto:";
            //
            // txtNome
            //
            this.txtNome.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtNome.Location = new System.Drawing.Point(96, 81);
            this.txtNome.Name = "txtNome";
            this.txtNome.Size = new System.Drawing.Size(209, 20);
            this.txtNome.TabIndex = 12;
            //
            // txtTelefone
            //
            this.txtTelefone.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtTelefone.Location = new System.Drawing.Point(96, 111);
            this.txtTelefone.Name = "txtTelefone";
            this.txtTelefone.Size = new System.Drawing.Size(94, 20);
            this.txtTelefone.TabIndex = 13;
            //
            // dtDataNascimento
            //
            this.dtDataNascimento.CustomFormat = "dd/MM/yyyy";
            this.dtDataNascimento.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.dtDataNascimento.Location = new System.Drawing.Point(96, 141);
            this.dtDataNascimento.Name = "dtDataNascimento";
            this.dtDataNascimento.Size = new System.Drawing.Size(94, 20);
            this.dtDataNascimento.TabIndex = 14;
            //
            // btnSelect
            //
            this.btnSelect.Location = new System.Drawing.Point(348, 140);
            this.btnSelect.Name = "btnSelect";
            this.btnSelect.Size = new System.Drawing.Size(75, 23);
            this.btnSelect.TabIndex = 15;
            this.btnSelect.Text = "Select";
            this.btnSelect.UseVisualStyleBackColor = true;
            this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(12, 35);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(538, 13);
            this.label5.TabIndex = 16;
            this.label5.Text = "---------------------------------------------------------------------------------" +
                "--------------------------------------------------------------------------------" +
                "----------------";
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(12, 166);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(538, 13);
            this.label6.TabIndex = 17;
            this.label6.Text = "---------------------------------------------------------------------------------" +
                "--------------------------------------------------------------------------------" +
                "----------------";
            //
            // frmMain
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(561, 461);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.btnSelect);
            this.Controls.Add(this.dtDataNascimento);
            this.Controls.Add(this.txtTelefone);
            this.Controls.Add(this.txtNome);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.txtID);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.dataGridView);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.Update);
            this.Controls.Add(this.btnInsert);
            this.Controls.Add(this.btnCriarTabelas);
            this.Controls.Add(this.btnCriarBase);
            this.Name = "frmMain";
            this.Text = "SQLite Embededd";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnCriarBase;
        private System.Windows.Forms.Button btnCriarTabelas;
        private System.Windows.Forms.Button btnInsert;
        private System.Windows.Forms.Button Update;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.DataGridView dataGridView;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtID;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox txtNome;
        private System.Windows.Forms.TextBox txtTelefone;
        private System.Windows.Forms.DateTimePicker dtDataNascimento;
        private System.Windows.Forms.Button btnSelect;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
    }
}

Ok! Feito isso iremos agora programar o código para cada um de nossos botões.

Para isso faça a referência à DLL System.Data.SQLite.dll. Procure pelo arquivo que você descompactou, aquele que você fez o download.

Primeiro vamos criar a base de dados.

Para criar o arquivo de base de dados usamos o método estático System.Data.SQLite.SQLiteConnection.CreateFile.

Clique 2x no botão “Criar Base”.  Segue o código do evento clique.

 private void btnCriarBase_Click(object sender, EventArgs e)
        {
            try
            {
                string dbFile = "sqlLite.db"; //a extensão pode ser a que você quiser
                if (System.IO.File.Exists(dbFile)) System.IO.File.Delete(dbFile);
                System.Data.SQLite.SQLiteConnection.CreateFile(dbFile);
                MessageBox.Show(this, "Base de dados criada com sucesso.", "Aviso!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Ocorreu um erro ao criar a base de dados.\n" +
                    ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

OK! Agora que criamos a base de dados precisamos criar as tabelas. O SQLite aceita os comando de criação de tabelas, CREATE TABLE, ALTER TABLE, DROP TABLE. Então vamos criar a nossa tabela.

Antes de criar as nossas tabelas precisamos conhecer as strings de conexões que podemos ter para o SQLite.

Se você não definiu nenhuma senha para sua base de dados, esta string é o suficiente.

Data Source=caminho completo do arquivo;Version=3;

Caso tenha definido uma senha, use esta string

Data Source=caminho completo do arquivo;Version=3;Password=senha;

Clique 2x no botão “Criar Tabelas”. Segue o código do evento clique.

 private void btnCriarTabelas_Click(object sender, EventArgs e)
        {
            try
            {
                SQLiteConnection conn = OpenConnection();

                //criamos um objeto Command;
                SQLiteCommand command = conn.CreateCommand();

                //definimos o script de criação de tabelas
                string createTable = @"CREATE TABLE Pessoa (
                        ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                        Nome VARCHAR(100) NOT NULL,
                        Telefone VARCHAR (30)
                    )";

                command.CommandText = createTable;
                command.ExecuteNonQuery();

                //aqui iremos fazer um alter table apenas para mostrar que é possível
                string alterTable = "ALTER TABLE Pessoa ADD Column DataNascimento DATE";

                command.CommandText = alterTable;
                command.ExecuteNonQuery();

                MessageBox.Show(this, "Tabela criada com sucesso.", "Aviso!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Ocorreu um erro ao criar a tabela na base de dados.\n" +
                    ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Repare na linha em destaque o comando ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT aqui definimos que o campo ID será nossa chave primária do tipo inteiro e autoincremento. NO SQLite você não precisa definir a diretiva “AUTOINCREMENT“, pois por padrão toda chave primária do tipo inteiro é autoincremento. Mas, eu gosto de colocar.

Ok! Já criamos a nossa base de dados e já criamos a nossa tabela. Agora vamos manipular estes dados, para isso iremos codificar os botões btnInsert, btnUpdate, btnDelete e btnSelect.

Veja o código dos botões abaixo.

Botão btnInsert

private void btnInsert_Click(object sender, EventArgs e)
{
	if (!Validate(false)) return;

	SQLiteConnection conn = OpenConnection();
	SQLiteTransaction transaction = null;
	try
	{
		transaction = conn.BeginTransaction();
		SQLiteCommand command = conn.CreateCommand();
		string insertCommand = "INSERT INTO Pessoa (Nome, Telefone, DataNascimento) VALUES(?,?,?)";
		command.Parameters.Add("Nome", DbType.String).Value = txtNome.Text;
		command.Parameters.Add("Telefone", DbType.String).Value = txtTelefone.Text;
		command.Parameters.Add("DataNascimento", DbType.Date).Value = dtDataNascimento.Text;
		command.CommandText = insertCommand;
		command.ExecuteNonQuery();
		transaction.Commit();
		btnSelect.PerformClick();

	}
	catch (Exception ex)
	{
		if (transaction != null) transaction.Rollback();
		MessageBox.Show(this, "Ocorreu um erro ao inserir os dados na tabela.\n" +
						   ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);

	}
	finally { conn.Close(); }
}

Botão btnUpdate


private void Update_Click(object sender, EventArgs e)
{
	if (!Validate(true)) return;

	SQLiteConnection conn = OpenConnection();
	SQLiteTransaction transaction = null;
	try
	{
		transaction = conn.BeginTransaction();
		SQLiteCommand command = conn.CreateCommand();
		string updateCommand = "UPDATE Pessoa SET Nome = ?, Telefone = ?, DataNascimento =? WHERE ID = ?";
		command.Parameters.Add("Nome", DbType.String).Value = txtNome.Text;
		command.Parameters.Add("Telefone", DbType.String).Value = txtTelefone.Text;
		command.Parameters.Add("DataNascimento", DbType.Date).Value = dtDataNascimento.Text;
		command.Parameters.Add("ID", DbType.Int32).Value = txtID.Text;
		command.CommandText = updateCommand;
		command.ExecuteNonQuery();
		transaction.Commit();
		btnSelect.PerformClick();

	}
	catch (Exception ex)
	{
		if (transaction != null) transaction.Rollback();
		MessageBox.Show(this, "Ocorreu um erro ao inserir os dados na tabela.\n" +
						   ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);

	}
	finally { conn.Close(); }
}

Botão btnDelete

private void btnDelete_Click(object sender, EventArgs e)
{
	if (string.IsNullOrEmpty(txtID.Text) || Convert.ToInt32(txtID.Text) == 0)
	{
		MessageBox.Show(this, "Selecione um registro para excluir!", "Exluir!", MessageBoxButtons.OK, MessageBoxIcon.Information);
		return;
	}

	SQLiteConnection conn = OpenConnection();
	SQLiteTransaction transaction = null;
	try
	{
		transaction = conn.BeginTransaction();
		SQLiteCommand command = conn.CreateCommand();
		string deleteCommand = "DELETE FROM Pessoa WHERE ID = ?";
		command.Parameters.Add("ID", DbType.Int32).Value = txtID.Text;
		command.CommandText = deleteCommand;
		command.ExecuteNonQuery();
		transaction.Commit();
		btnSelect.PerformClick();
	}
	catch (Exception ex)
	{
		if (transaction != null) transaction.Rollback();
		MessageBox.Show(this, "Ocorreu um erro ao excluir os dados da tabela.\n" +
						   ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);

	}
	finally { conn.Close(); }
}

Botão btnSelect

private void btnSelect_Click(object sender, EventArgs e)
{
	try
	{
		RefreshGrid();
	}
	catch (Exception ex)
	{
		MessageBox.Show(this, "Ocorreu um erro ao selcionar os registros.\n" +
						   ex.Message, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);

	}
	finally { }
}

Precisaremos também de alguns métodos que irão nos auxiliar no decorrer do processo.

Preste atenção aos comentários de cada método.

#region Métodos Auxiliares
///
/// abre uma conexão e retorna
///
///
private SQLiteConnection OpenConnection()
{
	string dbFile = "sqlLite.db";
	//criamos a conexão com a base de dados
	SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbFile + ";Version=3;");
	//abrimos a conexão
	conn.Open();
	return conn;
}

///
/// atualiza a grid com os dados da base.
///
private void RefreshGrid()
{
	SQLiteConnection conn = OpenConnection();
	SQLiteCommand command = conn.CreateCommand();
	command.CommandText = "SELECT ID, Nome, Telefone, DataNascimento AS 'Data Nascto' FROM Pessoa";
	SQLiteDataReader rs = command.ExecuteReader();
	BindDataGrid(dataGridView, rs);
	conn.Close();
}

///
/// cria os campos da grid e prepara para exibir os dados da base
///
/// <param name="_dataGrid" />datagridview que deverá ser preparada
/// <param name="_rs" />recordset com os dados que deverão ser populados na grid
private void BindDataGrid(DataGridView _dataGrid, SQLiteDataReader _rs)
{
	_dataGrid.Rows.Clear();
	_dataGrid.Columns.Clear();

	for (int i = 0; i < _rs.FieldCount; i++)
	{
		DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
		col.HeaderText = _rs.GetName(i);
		col.Visible = true;
		col.Name = "col" + i;
		col.Resizable = DataGridViewTriState.True;
		_dataGrid.Columns.Add(col);
	}

	while (_rs.Read())
	{
		object[] row = new object[_rs.FieldCount];

		for (int i = 0; i < _rs.FieldCount; i++)
		{
			row[i] = FormatValue(_rs.GetValue(i), _rs.GetDataTypeName(i));
		}

		_dataGrid.Rows.Add(row);
	}
}

///
/// Formata um valor para ser exibido na grid
///
/// <param name="fieldValue" />valor do campo
/// <param name="fieldType" />tipo do campo
///
private object FormatValue(object fieldValue, string fieldType)
{
	string ret = "";

	if (fieldType.ToUpper() == "DATE")//só nos interessa o campo data para exemplo
		ret = string.Format("{0:dd/MM/yyyy}", fieldValue);
	else
		ret = fieldValue.ToString();

	return ret;
}

///
/// valida os dados do formulário e retorna
///
/// <param name="update" />se true valida o ID
///
new private bool Validate(bool update)
{
	if (string.IsNullOrEmpty(txtNome.Text))
	{
		MessageBox.Show(this, "Nome é obrigatório!", "Campo Obrigatório!", MessageBoxButtons.OK, MessageBoxIcon.Information);
		return false;
	}

	if (string.IsNullOrEmpty(txtTelefone.Text))
	{
		MessageBox.Show(this, "Telefone é obrigatório!", "Campo Obrigatório!", MessageBoxButtons.OK, MessageBoxIcon.Information);
		return false;
	}

	if (update)
	{
		if (string.IsNullOrEmpty(txtID.Text) || Convert.ToInt32(txtID.Text) == 0)
		{
			MessageBox.Show(this, "Selecione um registro para continuar!", "Registro!", MessageBoxButtons.OK, MessageBoxIcon.Information);
			return false;
		}
	}

	return true;
}
#endregion

Com isso apresentei a vocês o SQLite, com este tutorial você aprendeu tudo que é preciso para fazer uma aplicação usando esta base de dados embarcada.

Para saber mais sobre o SQLite Provider acesse o link http://system.data.sqlite.org

Para saber mais sobre o SQLite acesse o link http://sqlite.org/docs.html

Para saber mais sobre as strings de conexão para SQLite acesse o link http://www.connectionstrings.com/sqlite

Se tiver alguma dúvida, utilize o nosso fórum de C# link http://techblog.desenvolvedores.net/bbpress/forum.php?id=2

Download para o projeto de exemplo Csharp com SQLite (111)


É isso ai pessoal :)
Até o próximo
♦ Marcelo

About Marcelo

Nascido em Juruaia/MG em uma fazenda de criação de búfalos. Está perdido em São Paulo trabalhando com desenvolvimento de aplicações desde os 17 anos. Atualmente é arquiteto de software, é um cara meia boca que fica entre a equipe de desenvolvimento e o gerente de projetos, no meio da ponte. Para saber mais ... http://desenvolvedores.net/marcelo []'s

Cast de string para enum em C#

0
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (Sem votação.)
Loading ... Loading ...
22 de dezembro de 2010
Muitas vezes precisamos atribuir a uma propriedade do tipo enum um conteúdo, porem temos em mãos somente uma string com valor a ser atribuito, para realizar esta operação temos que fazer uma conversão ou como é mais conhecido fazer um casting, no qual segue abaixo um código de exemplo:
//Definir nosso enumerador
public enum Sexo
{
   Masculino,
   Feminino
}
//Vamos criar uma propriedade tendo como tipo o nosso enumerador
public Sexo SexoCliente { get; set; }

//Vamos criar uma variável contendo uma string do sexo escolhido
string mSexo = "Masculino";

//Agora vamos atribuir a nossa propriedade SexoCliente o conteúdo da variável mSexo
SexoCliente = (Sexo)Enum.Parse(typeof(Sexo),mSexo);
É isso ai.

Como recuperar a descrição do enumerador partindo do código dele

1
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (Sem votação.)
Loading ... Loading ...
17 de dezembro de 2010

Em muitos casos temos a necessidade de recuperar a descrição de um Enum partindo do código, pois é este que temos gravado em nosso banco de dados, veja como:

//Enumerador de tipos
public enum GenericDBType
{
    Bit = 0,
    String = 1,
    Object = 2,
    Datetime = 3
}
//Digamos que eu tenha gravado no meu banco o código do enumerador
//neste caso vamos eleger o String (código 1), agora eu desejo recuperar
//a descrição do enumerador (String) a partir do código gravado (1).
//É bem simples, veja:
//Código que tá gravado no banco de dados

int codigoGravadoBanco = 1;
//o retorno será "String"

Enum.GetName(typeof(GenericDbType), codigoGravadoBanco); 

É isso ai, bem simples… :)

InputBox em CSharp

0
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (Sem votação.)
Loading ... Loading ...
10 de dezembro de 2010

Ola Pessoal.

Neste artigo eu vou falar de uma carência que o C# tem. O InputBox.

O C# não possui um InputBox, logo temos que criar um, aqui vai um código que facilita a vida.

Com este inputBox você pode tratar as teclas pressionadas pelo usuário, bem como modificar o título, o valor inicial, exibir uma mensagem ao usuário.

Bom, vamos deixar de falatório (ou seria escrevetório, nossa forcei agora). E vamos ao que interessa.
Vou assumir que você tem conhecimento em C#.

Crie um novo projeto to tipo Class Lybrary, isso irá criar para você uma DLL.

Na classe que veio como padrão, renomeie para InputBox.cs e utilize o código abaixo para fazer a sua DLL.

Copiar e colar amigável: http://desenvolvedores.net.pastebin.com/raw.php?i=czRKYN7F

Código:

/*
 * Exemplo de inpuBox em C#.
 * By http://desenvolvedores.net
 */
using System;
using System.Windows.Forms;

/*
 * definimos o namespace como System.Windows.Forms apenas
 * para manter no mesmo local que a MessageBox
 */
namespace System.Windows.Forms
{
    #region Formulário
    internal sealed class _InputBox : System.Windows.Forms.Form
    {
        #region Locais
        internal System.Windows.Forms.TextBox txtInput;
        private Button cmdOK;
        private Button cmdCancel;
        internal Label lblUserInfo;
        private System.ComponentModel.Container components = null;

        /// <summary>
        /// tratar os eventos de pressionamento de teclas e develver ao usuário
        /// </summary>
        internal KeyPressEventHandler keyPress = null;
        #endregion

        #region Construtor
        public _InputBox()
        {
            InitializeComponent();
            lblUserInfo.Text = "";
            txtInput.Text = "";
        }
        #endregion

        #region Métodos de criação e dipose do form
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.txtInput = new System.Windows.Forms.TextBox();
            this.cmdOK = new System.Windows.Forms.Button();
            this.cmdCancel = new System.Windows.Forms.Button();
            this.lblUserInfo = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // txtInput
            //
            this.txtInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtInput.Location = new System.Drawing.Point(16, 16);
            this.txtInput.Name = "txtInput";
            this.txtInput.Size = new System.Drawing.Size(256, 20);
            this.txtInput.TabIndex = 0;
            this.txtInput.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtInput_KeyDown);
            this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtInput_KeyPress);
            //
            // cmdOK
            //
            this.cmdOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.cmdOK.Location = new System.Drawing.Point(124, 46);
            this.cmdOK.Name = "cmdOK";
            this.cmdOK.Size = new System.Drawing.Size(71, 26);
            this.cmdOK.TabIndex = 1;
            this.cmdOK.Text = "OK";
            this.cmdOK.UseVisualStyleBackColor = true;
            this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
            //
            // cmdCancel
            //
            this.cmdCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.cmdCancel.Location = new System.Drawing.Point(201, 46);
            this.cmdCancel.Name = "cmdCancel";
            this.cmdCancel.Size = new System.Drawing.Size(71, 26);
            this.cmdCancel.TabIndex = 2;
            this.cmdCancel.Text = "Cancelar";
            this.cmdCancel.UseVisualStyleBackColor = true;
            this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
            //
            // lblUserInfo
            //
            this.lblUserInfo.AutoSize = true;
            this.lblUserInfo.Location = new System.Drawing.Point(16, 0);
            this.lblUserInfo.MaximumSize = new System.Drawing.Size(256, 0);
            this.lblUserInfo.Name = "lblUserInfo";
            this.lblUserInfo.Size = new System.Drawing.Size(140, 13);
            this.lblUserInfo.TabIndex = 3;
            this.lblUserInfo.Text = "XXXXXXXXXXXXXXXXXXX";
            //
            // _InputBox
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 73);
            this.ControlBox = false;
            this.Controls.Add(this.lblUserInfo);
            this.Controls.Add(this.cmdCancel);
            this.Controls.Add(this.cmdOK);
            this.Controls.Add(this.txtInput);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "_InputBox";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "InputBox";
            this.TopMost = true;
            this.Shown += new System.EventHandler(this._InputBox_Shown);
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        #region Método Show
        public new string Show()
        {
            base.ShowDialog();
            return this.txtInput.Text;
        }
        #endregion

        #region Tratamento das ações do usuário
        private void txtInput_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                cmdOK.PerformClick();
            else if (e.KeyCode == Keys.Escape)
                cmdCancel.PerformClick();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            txtInput.Text = "";
            this.Close();
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void _InputBox_Shown(object sender, EventArgs e)
        {
            //aqui temos que redimensionar o form por causa do tamanho da Label

            txtInput.Top = lblUserInfo.Top + lblUserInfo.Height + 5;
            this.Height = txtInput.Top + txtInput.Height + 60;
        }

        private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (keyPress != null)
                keyPress.Invoke(sender, e);
        }
        #endregion

    }
    #endregion

    #region Classe InputBox
    public static class InputBox
    {
        #region Métodos Show
        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <returns>string digitada</returns>
        public static string Show()
        {
            return InputBox.Show("", "", "", null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, KeyPressEventHandler keyHandler)
        {
            return InputBox.Show(Title, "", "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler)
        {
            return InputBox.Show("", "", "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler, string initalValue)
        {
            return InputBox.Show("", "", initalValue, keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string userInfo, string initalValue, KeyPressEventHandler keyHandler)
        {
            return InputBox.Show("", userInfo, initalValue, keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler, string Title, string userInfo)
        {
            return InputBox.Show(Title, userInfo, "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo, string initalValue)
        {
            return InputBox.Show(Title, userInfo, initalValue, null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo)
        {
            return InputBox.Show(Title, userInfo, "", null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo, string initalValue, KeyPressEventHandler keyHandler)
        {
            using (_InputBox input = new _InputBox())
            {
                input.Text = string.IsNullOrEmpty(Title) ? "Infome um valor..." : Title;
                input.lblUserInfo.Text = userInfo;
                input.txtInput.Text = initalValue;
                if (keyHandler != null) input.keyPress = keyHandler;
                return input.Show();
            }
        }
        #endregion
    }
    #endregion
}

Exmplo de uso:
Adicione um novo projeto à sua solução do tipo Windows Forms Application
Faça referência a sua DLL.

Copiar e colar amigável: http://desenvolvedores.net.pastebin.com/raw.php?i=HqxqLyTT

/*
 * Exemplo de uso InputBox C#
 * by http://desenvolvedores.net
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InputBoxExample
{
    public class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        private void btnComHandler_Click(object sender, EventArgs e)
        {
            KeyPressEventHandler keyPress = new KeyPressEventHandler(InputBoxKeyPress);
            txtTeclaPressionada.Text = "";
            MessageBox.Show(InputBox.Show(keyPress, "Digite alguma coisa", "O que você digitar aqui irá aparecer na caixa de texto do formulário."));
        }
        private void InputBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            txtTeclaPressionada.Text += e.KeyChar;
        }
        private void btnApenasTestar_Click(object sender, EventArgs e)
        {
            txtApenasTestar.Text = InputBox.Show();
        }
        private void btnValorInicial_Click(object sender, EventArgs e)
        {
            MessageBox.Show(InputBox.Show("Digite alguma coisa", "O que você digitou no textbox irá aparecer no textBox abaixo.", txtValorInicial.Text));
        }
        #region Componentes
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnComHandler = new System.Windows.Forms.Button();
            this.lblTeclaPressionada = new System.Windows.Forms.Label();
            this.txtTeclaPressionada = new System.Windows.Forms.TextBox();
            this.btnApenasTestar = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtApenasTestar = new System.Windows.Forms.TextBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.label2 = new System.Windows.Forms.Label();
            this.txtValorInicial = new System.Windows.Forms.TextBox();
            this.btnValorInicial = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.SuspendLayout();
            //
            // btnComHandler
            //
            this.btnComHandler.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnComHandler.Location = new System.Drawing.Point(249, 43);
            this.btnComHandler.Name = "btnComHandler";
            this.btnComHandler.Size = new System.Drawing.Size(250, 32);
            this.btnComHandler.TabIndex = 2;
            this.btnComHandler.Text = "Testar capturando a tecla pressionada";
            this.btnComHandler.UseVisualStyleBackColor = true;
            this.btnComHandler.Click += new System.EventHandler(this.btnComHandler_Click);
            //
            // lblTeclaPressionada
            //
            this.lblTeclaPressionada.AutoSize = true;
            this.lblTeclaPressionada.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblTeclaPressionada.Location = new System.Drawing.Point(6, 19);
            this.lblTeclaPressionada.Name = "lblTeclaPressionada";
            this.lblTeclaPressionada.Size = new System.Drawing.Size(108, 13);
            this.lblTeclaPressionada.TabIndex = 0;
            this.lblTeclaPressionada.Text = "Teclas Pressionadas:";
            //
            // txtTeclaPressionada
            //
            this.txtTeclaPressionada.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtTeclaPressionada.Location = new System.Drawing.Point(120, 17);
            this.txtTeclaPressionada.Name = "txtTeclaPressionada";
            this.txtTeclaPressionada.Size = new System.Drawing.Size(379, 20);
            this.txtTeclaPressionada.TabIndex = 1;
            //
            // btnApenasTestar
            //
            this.btnApenasTestar.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnApenasTestar.Location = new System.Drawing.Point(249, 53);
            this.btnApenasTestar.Name = "btnApenasTestar";
            this.btnApenasTestar.Size = new System.Drawing.Size(250, 32);
            this.btnApenasTestar.TabIndex = 2;
            this.btnApenasTestar.Text = "Apenas Testar";
            this.btnApenasTestar.UseVisualStyleBackColor = true;
            this.btnApenasTestar.Click += new System.EventHandler(this.btnApenasTestar_Click);
            //
            // groupBox1
            //
            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.btnComHandler);
            this.groupBox1.Controls.Add(this.lblTeclaPressionada);
            this.groupBox1.Controls.Add(this.txtTeclaPressionada);
            this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox1.Location = new System.Drawing.Point(12, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(511, 91);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Capturando as Teclas";
            //
            // groupBox2
            //
            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Controls.Add(this.txtApenasTestar);
            this.groupBox2.Controls.Add(this.btnApenasTestar);
            this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox2.Location = new System.Drawing.Point(12, 129);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(511, 91);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Apenas Testar";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(6, 21);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(48, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Retorno:";
            //
            // txtApenasTestar
            //
            this.txtApenasTestar.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtApenasTestar.Location = new System.Drawing.Point(120, 19);
            this.txtApenasTestar.Name = "txtApenasTestar";
            this.txtApenasTestar.Size = new System.Drawing.Size(379, 20);
            this.txtApenasTestar.TabIndex = 1;
            //
            // groupBox3
            //
            this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox3.Controls.Add(this.label2);
            this.groupBox3.Controls.Add(this.txtValorInicial);
            this.groupBox3.Controls.Add(this.btnValorInicial);
            this.groupBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox3.Location = new System.Drawing.Point(12, 237);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(511, 91);
            this.groupBox3.TabIndex = 2;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Valor Inicial";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(6, 21);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(99, 13);
            this.label2.TabIndex = 0;
            this.label2.Text = "Digite o valor Inicial";
            //
            // txtValorInicial
            //
            this.txtValorInicial.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtValorInicial.Location = new System.Drawing.Point(120, 19);
            this.txtValorInicial.Name = "txtValorInicial";
            this.txtValorInicial.Size = new System.Drawing.Size(379, 20);
            this.txtValorInicial.TabIndex = 1;
            //
            // btnValorInicial
            //
            this.btnValorInicial.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnValorInicial.Location = new System.Drawing.Point(249, 53);
            this.btnValorInicial.Name = "btnValorInicial";
            this.btnValorInicial.Size = new System.Drawing.Size(250, 32);
            this.btnValorInicial.TabIndex = 2;
            this.btnValorInicial.Text = "Com valor inicial";
            this.btnValorInicial.UseVisualStyleBackColor = true;
            this.btnValorInicial.Click += new System.EventHandler(this.btnValorInicial_Click);
            //
            // frmMain
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(535, 340);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "InputBox em C#";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.ResumeLayout(false);
        }
        #endregion
        private System.Windows.Forms.Button btnComHandler;
        private System.Windows.Forms.Label lblTeclaPressionada;
        private System.Windows.Forms.TextBox txtTeclaPressionada;
        private System.Windows.Forms.Button btnApenasTestar;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtApenasTestar;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtValorInicial;
        private System.Windows.Forms.Button btnValorInicial;
        #endregion
    }
}

Para os mais preguiçosos, faça o download do exemplo completo abaixo:
InputBox em C# (76)

É isso ai pessoal :)
Até o próximo
 ♦ Marcelo

About Marcelo

Nascido em Juruaia/MG em uma fazenda de criação de búfalos. Está perdido em São Paulo trabalhando com desenvolvimento de aplicações desde os 17 anos. Atualmente é arquiteto de software, é um cara meia boca que fica entre a equipe de desenvolvimento e o gerente de projetos, no meio da ponte. Para saber mais ... http://desenvolvedores.net/marcelo []'s

Paginação remota com ext.net, CSharp e ASPX

1
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (1 votos, média: 5,00 de 5)
Loading ... Loading ...
8 de dezembro de 2010

Olá Pessoal.

Neste tutorial eu vou escrever e falar  sobre paginação remota utilizando o Ext.Net, C# e ASP.Net.

Antes de começar, uma rápida revisão sobre paginação.

O que é paginação?
Paginação (paginar) consiste em dividir em partes (páginas).
Imagine o jornal que você lê, ele é dividido em páginas para que facilite a sua leitura, você pode virar as páginas ou ir para uma página específica do seu jornal e continuar a sua leitura, o mesmo acontece com livros, revistas etc.

Agora vamos imaginar a paginação dos dados.
Quando você abre um conjunto de registros, a exibição ao usuário pode se tornar lenta, se o número de registros for grande, neste momento você precisa paginar o seu conjunto de registros, ou tupla se você preferir.

Uma tupla é cada linha de registro de uma tabela na base de dados

A idéia de paginar os seus registros é o mesmo que o jornal faz, dividir e exibir o todo em partes.

Agora vamos ao que interessa.

No ext.net existe o componente PagingToolbar

<ext:PagingToolbar></ext:PagingToolbar>

Ele é o responsável pela interface ao usuário e por gerar os eventos necessários para a paginação.

Como tudo acontece.

Quando você clica no botão de navegação o ext envia uma requisição ao servidor, passando como parâmetros no Request as seguintes variáveis start e limit

Estas duas variáveis são responsáveis por dizer onde começa e qual o tamanho da página.

Ok! Mas como o ASPXvai capturar estas informações?

Para tratarmos estes eventos dentro do ASPX temos que usar handlers.

Opa! O que são handlers?

Os handlers são responsáveis por interceptar solicitações feitas ao servidor de aplicativo.
Eles são executados como processos em resposta a um pedido feito pelo site.

Você pode criar seus próprios handlers genéricos (ashx) que processam a saída e enviam ao navegador.

Para programar um handler genérico o mesmo deverá implementar a interface System.Web.IHttpHandler.
As interfaces exigem que você implemente o método ProcessRequest e a propriedade IsReusable.

O método ProcessRequest manipula o processamento para as solicitações feitas, enquanto o booleano IsReusable é a propriedade que diz se o manipulador é reutilizável ou se um novo manipulador é necessário para cada solicitação.

Declaração básica para um handler genérico:

Diretiva de página:
<%@ WebHandler Language=”C#Class=”DeclaracaoBasica %>

Código da página

using System;
using System.Web;

public class DeclaracaoBasica : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Bom, agora que temos os pré-requisitos vamos à nossa vídeo-aula clique no vídeo abaixo e assista.

O som do vídeo está baixo, recomendo o uso de um fone de ouvido.

Desvendando a paginação remota com ext.net, aspx, csharp
Tempo de execução
14:51
Visualizações
997

Se preferir, assista direto no youtube http://www.youtube.com/watch?v=BjFpW-Mg-bg&hd=1

Download do código de exemplo:
Paginação remota com Ext.net, handlers, aspx e C# (127)

Dúvidas? Poste-as no fórum referindo-se a este tutorial.
http://desenvolvedores.net/ext.net

É isso ai pessoal :)
Até o próximo
♦ Marcelo

About Marcelo

Nascido em Juruaia/MG em uma fazenda de criação de búfalos. Está perdido em São Paulo trabalhando com desenvolvimento de aplicações desde os 17 anos. Atualmente é arquiteto de software, é um cara meia boca que fica entre a equipe de desenvolvimento e o gerente de projetos, no meio da ponte. Para saber mais ... http://desenvolvedores.net/marcelo []'s