ASP.NET - Creating a Business Object
Creating business object is a vital part in order to split up the database related
operations from the Web form.
This makes it very easy for a designer to focus on
the design and calling business object only. Whereas an expert database coder can
prepare the business object in order to store and retrieve in a very proper manner.
Also, in future if it is needed to run the business object in a separate server,
that way also it will be helpful.
We have already made a standard baseservices which encapsulates all the necessary
functionalities. Writing business object is just to implement the important functions
which we are going to discuss shortly.
We need to use the following procedure:
- Create a class module under App_Code folder. (Tip: You can create and organize any
number of sub folders under App_Code, and store the business object in any of those
folders.) Now add the Inherits BaseServices to the class name, which will automatically
produce the following output.
Imports Microsoft.VisualBasic
Imports System.Data
Public Class clsUsers
Inherits BaseServices
Public Overrides Function DeleteEntry() As Boolean
End Function
Public Overrides Function GetEntry() As Boolean
End Function
Public Overrides Function SaveEntry(ByRef dr As _
System.Data.DataRow) As Boolean
End Function
End Class
- Our work is simply to implement the three functions. If you need some supporting
functions in this class you can do that. Here is the final version of the Business
Object. Each function is a self explanatory.
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Data
Public Class clsUsers
Inherits BaseServices
Dim mRoles As String
Dim mLastError As String
Public Property Roles() As String
Get
Return mRoles
End Get
Set(ByVal value As String)
mRoles = value
End Set
End Property
Public Property LastError() As String
Get
Return mLastError
End Get
Set(ByVal value As String)
mLastError = value
End Set
End Property
Public Function IsValidUser(ByVal UserName As String, _
ByVal Password As String) As Boolean
Try
Dim Sql As String
Sql = "Select * From Users Where " & _
"EmailId=@UserName And Password=@PassWord"
Dim cmd As New SqlCommand
cmd.CommandText = Sql
cmd.Parameters.Add("@UserName", _
Data.SqlDbType.VarChar).Value = UserName
cmd.Parameters.Add("@Password", _
Data.SqlDbType.VarChar).Value = _
FormsAuthentication.HashPasswordForStoringInConfigFile(_ Password, "md5")
Dim dt As DataTable
dt = GetDataSet(cmd).Tables(0)
If dt.Rows.Count > 0 Then
Roles = GetString(dt.Rows(0)("Roles"))
Dim dr As DataRow
dr = dt.Rows(0)
dr.BeginEdit()
dr("RecentActivityOn") = GetSQLServerDate()
dr.EndEdit()
UpdateDataTable(dt, "Users")
IsValidUser = True
Else
IsValidUser = False
LastError = "Invalid UserName/Password!"
End If
dt.Dispose()
dt = Nothing
Catch ex As Exception
Throw ex
End Try
End Function
Public Overrides Function DeleteEntry() As Boolean
Try
' Please make sure if this record ' can be deleted, confirmly.
Dim Sql As String
Sql = "Delete From Users Where UserId=" & KeyValue
DeleteEntry = (ExecuteNonQuery(Sql) > 0)
Catch ex As Exception
Throw ex
End Try
End Function
Public Overrides Function GetEntry() As Boolean
Try
Dim Sql As String
Sql = "Select * From Users Where UserId=" & KeyValue
DataSet.Tables.Clear()
DataSet.Tables.Add(GetDataTable(Sql, "Users"))
Catch ex As Exception
Throw ex
End Try
End Function
Public Overrides Function SaveEntry(ByRef dr As DataRow) As Boolean
Try
' Validate the Entry.
ClearErrors()
CheckRequiredField(GetString(dr("EmailId")), _
"Email Id", 50)
CheckForDuplication("Users", "EmailId", "UserId", _
GetString(dr("EmailId")), KeyValue, "Email Id")
CheckRequiredField(GetString(dr("Roles")), "Roles", 256)
If IsValid Then
SaveRow(dr)
UpdateDataTable(DataSet.Tables(0).GetChanges, "Users")
Else
Return False
End If
Return True
Catch ex As Exception
Throw ex
End Try
End Function
End Class
How to call the Business object Functions from the Web Form?
Here is the complete code of Users web form. I've highlighted various places in which
we are calling the business object function. I think there won't be any
difficulty in understanding these codings. I advise you to concentrate only on the highlighted
area in order to understand the simplicity of calling the business objects.
Imports System.Data
Partial Class Admin_Users
Inherits System.Web.UI.Page
Dim mLastListRecordsCount As Long
Private Sub LoadData()
Try
Dim Sql As String
Dim dt As DataTable
Sql = "Select * From Users "
If hfCurrentListingMode.Value = "ListAll" Then
' No condition is needed now!
Else
' Put the Search String Condition Here.
Sql &= " Where EmailId Like '" & _
hfCurrentListingMode.Value & "%' "
End If
Dim OrderBy As String = " Order By " & _
hfLastSortExpression.Value & " " & hfLastSortDirection.Value
Sql &= " " & OrderBy
dt = GetDataTable(Sql)
mLastListRecordsCount = dt.Rows.Count
If mLastListRecordsCount > 0 Then
gvList.DataSource = dt
gvList.DataBind()
End If
' Bind the Roles.
Sql = "Select * From Roles Order By RoleId"
dt = GetDataTable(Sql)
chkRoles.DataSource = dt
chkRoles.DataBind()
Catch ex As Exception
ShowError(ex)
End Try
End Sub
Protected Sub gvList_SelectedIndexChanged(ByVal _
sender As Object, ByVal e As System.EventArgs)
End Sub
Protected Sub gvList_PageIndexChanging(ByVal _
sender As Object, ByVal e As _
System.Web.UI.WebControls.GridViewPageEventArgs) _
Handles gvList.PageIndexChanging
gvList.PageIndex = e.NewPageIndex
End Sub
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadData()
End If
End Sub
Protected Sub gvList_Sorting(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) _
Handles gvList.Sorting
If e.SortExpression = hfLastSortExpression.Value Then
hfLastSortDirection.Value = _
IIf(hfLastSortDirection.Value = "ASC", "DESC", "ASC")
Else
hfLastSortExpression.Value = e.SortExpression
hfLastSortDirection.Value = "ASC"
End If
LoadData()
End Sub
Protected Sub btnNew_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Try
MultiView1.ActiveViewIndex = 1
txtEmailId.Text = ""
chkLocked.Checked = False
hfKeyValue.Value = 0
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub btnList_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
MultiView1.ActiveViewIndex = 0
End Sub
Private Function GetRoles() As String
Try
Dim li As ListItem
Dim out As String = ""
For Each li In chkRoles.Items
If li.Selected Then
If out.Length > 0 Then out &= ","
out &= li.Text
End If
Next
Return out
Catch ex As Exception
Throw ex
End Try
End Function
Protected Sub btnSave_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim o As New clsUsers Try
lblErrorText.Text = ""
o.KeyValue = hfKeyValue.Value o.GetEntry() Dim
dr As DataRow = o.DataRow dr.BeginEdit()
dr("EmailId") = txtEmailId.Text
If o.KeyValue = 0 Then
dr("Password") = GetRandomPassword()
End If
dr("DateOfRegistration") = GetSQLServerDate()
dr("Roles") = GetRoles()
dr("Locked") = chkLocked.Checked
dr.EndEdit()
If Not o.SaveEntry(dr) Then
lblErrorText.Text = o.ValidationError
Exit Sub
End If
gvList.PageIndex = 0
LoadData()
MultiView1.ActiveViewIndex = 0
Catch ex As Exception
ShowError(ex)
Finally
o = Nothing End Try
End Sub
Private Sub SetRoles(ByVal Roles As String)
Try
Dim R() As String = Roles.Split(",")
Dim S As String
For Each S In R
Dim I As Integer
Dim li As ListItem
For I = 0 To chkRoles.Items.Count - 1
li = chkRoles.Items(I)
If li.Text = S Then
li.Selected = True
Exit For
End If
Next
Next
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub lbEdit_Command(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.CommandEventArgs)
Dim o As New clsUsers Try
hfKeyValue.Value = e.CommandArgument
o.KeyValue = hfKeyValue.Value o.GetEntry() Dim
dr As DataRow = o.DataRow txtEmailId.Text = GetString(dr("EmailId"))
chkLocked.Checked = GetBoolean(dr("Locked"))
SetRoles(GetString(dr("Roles")))
LoadData()
MultiView1.ActiveViewIndex = 1
Catch ex As Exception
ShowError(ex)
Finally
o = Nothing End Try
End Sub
Protected Sub lbDelete_Command(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.CommandEventArgs)
Dim o As New clsUsers Try
hfKeyValue.Value = e.CommandArgument
o.KeyValue = hfKeyValue.Value
o.DeleteEntry()
LoadData()
Catch ex As Exception
ShowError(ex)
Finally
o = Nothing End Try
End Sub
Protected Sub btnGo_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Try
Dim txt As TextBox
txt = CType(gvList.HeaderRow.FindControl("txtSearch"), TextBox)
hfCurrentListingMode.Value = txt.Text
LoadData()
If mLastListRecordsCount > 0 Then
txt.BackColor = Drawing.Color.White
Else
txt.BackColor = Drawing.Color.Red
End If
Catch ex As Exception
ShowError(ex)
End Try
End Sub
End Class
|
|