WHAT'S NEW?
Loading...

Handles possible restriction for the system security

Programming Problem:

Write a program that provides security level where the users can login to control the flow of a program and handles possible restriction. The system has 2 user level, USER and ADMIN. Now, design a program that both users can access the system but there’s a limitation. For example, the USER only allow to login and view the records but they cannot click add, delete, and update button. And only ADMIN has an authority to access the entire system if they want to grant privileges to permit the USER to add, delete, or update.

For instance, let’s assume there are textboxes for First name, Last name, and middle name to be fill up by the users. For the security of a program, any anomalies happens in the system will displays error message that does not automatically point out the errors in the source code, instead it will display during run time. Furthermore, you may also use buttons (Enabled – True/False or Visible – True/False) to determine if it is accessible by the users to handles transaction based on the security being used in the system. Once the users was logged in, it will display which visible commands are accessible to be process.

In addition, the system also determine how many attempt you try to access the system, to address the security access, the users only allow to access 3 times otherwise more than that the system will automatically closed. Use only 2 Forms, Form for Login and Form for Viewing the record which includes user’s buttons and textboxes visibility for security access. It’s up to you how to manage the design and codes of your program as long the requirements meets what the given problem is, and at the same time the logic of your program it should be flexible. It includes also Algorithm/Flowchart to determine the flow of your program. Good luck!

Visual Basic.Net Database Programming with ADO.NET

To introduce the connection string to communicate between your application and the database (Microsoft Access, MySQL, MSSQL, Oracle), you need to know more details what is ADO.NET and its functions to understand well on its uses. Now, it’s time to work with Visual Basic.Net to build our simple application to communicate with the database that enables performs queries to retrieve, insert, update, and delete data from database. In this tutorial, we’ll stick to work with Microsoft Access Database but if you want to work with a large amount data to store in your database it’s better to use SQL Server, Oracle, MySQL, or other DBMS that supports large amount of storage because Database Access has a limited features over the others. Let’s work with OLE DB connection object, OLE stands for Object Linking and Embedding, and it’s basically a lot of objects (COM objects) bundled together that allow you to connect to data sources in general. There are a number of different OLE DB objects (called data providers), but the one we'll use is called "Jet".

Imports System.Data.OleDb namespace needs to be import first just above the Public Class Form1 to use all of this components such as Connection, Command, DataAdapter, and DataReader.

We need to pass two things to our new Connection Object: the technology we want to use to do the connecting to our database; and where the database is. (If your database was password and user name protected, you would add these two parameters as well. Ours isn't, so we only need the two.)
The technology is called the Provider; and you use Data Source to specify where your database is. So, this is the code:

connString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = D:\\OledbCon\DbInfo.mdb"

The first part specifies which provider technology we want to use to do the connecting (JET). The second part, typed after a semi-colon, points to where the database is. In the above code, the database is on the D Drive, in the root folder OledbCon. The name of the Access file we want to connect to is called DbInfo.mdb. Remember "Data Source" is two words, and not one. Note, make sure your file extension is .mdb not .accdb because it doesn’t work for it.

connString is a String variable that holds your Connection Object

conn.ConnectionString = connString
conn.Open()

ConnectionString is a property of the con variable. The con variable holds our Connection Object. We're passing the Connection String the name of a data Provider, and a path to the database.

Open method of the Connection Object, once open the connection has to be closed again, just use Close method conn.Close()

Your code looks like the following:

#Region "Method name for connection string"
    Public Sub myConnectionString()
        connString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = D:\\OledbCon\DbInfo.mdb"
        conn.ConnectionString = connString
        conn.Open()
    End Sub
#End Region

We’ll use Region to specify the name of my method myConnectionString, so that it easy to connect every time to open my database to performs queries. However, you can do a lot more of this approach, you may also use module or class to enable access globally. (The purpose is you don’t need to type again every time to connect from your database.)

    Dim connString As String
    Dim conn As New OleDbConnection
    Dim da As OleDbDataAdapter
    Dim cmd As New OleDbCommand
    Dim ds As New DataSet
    Dim sql As String

The above variables are needed to the whole of this program. Declare this variable as public under Public Class Form1 to enabled access other controls within the class.

To ensure you’re successfully connected to your database, in your button connect, the code looks like the following.

Call myConnectionString()
MessageBox.Show("Successfully connected to the database", "Connected", MessageBoxButtons.OK, MessageBoxIcon.Information)

conn.Close()
MessageBox.Show("Database closed", "Closed", MessageBoxButtons.OK, MessageBoxIcon.Information)

To connect from your database, you need to Call myConnectionString method followed by message box result if it is connected successfully or not.

Understanding what is SQL Statement

SQL (pronounced es-kyoo-el) is not an acronym. It’s a common misconception that SQL stands for structured query language; it stands for S–Q–L and nothing else. Why? Because ANSI says, the official name is Database Language SQL, isn’t structured (because it can’t be broken down into blocks or procedures), isn’t for only queries (because it has more than just the SELECT statement), and isn’t a language (because it’s not Turing complete, which you’ll study should you take Theory of Computation.) SQL it is not case sensitive. reference ~Third Edition Chris Fehily~

SQL statement are divided into Three Categories

Data manipulation language (DML) statements retrieve, reckon, insert, edit, and delete data stored in a database.

Data definition language (DDL) statements create, modify, and destroy database objects such as tables, indexes, and views.

Data control language (DCL) statements authorize certain users to view, change, or delete data and database objects.

For more information about SQL queries and its uses, I’ve suggest to read more in details. Unfortunately, I only stated important keyword what is SQL stands for in this article. However, we need only used SELECT, INSERT, DELETE, and UPDATE statement that meet our needs for our application in Visual Basic.Net. SQL queries and other components both were apply to communicate between your application and the database. To do so:

SELECT * FROM Table_Name

Asterisk (*) means all fields or columns are displays in your query result using your SELECT Statement. If you are going to specify the name of each columns, instead of asterisk (*), write the column name you want to display on your result separated by a comma.

SELECT col1, col2, coln FROM Table_Name

FROM refers from which table name in your database to display the result, and followed by the name of your Table.

Here’s your code looks like:

Private Sub retrieveData()
        'I've created this method so that you don't need to type
        'this query every time you retrieve your data from database,
        'instead call it if needed.
        Call myConnectionString()
        sql = "SELECT * FROM tblInfo"
        da = New OleDbDataAdapter(sql, conn)

        da.Fill(ds, "DbInfo")
        DataGridView1.DataSource = ds.Tables("DbInfo")
        conn.Close()
End Sub

tblInfo is the name of the Table and DbInfo is the name of your database where your table is already belong.

sql is a variable name that holds your query statement, da stands for DataAdapter also a variable and conn is your connection variable for an instance object to communicate between your database, and the DataAdapter can Fill a DataSet (ds) with records from a Table. Lastly, it will close the connection between the application and your database.

To display the result, you need DataGridView to fill with records from your table. So, place the code in your Form Load event so that once the program is run it will automatically retrieve the data from your database.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'call method name retrieveData to fill the DataGridView
        Call retrieveData()
End Sub

We already did to retrieve data from database. Now, it’s time to add/insert new entry to your database. Your code looks like the following:

Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
        Call myConnectionString() 'Enabled communicate to database

        sql = "INSERT INTO tblInfo(Firstname,Lastname,Middlename) VALUES ('" & txtLastname.Text & _
            "','" & txtFirstname.Text & "','" & cbMiddlename.Text & "')"

        cmd = New OleDbCommand(sql, conn)
        cmd.ExecuteNonQuery()

        MessageBox.Show("Successfully Added to your Database", "New Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information)
        conn.Close()
        Me.Close()
End Sub

The above code runs smoothly to insert record directly to your database. You used INSERT INTO statement to execute insert command.

INSERT INTO Table_Name (col1, col2, coln…) VALUES (value1, value2, valuen…)

ExecuteNotQuery allows you to execute a SQL statement or command object with CommandText property having a SQL statement without using a DataSet.

Here are other options how to INSERT record.

#Region "CommandText Insert Command"
    'You may also used this approach to insert record.
    'If you want to try to run this code, call this procedure
    'and comment the code you already made.
    Private Sub CmdTextInsert()
        cmd = New OleDbCommand("tblInfo", conn)
        cmd.CommandText = "INSERT INTO tblInfo(Firstname,Lastname,Middlename) VALUES ('" & txtlastname.Text & _
            "','" & txtfirstname.Text & "','" & txtmiddlename.Text & "')"
        cmd.ExecuteNonQuery()
        MsgBox("Successfully Added to your Database", "New Record(s) Added", MsgBoxStyle.Information)
        conn.Close()
    End Sub
#End Region

#Region "Other Insert Command"
    Private Sub OtherInsert()
        sql = "INSERT INTO tblInfo(Firstname,Lastname,Middlename) VALUES ('" & txtlastname.Text & _
            "','" & txtfirstname.Text & "','" & txtmiddlename.Text & "')"
        Dim da As New OleDbDataAdapter(sql, conn)
        da.Fill(ds)
    End Sub
#End Region

You can choose which INSERT command you’re really compatible to use.

Next, need to modify your record if in case there’s record inserted mistaken? To do so, to modify the entry in DataGridView, the users can double click which entry in row they are going to modify. I used this code in my previous tutorial Barcode product entry system used by a cashier, so this click event include DOUBLE click in order to make changes the entry.

Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick
        Dim x As Integer
        If Not DataGridView1.CurrentRow.IsNewRow Then
            x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
            txtFirstname.Text = DataGridView1.Rows(x).Cells(1).Value.ToString()
            txtLastname.Text = DataGridView1.Rows(x).Cells(2).Value.ToString()
            cbMiddlename.Text = DataGridView1.Rows(x).Cells(3).Value.ToString()
        End If
End Sub

Once the user double click the cell, the current data selected in DataGridView displays in TextBox. That’s the time you can make changes the entry. Here’s the code:

Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdate.Click
        Call myConnectionString()
        Dim x As Integer
        Dim id As Integer
        If Not DataGridView1.CurrentRow.IsNewRow Then
            x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
            id = DataGridView1.Rows(x).Cells(0).Value.ToString()

            sql = "UPDATE tblInfo SET Firstname = '" & txtFirstname.Text & "',Lastname = '" &
                txtLastname.Text & "',Middlename = '" & cbMiddlename.Text & "' WHERE ID = " & id & ""
            Dim da As New OleDbDataAdapter(sql, conn)
            da.Fill(ds)
            MessageBox.Show("Data successfully updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information)
            conn.Close()
            Me.Close()
        End If
End Sub

In update, you used UPDATE statement to enable modification of entry.

UPDATE Table_Name SET col1, col2, colnWHERE col = col

UPDATE, SET, and WHERE Keywords in SQL that has a special meaning. WHERE clause is every important to emphasize which column match unique ID so that once it update, only one entry in row will affected because once you didn’t specify the WHERE clause properly there’s some tendency all records in table will change in one updates. SET simply set which column(s) in table to modify.

Lastly, it enables to DELETE if you don’t satisfy what entry was inserted. Here’s the code:

Private Sub btndelete_Click(sender As System.Object, e As System.EventArgs) Handles btndelete.Click
        Call myConnectionString() 'Connect to database first

        Dim x As Integer
        Dim id As Integer
        Dim firstname As String
        Dim lastname As String

        If Not DataGridView1.CurrentRow.IsNewRow Then
            x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
            id = DataGridView1.Rows(x).Cells(0).Value.ToString()
            firstname = DataGridView1.Rows(x).Cells(1).Value.ToString()
            lastname = DataGridView1.Rows(x).Cells(2).Value.ToString()

            If MessageBox.Show("Are you sure you want to delete " & firstname & " " & lastname & " entry", "Delete Entry" _
                               , MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                sql = "DELETE FROM tblInfo WHERE ID = " & id
                Dim da As New OleDbDataAdapter(sql, conn)
                da.Fill(ds)
                MessageBox.Show("Record successfully deleted", "Confirmed", MessageBoxButtons.OK)
                conn.Close()
                Me.Close()
            Else
                MessageBox.Show("Cancelled Operation", "Cancelled", MessageBoxButtons.OK)
                conn.Close()
            End If
        End If
End Sub

To DELETE entry, also the same as UPDATE statement because you’re specifying a WHERE clause statement which ID to be deleted. Why ID? Because that’s the only fields provide the uniqueness of entry in a table. If you are going to put unique ID in your table it must be a PRIMARY Key and Data Type AutoNumber for Access, so it will automatically generated every time new entry is added, and ID is your identity to identify which entry to be update or delete in your table.

To download the complete program, here is the link. VB.NET Database Programming includes SELECT, INSERT, UPDATE, and DELETE statement. If you want to save your files online and share it to your friends, sign up for free.

What is ADO.NET database programming in VB.NET?

Visual Basic.Net is a latest version of Microsoft that run dependent on the .NET Framework. All supported languages in .NET Framework share a common library. In the .NET Framework, the database API is ADO.NET that supports variety of Data Providers. These Providers composed of different kind of databases platforms (MSSQL, MSSQL, DB2, ORACLE, and MSACCESS) that can be use in any Microsoft related languages such as VB.NET, C#, C++, F#, and J# that enable to store data and performs SQL queries from database. ADO.NET stands for Active Data Objects .NET from its predecessor Data Access Object (DAO) , perhaps misnamed because it’s not an ActiveX/Component Object Model (COM) technology, the goal is to write high – performance, reliable, and scalable database for client - server applications both Desktop  and on the Web.

ADO.NET Framework can access any kind of data source, it’s a set of Object – oriented classes that provides a rich set of data components based on the ADO model and have some objects in common. To understand why ADO.NET was designed is because some developers not easy to program and some of them don’t have good enough performance. For instance, Open Database Connectivity (ODBC) Application Programming Interface (API) is a set of C functions. There is no object – oriented supports, the reason in developing applications using ODBC is because time – consuming process for developers and problematic in its relational natures, and limited support of relational databases. That’s why Microsoft introduced ADO high – level programming model that meets today’s programming and developer’s need (this was before ADO.NET), including disconnected data, tight integration with XML, and a common model work with all kinds of data sources.

The ADO.NET provides a Single Object – Oriented API set of classes. There are different data providers to work with different data sources, but the programming model for all these data providers work in the same way. Fortunately, if you know how to work with one data provider, you know already how to work easily with others. It’s just a matter of changing class names and connection strings. However, you can use more than one data provider to access a single data source. For example, you can use ODBC, MSSQL, or OleDb data providers to access Microsoft Access database because ADO.NET treats all databases in the same manner by using different data providers. The only difference is that you use different classes and connection strings to communicate databases, but it takes care for you under the hood. For instance, if you use the OleDb data provider (OLE stands for Object Linking and Embedding) to work with Access other OLE DB data sources, you use OleDbConnection, OleDbAdapter, and OleDbCommand objects. If you work with MSSQL Server, you use the Sql data provider’s classes SqlConnection, SqlDataAdapter, and SqlCommand. If you work with MySQL, you use MySqlConnection, MySqlDataAdapter, and MySqlCommand. All this commands work exactly in the same approach as the OleDb data provider’s classes. Classes are easy to use and to understand because of their Object – Oriented nature. One good thing to remember, if you know how to use these classes in Visual Basic.Net, you’ll have no problem to migrate using C#.

Understanding ADO.NET Components 
ado.net architecture

There are three (3) components to categorized ADO.NET.

Disconnected Component – A builds the basic ADO.NET architecture, these components (or class) with or without data providers.

Common or Shared – Are based on classes for data providers and shared by all data providers.

.NET Data Provider – Are specifically designed to work with different kinds of data sources. This composed of four sets components such as Connection, Command, DataAdapter, and DataReader.

Connection – The first component that talks to a data source and works as a connection reference in Command and DataAdapter objects.
Command – An object executes a SQL query and stored procedures to Select, Insert, Delete, and Update data of a data source via at DataAdapter.
DataAdapter – is a bridge between a DataSet and the connection to the data source. It uses Command objects to execute SQL queries and stored procedures.
DataReader – A method of a command object that executes the query and returns data in a DataReader object.

A DataSet objects falls in disconnected components series consists of a collection of tables, rows, columns, and relationships. It contains a collection of DataTables and the DataTable contain a collection of DataRows, DataRelations, and DataColumns. In addition, maps to a table in the database. Each DataRow can be accessed via an index, DataRelation can be accessed by its integrity, and DataColumn can be accessed by either an index or the column name. Moreover, DataSet act as a local copy of your database that has one – to – many relationships with DataTable. That means, it have one or more than one DataTable objects. Identically, a DataTable can have one or more than one DataRelation, DataRow, and DataColumn Objects.

This is the complete program in Visual Basic.Net Database programming with ADO.NET includes SELECT, INSERT, UPDATE, and DELETE statement.

Barcode product entry system used by a cashier

Almost many establishments, shopping Malls, or even a small store need to have product entry system to make it easy for customers to pay their item in the cashier counter. With the help of this system, transactions made easy especially for the benefits of the business because they don’t only compute or analyze manually to determine their revenue and other important matter in every transaction, instead they look only in the system for further information how the system being track each transactions made.

In this tutorial, it only tackles for creating simple barcode entry system used by a cashier using Visual Basic.Net. Obviously, through Visual Basic we can create rapid application in a minute. Unfortunately, will only use to enter each barcode of every item because we don’t have a barcode reader or scanner, just only a simple system to figure out how it will looks our system like as we seen in various malls when we pay our items in cashier counter. For further information, I’ll try to work this simple tutorial to support database for the next tutorial so that every transactions made for each customers and business itself will automatically saves on database and easy to retrieve for analysis.

The concept of this Aka Product Entry System allows the users input item barcode and display the result in DataGridView with the corresponding item description, quantity, price of an item, and total that match to the barcode entered by the user. If the barcode entered does not match to the given barcode, the system display invalid barcode item doesn’t exist. In addition, shortcut keys allow the users quick access all the commands necessary for every transaction made. It provides security account if the user’s mistakes input the number of quantity of an item and only authorized person can modify or delete the items, also includes the additional 12 percent vat. Unfortunately, doesn’t allow printing, not supported by database, only saves on memory and once the program close the data will automatically lost. Furthermore, you can contribute to improve this application if you wish. Hope this is very helpful.

The Barcode Product Entry System looks like the following:
Barcode entry system
List of Forms and Controls needed to build this application are:

We need to add 4 Forms and name the property name frmProductEntry, frmTotal, frmChange, frmAccount.

frmProductEntry – The main entry of all products to be process, its shows items entry and commands to quick access for users. In this form, in your properties settings, in Text, change the text name to PRODUCT ENTRY: Version 1.0, StartPosition at CenterScreen, FormBorderStyle to FixedSingle, and ControlBox to False. Here are the lists of controls needed in this form:

MenuStrip – includes the following menus, Exit, Functions composed of shortcut keys such as qty F2,  delete F1, edit F2, enter amount F5, print report F4, enter item barcode F6, and select items F7, Settings, About, and Help. Unfortunately, there’s some menus doesn’t functions yet, and images are optional. 
    
DataGridView – to add column name, click datagridview and in small arrow above click it and edit columns… Now, click add button to enable to add column name, by default name Column1 change the name to itemDescription make sure does not includes spacing, Type let it default DataGridViewTextBoxColumn, and Header Text change the name Column1 to Item Description, it allows you used spacing, unlike Name, in column properties only change the Width to 530 . Then followed by Quantity, Price, and Total, all width is 80 and then clicks OK. Again, click the small arrow above in your datagridview and unchecked Enable Adding, Enable Editing, and Enable Deleting.
                
Textboxadd 3 textboxes; name the first textbox to txtbarcode for item barcode, second textbox txtAmount for amount, and the third textbox txtquantity, let 1 the default value.
                
Button – we have various buttons in this form but only have 2 buttons where our code put later, button for accepting items barcode and button for accepting amount. Other buttons show only a shortcut keys to enable the users to quick access all necessary commands to be process. F1 – F7 are only buttons for showing the shortcut keys, codes are place in Function menu not in a button.
                
Label – we have different labels that label our textboxes or buttons, but there’s few labels show the result like the Total, Number of items, Total vat, and Change. The Name property of each labels are follows. Total (lblTotal), Number of Items (lblnumberofitems), Total vat (lbltotalvat), and Change (lblchange)

frmTotal - Display the total amount of an items. In the properties settings, switch the FormBorderStyle to None and StartPosition to CenterScreen. We’re only having 2 labels, TOTAL as label for the total result and lbltotal to displays result. The form looks like the following.

Item barcode total


frmChange Display the Amount Paid and Change. In the properties settings, switch the FormBorderStyle to None and StartPosition to CenterScreen. The form looks like the following.

iteam barcode amount
frmAccount – Only authorize users can access this form is there any mistakes inputs while processing the product entry. In the properties settings, switch the FormBorderStyle to None and StartPosition to CenterScreen. The form looks like the following.
barcode security system


Note: There’s an error while copying the code and paste to its controls if you don’t know how to place each piece of code in a specific controls. For instance, to enable KeyDown click event, you must place the code which control to be click enter so that when the users finish adding entry in textbox it will automatically process. However, if you only have one button to be click after entering data in textboxes, it's better to use accept button. In general, various buttons in one form with different click event, it's better to use Keydown event because it allows the user to place which appropriate command will trigger when the user hit enter. To do so, double click which textbox where the users enter data, after that click the dropdown menu and select KeyDown event, there are various events can be found but stick to the KeyDown event and add your following code.

It looks like the following image if you are going to locate click event.
Visual studio click event

Source code can download here.

Start with Dropbox? Sign up to save your files online and enable to share your link.