 VB .NET - Criando uma 
aplicação em camadas (de novo) III
  
VB .NET - Criando uma 
aplicação em camadas (de novo) III
Continuando o artigo VB .NET - Criando uma aplicação em camadas (de novo) II vou definir o conteúdo das classes DALCurso e DALEstudantes que fazem parte da camada de acesso a dados que foi definida como um projeto distinto com o nome de DataAccessLayer.
Estas classes terão a responsabilidade de conhecer e acessar o sistema de persistência que neste exemplo esta sendo representando por um banco de dados do Microsoft Access. Neste contexto a classe DALCurso tem a especialidade de acessar os dados e realizar as operações pertinentes aos Cursos definido pela entidade Curso e representada pela tabela Cursos do banco de dados Matricula.mdb.
Definindo a classe DALCurso
A classe DALCurso possui a seguinte estrutura onde temos representados os imports, namespaces, variáveis e métodos públicos e privados:
|  | 
Com isso em mente vamos declarar no início do arquivo DALCurso.vb os imports usados:
Imports
SystemA seguir vamos declarar um namespace :
Namespace
DAL.CursoA seguir defina o nome da classe :
Public
Class DALCursoVamos as variáveis usadas para tratar os objetos de acesso a dados, no caso os objetos do provedor OleDb. Criamos dessa forma um objetos do tipo Connection, Command, Adapter e Dataset e o mais importante obtemos a string de conexão definida em My.Settings :
|  | 
Private _conStr As String = My.Settings.DataConnection.ToString()
Private _olecon As OleDb.OleDbConnection = Nothing
Private _olecom As OleDb.OleDbCommand = Nothing Private _oledap As OleDb.OleDbDataAdapter = Nothing Private _dset As DataSet = Nothing Private _preco As Double = 0Na classe DALCurso iremos definir dois métodos que acessam os dados dos cursos:
Estes métodos são chamados pela classe BLLCurso da camada de negócio - BusinessLogicLayer.
1- Método TodosCursos()
| Public 
    Function TodosCursos()
    As 
    DataSet _dset =Nothing Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="SELECT cursoID,cursoNome " & _ "FROM Cursos ORDER BY cursoID" End With 
 _dset =New DataSet() _oledap.Fill(_dset)Catch ex As Exception _dset =Nothing Throw ex Finally liberaTodosObjetos()End Try Return _dset End Function | 
2- Método getCursoPreco() - passa como parâmetro o código do curso (CursoID)
| Public 
    Function getCursoPreco(ByVal 
    CursoID As
    Integer) 
    As 
    Double 
 _preco = 0 Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _olecom =New OleDb.OleDbCommand() 
 With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText = "SELECT cursoPreco FROM Cursos WHERE cursoID =@CursoID" .Parameters.Add("@CursoID", OleDbType.Integer).Value = CursoID _preco =CType(.ExecuteScalar(), Double) End With 
 _olecom.Parameters.Clear()Catch ex As Exception _preco = 0Throw ex Finally liberaTodosObjetos()End Try Return _preco End Function | 
Temos também um método de suporte que libera os objetos usados, liberaTodosObjetos() cujo código é:
| Private
    Sub liberaTodosObjetos() If _oledap IsNot Nothing Then _oledap.Dispose() _oledap = NothingEnd If If _olecom IsNot Nothing Then _olecom.Cancel() _olecom.Dispose() _olecom = NothingEnd If If _olecon IsNot Nothing Then If _olecon.State = ConnectionState.Open Then _olecon.Close() End If _olecon.Dispose() _olecon = NothingEnd If End Sub | 
Definindo a classe DALEstudantes
A classe DALEstudantes possui a seguinte estrutura onde temos representados os imports, namespaces, variáveis e métodos públicos e privados:
|  | 
Começamos com a declaração no início do arquivo DALEstudantes.vb, os imports usados:
Imports
SystemA seguir vamos declarar um namespace :
Namespace
DAL.EstudantesA seguir defina o nome da classe :
Public
Class DALEstudantesA seguir definimos as variáveis e objetos usados na classe:
Private _conStr As String = My.Settings.DataConnection.ToString()Private _olecon As OleDb.OleDbConnection = Nothing
Private _olecom As OleDb.OleDbCommand = Nothing Private _oledap As OleDb.OleDbDataAdapter = Nothing Private _dset As DataSet = Nothing Private _dlinha As DataRow = Nothing Private _transacao As OleDb.OleDbTransaction = Nothing Private _idvalor As Object = Nothing Private _retvalor As Boolean = FalseA classe DALEstudantes terá os seguintes métodos responsáveis pelo acesso a dados dos estudantes:
Esses métodos são chamados pela classe BLLEstudante da camada de negócio - BusinessLogicLayer.
| Public 
    Function 
    ProximoEstudanteID() As
    
    String _idvalor =Nothing Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="SELECT MAX(EstudanteID) AS EstudanteID FROM Estudantes" _idvalor = .ExecuteScalar()End With 'Formato do Numero do Estudante. Ex:S0001, S0002 ' ---- SXXXX If _idvalor Is Nothing Or _idvalor.Equals(System.DBNull.Value) Then _idvalor ="S0001" Else Dim valor As Integer = 0 valor = _idvalor.ToString().Substring(1, (_idvalor.ToString().Length - 1)) + 1If valor >= 0 And valor <= 9 Then _idvalor = "S000" & valor.ToString() If valor >= 10 And valor <= 99 Then _idvalor = "S00" & valor.ToString() If valor >= 100 And valor <= 999 Then _idvalor = "S0" & valor.ToString() If valor >= 1000 And valor <= 9999 Then _idvalor = "S" & valor.ToString() End If Catch ex As Exception _idvalor =Nothing Throw ex Finally liberaTodosObjetos()End Try Return _idvalor.ToString() End Function 
 | 
| ProximoEstudanteID | 
| PublicFunction CriaNovoEstudante(ByVal EstudanteID As String, ByVal CursoID As Integer, ByVal EstudanteNome As String, _ ByVal EstudanteEndereco As String, ByVal Telefone As String, _ ByVal Idade As Integer, ByVal EstaPago As Boolean) As Boolean _retvalor =False Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _transacao = _olecon.BeginTransaction(IsolationLevel.ReadCommitted) _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="INSERT INTO Estudantes " & _ "(EstudanteID,cursoID,estudanteNome,estudanteEndereco,estudanteTelefone,estudanteIdade,estudantePago,estudanteDataRegistro) VALUES " & _ "(@EstudanteID,@cursoID,@estudanteNome,@estudanteEndereco,@estudanteTelefone,@estudanteIdade,@estudantePago,@estudanteDataRegistro)" .Parameters.Add("@EstudanteID", OleDbType.VarChar, 5).Value = EstudanteID.Trim() .Parameters.Add("@cursoID", OleDbType.Integer).Value = CursoID .Parameters.Add("@estudanteNome", OleDbType.VarChar, 100).Value = EstudanteNome.Trim() .Parameters.Add("@estudanteEndereco", OleDbType.VarChar, 100).Value = EstudanteEndereco.Trim() .Parameters.Add("@estudanteTelefone", OleDbType.VarChar, 10).Value = Telefone.Trim() .Parameters.Add("@estudanteIdade", OleDbType.Integer).Value = Idade .Parameters.Add("@estudantePago", OleDbType.Boolean).Value = EstaPago .Parameters.Add("@estudanteDataRegistro", OleDbType.Date).Value = Now.ToString("dd/MMM/yyyy") .Transaction = _transacao .ExecuteNonQuery() .Parameters.Clear()End With _transacao.Commit() _retvalor =True Catch ex As Exception _transacao.Rollback()Throw ex Finally liberaTodosObjetos()End Try Return _retvalor End Function 
 
 | 
| CriaNovoEstudante() | 
| Public 
    Function 
    AtualizaEstudante(ByVal 
    EstudanteID As
    String, 
    ByVal CursoID 
    As 
    Integer, 
    ByVal EstudanteNome
    As 
    String, 
    _
    
    ByVal EstudanteEndereco
    As 
    String, 
    ByVal Telefone 
    As 
    String, 
    _
    
    ByVal Idade 
    As 
    Integer, 
    ByVal EstaPago 
    As 
    Boolean) 
    As 
    Boolean _retvalor =False Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _transacao = _olecon.BeginTransaction(IsolationLevel.ReadCommitted) _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="UPDATE Estudantes " & _ "SET cursoID =@cursoID," & _ "estudanteNome =@estudanteNome," & _ "estudanteEndereco =@estudanteEndereco," & _ "estudanteTelefone =@estudanteTelefone," & _ "estudanteIdade = @estudanteIdade," & _ "estudantePago = @estudantePago " & _ "WHERE EstudanteID=@EstudanteID" .Parameters.Add("@cursoID", OleDbType.Integer).Value = CursoID .Parameters.Add("@estudanteNome", OleDbType.VarChar, 100).Value = EstudanteNome.Trim() .Parameters.Add("@estudanteEndereco", OleDbType.VarChar, 100).Value = EstudanteEndereco.Trim() .Parameters.Add("@estudanteTelefone", OleDbType.VarChar, 10).Value = Telefone.Trim() .Parameters.Add("@estudanteIdade", OleDbType.Integer).Value = Idade .Parameters.Add("@estudantePago", OleDbType.Boolean).Value = EstaPago .Parameters.Add("@EstudanteID", OleDbType.VarChar, 5).Value = EstudanteID.Trim() .Transaction = _transacao .ExecuteNonQuery() .Parameters.Clear()End With _transacao.Commit() _retvalor =True Catch ex As Exception _transacao.Rollback()Throw ex Finally liberaTodosObjetos()End Try Return _retvalor End Function 
 | 
| AtualizaEstudante | 
| PublicFunction ExcluiEstudante(ByVal EstudanteID As String) As Boolean _retvalor =False Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _transacao = _olecon.BeginTransaction(IsolationLevel.ReadCommitted) _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="DELETE FROM Estudantes WHERE EstudanteID=@EstudanteID" .Parameters.Add("@EstudanteID", OleDbType.VarChar, 5).Value = EstudanteID.Trim() .Transaction = _transacao .ExecuteNonQuery() .Parameters.Clear()End With _transacao.Commit() _retvalor =True Catch ex As Exception _transacao.Rollback()Throw ex Finally liberaTodosObjetos()End Try Return _retvalor End Function 
 | 
| ExcluiEstudante() | 
| Public 
    Function GetEstudante(ByVal 
    EstudanteID As
    String) 
    As 
    DataRow _dlinha =Nothing Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="SELECT Estudantes.EstudanteID, Estudantes.estudanteNome, Estudantes.estudanteEndereco, " & _ "Estudantes.estudanteTelefone, Estudantes.estudanteIdade, Estudantes.cursoID, " & _ "Cursos.cursoPreco, Estudantes.estudantePago " & _ "FROM Cursos INNER JOIN Estudantes ON Cursos.cursoID = Estudantes.cursoID " & _ "WHERE Estudantes.EstudanteID =@EstudanteID" 
 .Parameters.Add("@EstudanteID", OleDbType.VarChar, 5).Value = EstudanteID.Trim() End With _oledap =New OleDb.OleDbDataAdapter(_olecom) _dset =New DataSet() _oledap.Fill(_dset)If _dset.Tables(0).Rows.Count > 0 Then _dlinha = _dset.Tables(0).Rows(0)Else _dlinha =Nothing End If _olecom.Parameters.Clear()Catch ex As Exception _dlinha =Nothing Throw ex Finally liberaTodosObjetos()End Try Return _dlinha End Function 
 | 
| GetEstudante() | 
| Public 
    Function 
    TodosEstudantes() As 
    DataSet _dset =Nothing Try _olecon =New OleDb.OleDbConnection(_conStr) _olecon.Open() _olecom =New OleDb.OleDbCommand() With _olecom .Connection = _olecon .CommandType = CommandType.Text .CommandText ="SELECT EstudanteID,estudanteNome,estudanteTelefone " & _ "FROM Estudantes ORDER BY estudanteNome" End With _oledap =New OleDb.OleDbDataAdapter(_olecom) _dset =New DataSet() _oledap.Fill(_dset)Catch ex As Exception _dset =Nothing Throw ex Finally liberaTodosObjetos()End Try Return _dset End Function 
 | 
| TodosEstudantes() | 
Note que as classes DALCurso e DALEstudante possuem métodos que conhecem apenas como acessar e retornar os dados e nelas não há lógica de negócio.
Temos também um método de suporte que libera os objetos usados, liberaTodosObjetos() cujo código é:
| Private 
    Sub 
    liberaTodosObjetos() If _transacao IsNot Nothing Then _transacao.Dispose() _transacao =Nothing End If If _oledap IsNot Nothing Then _oledap.Dispose() _oledap =Nothing End If If _olecom IsNot Nothing Then _olecom.Cancel() _olecom.Dispose() _olecom =Nothing End If If _olecon IsNot Nothing Then If _olecon.State = ConnectionState.Open Then _olecon.Close() End If _olecon.Dispose() _olecon =Nothing End If End Sub | 
Com isso encerramos as definições das classes da camada de acesso dados DataAccesLayer. Iremos definir agora a camada de interface representada pelo projeto EstudanteMatricula criado na primeira parte deste artigo.
Neste exemplo nossa camada de apresentação será uma aplicação Windows Forms mas poderíamos ter usando um projeto web ou mobile. Repetindo a definição para cada uma das camadas temos:
Veja a continuação deste artigo em : VB .NET - Criando uma aplicação em camadas (de novo) IV
| Veja os 
    Destaques e novidades do SUPER DVD Visual Basic 
(sempre atualizado) : clique e confira ! Quer migrar para o VB .NET ? 
 Quer aprender C# ?? 
 Quer aprender os conceitos da Programação Orientada a objetos ? Quer aprender o gerar relatórios com o ReportViewer no VS 2013 ? | 
             Gostou ?
  Compartilhe no Facebook
Compartilhe no Facebook
  
 Compartilhe no Twitter
 
Compartilhe no Twitter 
Referências:
José Carlos Macoratti