Script Pronto (ASP.NET) - Aplicacao em 3 camadas

Este fórum é para dúvidas onde a base da questão é a linguagem ASP.

Moderador: web

responder a dúvida

Script Pronto (ASP.NET) - Aplicacao em 3 camadas

Mensagem por Rodrigo1 Offline » Qui Fev 26, 2009 6:54 pm


Vou dar uma ajudinha aí pra quem ta iniciando em asp.net

Um dos esquemas do asp.net é programar em 3 camadas:
A camada de Modelos (Models Layer)
A camada de acesso a dados (Data Access Layer)
A Camada das regras de negocio(Bussiness Logic Layer)

Vou dar um exemplo de cada uma aqui e depois como usar na pagina .aspx

Models
Aqui vc cria suas variaveis e os metodos que setam e pagam o valor
O método SET é o que seta o novo valor para a variavel e o GET é qdo vc pega o valor em algum lugar

Código: Selecionar todos
Public Class ClientesInfo
    Private _fNome As String
    Private _fCpf As String
    Private _fRg As String

Public Property fNome() As String
        Get
            Return _fNome
        End Get
        Set(ByVal value As String)
            _fNome = value
        End Set
    End Property

    Public Property fCpf() As String
        Get
            Return _fCpf
        End Get
        Set(ByVal value As String)
            _fCpf = value
        End Set
    End Property

    Public Property fRg() As String
        Get
            Return _fRg
        End Get
        Set(ByVal value As String)
            _fRg = value
        End Set
    End Property

End Class

Data Access Layer
Nesta aqui vc se conecta no banco de dados e faz tudo com o bd nela
Código: Selecionar todos
Public Class Cliente
    ''' <summary>
    ''' Inserir Cliente
    ''' </summary>
    ''' <param name="MyClientesInfo"></param>
    ''' <remarks></remarks>
    Public Sub InserirCliente(ByVal MyClientesInfo As ClientesInfo)' Aqui a gente faz a relacao com o modelo
        Dim aDataAniversario As Array
        aDataAniversario = Split(MyClientesInfo.fAniversario, "/")

        Dim vDataAniversario As String
        vDataAniversario = aDataAniversario(2) + "/" + aDataAniversario(1) + "/" + aDataAniversario(0)

        Dim oConn As New SqlConnection(Dados.Conexao.ToString)
        Try

            Dim oCmd As New SqlCommand("InserirCliente", oConn)
            oCmd.CommandType = CommandType.Text
            Dim vSql As String = "Insert into Clientes(Id, Nome, CPF, RG) VALUES (@cli_codigo, @cli_nome_, @cli_cpf, @rg)"
            oCmd.CommandText = vSql
            Dim vUltimoRegistro As Double = Dados.ultimoRegistroCliente + 1
            oCmd.Parameters.Add(New SqlParameter("@cli_codigo", vUltimoRegistro))'vUltimo registro é uma funcao que pega o ultimo registro do bd, está no forum tbm
            oCmd.Parameters.Add(New SqlParameter("@cli_nome_", MyClientesInfo.fNome))
            oCmd.Parameters.Add(New SqlParameter("@cli_cpf", MyClientesInfo.fCpf))
            oCmd.Parameters.Add(New SqlParameter("@rg", MyClientesInfo.fRg))
       
            oConn.Open()
            oCmd.ExecuteNonQuery()

            Throw New Exception("Cliente Cadastrado!")

        Catch ex As Exception
            'Throw New Exception("Cliente Nao Cadastrado, Contate o profissional de T.I.!")
            Throw New Exception(ex.Message)
            oConn.Close()
        End Try
    End Sub



End Class

Agora o Business logic Layer a gente escolhe as regras de negocio, tal como nao deixar escrever texto no telefone
Ps:Vc pode usar os validadores tbm
Código: Selecionar todos
Public Class ClienteBLL
    Public Sub CadastrarCliente(ByVal Cliente As ClientesInfo)
       
         If Cliente.fIdEmpresa = "" Then
            Throw New Exception("Selecione uma empresa.")
        End If
        Try
            Convert.ToDouble(Cliente.fIdEmpresa)
        Catch ex As Exception
            Throw New Exception("Selecione a empresa direto da tabela.")
        End Try
        '-----------------------------------------


        Dim ClienteDAL As New Cliente
        ClienteDAL.InserirCliente(Cliente)
    End Sub
End Class

Aqui a gente apenas atribui as variaveis aos modelos e pronto
Código: Selecionar todos
Sub GravaCliente()
        Try
            Dim oClientesInfo As New ClientesInfo
            With oClientesInfo
                .fNome = fNomeTextBox.Text
                .fCpf = fCpfTextBox.Text
                .fRg = fRgTextBox.Text

            End With

            Dim oClientesBLL As New ClienteBLL
            oClientesBLL.CadastrarCliente(oClientesInfo)

        Catch ex As Exception
            MensagemLabel.Text = ex.Message
            MensagemLabel.ForeColor = Color.Red
        End Try
    End Sub


Qq duvidas post

Nao tive tempo de detalhar mto!



detalhes...

Contribua você tambem com o forum!
Nao abandone seu post, responda se der certo!
Paz!

Avatar do usuário
Rodrigo1
SUPER ATIVO
SUPER ATIVO
Mensagens: 93
Registrado em: Qui Nov 06, 2008 2:49 pm
Localização: Sao Paulo

Script Pronto (ASP.NET) - Aplicacao em 3 camadas

Mensagem por Rodrigo1 Offline » Ter Mar 24, 2009 2:58 pm

Quem quiser em C#

Models
Aqui vc cria suas variaveis e os metodos que setam e pagam o valor
O método SET é o que seta o novo valor para a variavel e o GET é qdo vc pega o valor em algum lugar

Código: Selecionar todos
public class ClientesInfo
{
   private string _fNome;
   private string _fCpf;
   private string _fRg;

   public string fNome {
      get { return _fNome; }
      set { _fNome = value; }
   }

   public string fCpf {
      get { return _fCpf; }
      set { _fCpf = value; }
   }

   public string fRg {
      get { return _fRg; }
      set { _fRg = value; }
   }

}

Data Access Layer
Nesta aqui vc se conecta no banco de dados e faz tudo com o bd nela

Código: Selecionar todos
public class Cliente
{
   /// <summary>
   /// Inserir Cliente
   /// </summary>
   /// <param name="MyClientesInfo"></param>
   /// <remarks></remarks>
   // Aqui a gente faz a relacao com o modelo
   public void InserirCliente(ClientesInfo MyClientesInfo)
   {
      Array aDataAniversario;
      aDataAniversario = Split(MyClientesInfo.fAniversario, "/");

      string vDataAniversario;
      vDataAniversario = aDataAniversario(2) + "/" + aDataAniversario(1) + "/" + aDataAniversario(0);

      SqlConnection oConn = new SqlConnection(Dados.Conexao.ToString);
      try {

         SqlCommand oCmd = new SqlCommand("InserirCliente", oConn);
         oCmd.CommandType = CommandType.Text;
         string vSql = "Insert into Clientes(Id, Nome, CPF, RG) VALUES (@cli_codigo, @cli_nome_fantasia, @cli_cnpj, @rg)";
         oCmd.CommandText = vSql;
         double vUltimoRegistro = Dados.ultimoRegistroCliente + 1;
         oCmd.Parameters.Add(new SqlParameter("@cli_codigo", vUltimoRegistro));
         //vUltimo registro é uma funcao que pega o ultimo registro do bd, está no forum tbm
         oCmd.Parameters.Add(new SqlParameter("@cli_nome_fantasia", MyClientesInfo.fNome));
         oCmd.Parameters.Add(new SqlParameter("@cli_cnpj", MyClientesInfo.fCpf));
         oCmd.Parameters.Add(new SqlParameter("@rg", MyClientesInfo.fRg));

         oConn.Open();
         oCmd.ExecuteNonQuery();

         throw new Exception("Cliente Cadastrado!");
      }

      catch (Exception ex) {
         //Throw New Exception("Cliente Nao Cadastrado, Contate o profissional de T.I.!")
         throw new Exception(ex.Message);
         oConn.Close();
      }
   }



}


Agora o Business logic Layer a gente escolhe as regras de negocio, tal como nao deixar escrever texto no telefone
Ps:Vc pode usar os validadores tbm

Código: Selecionar todos
public class ClienteBLL
{
   public void CadastrarCliente(ClientesInfo Cliente)
   {

      if (Cliente.fIdEmpresa == "") {
         throw new Exception("Selecione uma empresa.");
      }
      try {
         Convert.ToDouble(Cliente.fIdEmpresa);
      }
      catch (Exception ex) {
         throw new Exception("Selecione a empresa direto da tabela.");
      }
      //-----------------------------------------


      Cliente ClienteDAL = new Cliente();
      ClienteDAL.InserirCliente(Cliente);
   }
}

Aqui a gente apenas atribui as variaveis aos modelos e pronto

Código: Selecionar todos
void GravaCliente()
{
   try {
      ClientesInfo oClientesInfo = new ClientesInfo();
       
                oClientesInfo.fNome = fNomeTextBox.Text
                oClientesInfo.fCpf = fCpfTextBox.Text
                oClientesInfo.fRg = fRgTextBox.Text

             ClienteBLL oClientesBLL = new ClienteBLL();
      oClientesBLL.CadastrarCliente(oClientesInfo);
   }

   catch (Exception ex) {
      MensagemLabel.Text = ex.Message;
      MensagemLabel.ForeColor = Color.Red;
   }
}

Falou galera

detalhes...

Contribua você tambem com o forum!
Nao abandone seu post, responda se der certo!
Paz!

Avatar do usuário
Rodrigo1
SUPER ATIVO
SUPER ATIVO
Mensagens: 93
Registrado em: Qui Nov 06, 2008 2:49 pm
Localização: Sao Paulo


responder a dúvida

Voltar para Asp

Quem está online

Usuários navegando neste fórum: Nenhum usuário registrado e 1 visitante