This tutorial will show you how to create your own class in ASP.NET and VB.NET
In this tutorial, we will look at how to create a Custom Class that will represent an object. When working with databases in Web Applications, it is often useful to have an object representing that data, rather than using the built-in types such as a DataTable. By creating your own class, you can gain access to the Properties instead of referencing row and column numbers. An example would be if you're working with data from a database that consisted of a group of people. The columns could be name, age, and telephone. If you used a datatable to retrieve and interact with this data, it could get messy very quickly. But if you created a class to represent the data, then you would be able to programmatically reference the properties (name, age, and telephone) directly.
In this example, we will use a SQL Database and create a class to represent the data. We will keep it simple and use the following columns in the table: ID, Name, Age, Telephone.
Let's begin by starting a new Web Application in Visual Studio. Right-click on the App_Data folder in Solution Explorer, and choose Add New Item.. SQL Server Database. Once it opens up in the Server Explorer window, right-click the Tables folder and choose to Add New Table. Add the following columns and data types:
ID bigint
Name varchar(50)
Age smallint
Telephone varchar(20)
We also want to make the ID column the Primary Key, and in the properties, set Identity Specification to Yes. Then Save the table, and add the Connection String to the Web.config:
| <connectionStrings> <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> |
If you're unsure about the Connection String, see ConnectionStrings.com
Now let us begin writing our Class. If you don't have an App_Code folder in your Solution Explorer, right-click your Project and choose to Add ASP.NET Folder > App_Code. Then right-click the App_Code folder and choose to Add New Item.. Class. Give it a name. You should then be presented with something like this:
| Imports Microsoft.VisualBasic Public Class Person End Class |
Try Server Intellect for Windows Server Hosting. Quality and Quantity!
The first thing we should do is add the Properties. We want the Properties to reflect the columns of the table in the database. We will need to set the data types as well:
| #Region "properties" Public Property ID() As Int32 Get End PropertyReturn _ID End GetSet(ByVal value As Int32) _ID = value End SetPrivate _ID As Int32 = 0 Public Property Name() As String Get End PropertyReturn _Name End GetSet(ByVal value As String) _Name = value End SetPrivate _Name As String = "" Public Property Age() As Integer Get End PropertyReturn _Age End GetSet(ByVal value As Integer) _Age = value End SetPrivate _Age As Integer = 0 Public Property Telephone() As String Get End PropertyReturn _Telephone End GetSet(ByVal value As String) _Telephone = value End SetPrivate _Telephone As String = "" #End Region |
Notice that each Property is public so that we can access it from outside the class. We also set the default values for each Property.
Now that we've got all of our Properties, we can move onto the constructors and methods. Let's start with the base method - SetObjectData. We will use this method to build our object from a SqlDataReader, but before we do, we need to add the following reference:
| Imports System.Data.SqlClient |
We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!
The reference to this class will allow us to interact with our SQL Server Database. Our SetObjectData method will take the parameter of a SqlDataReader and then use that to fill the properties we have just created:
| Private Sub SetObjectData(ByVal theObjReader As SqlDataReader) Try End Try End Sub Me._ID = Convert.ToInt32(theObjReader("ID")) CatchMe._Name = theObjReader("Name").ToString() Me._Age = Convert.ToInt16(theObjReader("Age")) Me._Telephone = theObjReader("Telephone").ToString() |
We make this method private because we don't want it to be accessible beyond the class; only class methods should call it. From within the method, when 'this.' is typed, you should be presented with the intellisense dropdown, which holds the properties we added earlier. We will set these properties using the passed SqlDataReader.
Now we can create a constructor that will use this method. By doing this, we protect the method from external usage, but allow it to still be used with the constructor. This will allow us to create a new object just by passing a valid SqlDataReader. By valid, we mean that it must still hold the correct properties in order for the object to be built and returned. The constructor will look something like this:
| Public Sub New(ByVal theObjReader As SqlDataReader) SetObjectData(theObjReader) End Sub |
Another constructor we can create that is always useful is one that will retrieve an object based upon the ID passed to it. This allows us to populate an object with the record we want, just by specifying its ID. For this method, we will need to reference the following namespaces:
| Imports System.Data Imports System.Web.Configuration |
The method will look something like this:
| Public Sub New(ByVal thePersonID As Int32) Dim connection As New SqlConnection(WebConfigurationManager.ConnectionStrings("ConnectionString").ToString()) Try End Sub Dim cmd As SqlCommand Catch cmd = New SqlCommand("sp_GetPersonByID", connection) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@ID", thePersonID) connection.Open() Dim objReader As SqlDataReader = cmd.ExecuteReader() Do While objReader.Read() SetObjectData(objReader) LoopobjReader.Close() connection.Close() connection.Close() End Try |
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
We are taking a parameter of type Int32 and then simply executing a Stored Procedure that will compare this ID and return the match. With that match we use our SetObjectData method to build the Person object. To create a Stored Procedure, open up the Server Explorer window and right click on the Stored Procedures folder, choose Add New. Our Stored Procedure looks like this:
| CREATE PROCEDURE dbo.sp_GetPersonByID @ID bigint AS SELECT * FROM Table1 WHERE ID=@ID |
Our class is pretty much done for the most part, but many public methods can be added for use with the custom object. For example, we can create a public method that can be called from any ASPX page that will insert new data into the database, using the object. To do this, we will create a public method that will return an integer, which will be the ID of the new record just inserted. If insert fails, the method will return zero. Because we are passing an object to the method, we will set the parameters like so:
| Public Shared Function InsertPerson(ByVal thePerson As Person) As Int32 Dim newPersonID As Int32 = 0 End Function Dim connection As New SqlConnection(WebConfigurationManager.ConnectionStrings("ConnectionString").ToString()) Try Dim cmd As New SqlCommand("sp_InsertPerson", connection) Catch cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Name", thePerson.Name) cmd.Parameters.AddWithValue("@Age", thePerson.Age) cmd.Parameters.AddWithValue("@Telephone", thePerson.Telephone) connection.Open() newPersonID = Convert.ToInt32(cmd.ExecuteScalar()) connection.Close() connection.Close() End TryReturn newPersonID |
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
We use a similar structure to the constructor with the Int32 parameter, but we do not need to use the SetObjectData method on this one, as we are not returning the object. We are taking the object as a parameter, adding that data to the database, then returning its ID. All the object's public properties can be accessed using the instance name and then a period(.), just like other objects.
Our Insert Stored Procedure looks like this:
| CREATE PROCEDURE dbo.sp_InsertPerson @Name varchar(50), AS@Age smallint, @Telephone varchar(20) INSERT INTO Table1 ([Name], Age, Telephone) VALUES (@Name, @Age, @Telephone) SELECT SCOPE_IDENTITY() |
No comments:
Post a Comment