Upload
lamanh
View
222
Download
3
Embed Size (px)
Citation preview
1
CHAPTER 1
Introduction
Institutions and Organizations today are facing several unique communication challenges:
the proliferation of electronic messages across their enterprise; the need to provide employees,
customers, students and partners with consistent information; the desire to better equip
information workers with meaningful information to drive informed decisions; and the
mandate to control costs without sacrificing application, availability, security or reliability.
Various types of SMS text messages can be sent from multiple platforms, applications and
devices to making it easier to connect internal and external systems and deliver robust,
integrated intelligent solutions that help drive informed decisions and increase productivity
across the entire organization by controlling costs without sacrificing performance, availability,
or scalability.
The simplicity, speed and convenience of Short Messaging Service (SMS) have helped promote
its wide usage. Initially, the usage of SMS was to complement the functions of a standard
mobile phone. Lately, many have started to commercialize the usage of the SMS, for instance,
sending money (M-Pesa), shopping for commodities from retail stores, paying for electricity and
water bills, and querying bank account balances among others.
This project takes advantage of the convenience and speed of the SMS technology, so as to
design and implement an application that would enable students retrieve their examination
results via SMS.
2
1.1 Problem Statement
The project aims at reducing the havoc students’ go through to travel long distances, queue at
examination offices or crowd at notice boards to view their results. It even goes further to
reduce the amount of paper work that would otherwise be involved during preparation and
presentation of these results.
The student is registered and student details stored in a database. The student sends as SMS
with a service code to server. It validates the service code and processes the student request.
An SMS notifying the student of his/her results is then ensued.
1.2 Objective
Objectively, this project sets out three main purposes for its relevance. Firstly, that the success
of this project will be crucial in explaining its adoption by the University of Nairobi, Department
of Electrical and Electronic Engineering. Secondly, that the examination results are secure
within the database that stores examination results. Lastly, that it is simple and easily
understood by the end-users.
For simplicity, I have split this paper into four broad sections. In the first section, I present the
literature review on SMS technology. In section two, I provide a brief discussion on databases,
PC-to-mobile connectivity using AT commands. The methodology of design and implementation
is in section three, whereas the fourth section handles results of the experimental analysis. This
report concludes by discussing the limitations faced during design and implementation and
recommendations for future work.
3
CHAPTER 2
LITERATURE REVIEW
2.1 SMS Theory
SMS stands for Short Messaging Service. A Short Messaging Service is a binary string that
contains all the necessary information to form the message header needed for transportation
and the message body that contains the payload. The basic addressing scheme of SMS
messages are mobile telephone numbers called MSISDN.
This technology enables the sending and receiving of messages between mobile phones. SMS
first appeared in Europe in 1992. It was included in the GSM standards and later ported to
wireless technologies like CDMA and TDMA. The GSM and SMS standards were originally
developed by ETSI. ETSI is abbreviated to mean European Telecommunications Standards
Institute. Now 3GPP is responsible for the development and maintenance of the GSM and SMS
standards.
As the name suggests “Short Messaging Service”, the data that can be held by an SMS is at most
140 bytes. This actually implies that one SMS message can contain up to:
• 160 characters if 7-bit character encoding is used. 7-bit character encoding is suitable
for encoding Latin characters e.g. English alphabets.
• 70 characters if 16-bit Unicode UCS2 character encoding is used. This is mainly used in
text messages containing non-Latin characters like Chinese.
4
An SMS message can carry binary data. This makes it possible to send ringtones, pictures,
operator logos, wallpapers, animations, business cards and WAP configurations to a mobile
phone via SMS.
SMS is a success all over the world. The number of SMS messages exchanged every day is
enormous. SMS messaging is now one of the most important revenue sources of wireless
carriers. The SMS technology presents the following merits:
• SMS Messages can be Sent and Read at Any Time; almost every person has a mobile
phone and carries it most of the time.
• SMS Messages can be sent to an Offline Mobile Phone; an SMS can be sent to a mobile
phone that is switched off or if the recipient of the text is in a place where the wireless
signal is temporarily unavailable.
• SMS Messages are supported by 100% GSM mobile phones and can be exchanged
between different wireless carriers.
• SMS supports reverse billing, which enables payment to be made conveniently.
2.2 Short Messaging Service Centre
A Short Messaging Service Centre, usually abbreviated as SMSC, is responsible for handling the
SMS operations of a wireless network. When an SMS message is sent from a mobile phone, it
will reach an SMSC first. The SMSC then forwards the SMS message towards the destination. An
SMS message may need to pass through more than one network entity (e.g. SMSC and SMS
gateway) before reaching the destination.
5
The main duty of an SMSC is to route SMS messages and regulate the process.
Figure1. Basic Network Architecture for an SMSC
Figure 1 represents the basic network architecture for an SMSC deployment handling multiple
input sources, including a voice-mail system (VMS), Web-based messaging, e-mail integration,
and other external short message entities (ESMEs). Communication with the wireless network
elements such as the home location register (HLR) and mobile switching center (MSC) is
achieved through the signal transfer point (STP).
Visitor Location Register (VLR)
The visitor location register is a database that contains temporary information about
subscribers homed in one HLR who are roaming into another HLR.
MSC
The MSC performs the switching functions of the system and controls calls to and from
other telephone and data systems. The MSC will deliver short message to the specific
mobile subscriber through the base station.
6
Air Interface
The air interface is defined in each one of the different wireless technologies (GSM,
TDMA, and CDMA). These standards specify how the voice or data signals are
transferred from the MSC to the handset and back, as well as the utilization of
transmission frequencies, considering the available bandwidth and the system’s capacity
constraints.
2.3 SMS Gateway
The SMS gateway is a relay between two SMSCs. It translates one SMSC protocol to another in
order to facilitate two different wireless carriers to interconnect their SMSCs for purposes such
as, enabling the exchange of inter-operator SMS messages. Any two SMSCs cannot connect if
they do not support a common SMSC protocol.
Figure2: An SMS gateway acts as a relay between two SMS centers
7
To connect to an SMS gateway, you can use an SMSC protocol such as SMPP and CIMD. Some
SMS gateways support an HTTP / HTTPS interface. HTTP / HTTPS are easier to use than SMSC
protocols. The drawback is that there may be fewer SMS features to use. For example, an SMS
gateway may not support the sending of picture messages through the HTTP / HTTPS interface.
2.3.1 Basic services
The Short Message Service comprises of two basic services:
• SM MT (Short Message Mobile Terminated);
• SM MO (Short Message Mobile Originated).
SM MT denotes the capability of the GSM system to transfer a short message submitted from
the SMSC to one MS, and to provide information about the delivery of the short message either
by a delivery report or a failure report with a specific mechanism for later delivery.
SM MO denotes the capability of the GSM system to transfer a short message submitted by
the MS to one SME via an SMSC, and to provide information about the delivery of the short
message either by a delivery report or a failure report. The message must include the address
of that SME to which the SMSC shall eventually attempt to relay the short message.
8
2.3.2 Short Message Service elements
• Validity-Period
• Service-Centre-Time-Stamp
• Status report capabilities
Validity-Period
The Validity-Period parameter value indicates the time period for which the SMS is valid,
i.e. how long the SMSC shall guarantee its existence in the SMSC memory before delivery to the
recipient.
Service-Centre-Time-Stamp
The Service-Centre-Time-Stamp is the information element by which the SMSC informs the
recipient about the time of arrival of the SMS.
Sender: Year: Month: Day: Hour: Minute: Second:
Status report capabilities
The SMS also offers to the SMSC the capabilities of informing the MS of the status of a
previously sent mobile originated short message. The status of the message can be:
• Successfully delivered to the SME;
• The SMSC was not able to forward the message to the SME. The reason can be an error
of permanent or temporary nature. Permanent errors can be e.g. validity period
expired, invalid SME address.
9
2.4 GSM Modem
A GSM modem is a wireless modem that works with a GSM wireless network. A wireless
modem behaves like a dial-up modem. The main difference between them is that a dial-up
modem sends and receives data through a fixed telephone line while a wireless modem sends
and receives data through radio waves.
A GSM modem can be an external device or a PC Card / PCMCIA Card. Typically, an external
GSM modem is connected to a computer through a serial cable or a USB cable.
Like a GSM mobile phone, a GSM modem requires a SIM card from a wireless carrier in order to
operate.
The number of SMS messages that can be processed by a GSM modem per minute is about six
to ten SMS messages per minute.
2.5 GPRS Modem
A GPRS modem is a GSM modem that additionally supports the GPRS technology for data
transmission. It is a packet-switched technology that is an extension of GSM whereas GSM is a
circuit-switched technology. A key advantage of GPRS over GSM is that GPRS has a higher data
transmission speed.
If SMS over GPRS is used, then about 30 SMS messages per minute may be achieved. This is
much faster than using the ordinary SMS over GSM that averages at approximately six.
10
2.6 Drawbacks of the SMS Technology One SMS message can only carry a very limited amount of data. To overcome this drawback, an
extension called concatenated SMS (also known as long SMS) was developed. A concatenated
SMS text message can contain more than 160 English characters. The drawback of
concatenated SMS is that it is less widely supported than SMS on wireless devices.
Another major drawback is an SMS message cannot include rich-media content such as
pictures, animations and melodies. EMS (Enhanced Messaging Service) was developed in
response to this. The drawback of EMS is that it is less widely supported than SMS on wireless
devices. Also, many EMS-enabled wireless devices only support a subset of the features defined
in the EMS specification. A certain EMS feature may be supported on one wireless device but
not on the other.
11
CHAPTER 3
DATABASES
A database is a collection of information, tables and other objects organized and presented to
serve a specific purpose, such as facilitating searching, sorting and recombining data.
Databases can either be in the form of cards, paper files or electronic. An electronic database is
any collection of data that is specially and specifically organized for rapid search and retrieval
by a computer.
Advantages of electronic database
• Searching speed: electronic databases with powerful servers can be searched through a
query in a couple of seconds on any millions of records.
• Flexibility on data level: having structures of data one can build different templates of
the same data.
• Archive advantage: when the database is properly designed and maintained, it will still
search rapid and return results fast several years down the line.
• Future growth advantage: with electronic databases one can easily redesign without
having a reason to rewrite everything like it would in the case of a manual database.
• Variety of share points: an electronic database can be accessed by many users at the
same time.
Examples of electronic databases include; Microsoft Access, PostgreSQL, Microsoft SQL, Oracle,
MySQL etc.
12
3.1 SQL Express
SQL Express is a client/server relational database management system (RDBMS).
The terms client/server are used to refer to very general concepts or specific items of hardware
or software.
A client is any component of a system that requests services or resources from other system
components. A server is any system component that provides services or resources to other
system components.
An RDBMS is a collection of data organized in two-dimensional tables consisting of named
columns and unique rows. Each table represents the mathematical concept of a relation as
defined in set theory. In set theory columns are known as attributes and rows are known as
tuples. The operations that may be performed on tables are similarly based on manipulation of
relations to produce new relations, usually referred to as queries or views.
Microsoft SQL server controls access to your data to ensure that multiple users can work with it
concurrently, to provide fast access to it and ensure only authorized users can obtain access.
Hence, SQL Express is a multi-user, multi-threaded server.
3.2 Database file types
Database files are categorized into three types:
• Primary data file. This file is the starting point of the database. Every database must
have one, but only one. Primary data filenames have an .mdf extension.
13
• Secondary data files. These files are optional and can hold all data and objects that are
not on the primary data file. A database does not have to have secondary data files, but
may have secondary data files. Secondary data filenames have an .ndf extension.
• Log files. These files hold all the transaction log information used to recover the
database. Every database has at least one log file. Log filenames have an .ldf extension.
3.3 The Design Process
The best way of understanding database design is to start with an all-in-one, flat-file table
design then later on tossing in sample data to examine what happens. By analyzing sample
data, one will be able to identify the problems caused by the initial design. Modification of the
design to eliminate the problems is therefore of primary importance.
Modification and re-modification is a continual process until a consistent and problem-free
design is achieved.
Ultimately, the design will depend on the complexity of the data, each time the database is
designed.
However, the following are vital points to any design process:
• Break composite fields down into constituent parts. Example: name becomes lastname
and firstname.
• Create a key field which uniquely identifies each record.
14
• Eliminate repeating groups of fields. Example: if a table contains fields Location 1,
Location 2, Location 3 containing similar data, it is a sure warning sign.
• Eliminate record modification, deletion and addition problems by ensuring each non-key
field depends on the entire key. To achieve this, create a separate table for any
information that is used in multiple records, and then use a key to link these tables to
one another.
SQL Express is based on the relational data model and uses SQL as its query language. The
relational data models:
1. It is a model that is easily understood and visualized.
2. Reduced data redundancy.
3. Independent physical storage and logical database structures.
4. Its integrity laws are easy to develop and understand.
15
CHAPTER 4
MOBILE PHONE & PC CONNECTIVITY
There are two widely used ways through which a mobile phone can be physically connected to
a computer:
• Via Bluetooth
• Via serial data cable
Commands are sent to the phone to perform certain tasks; these commands are the same
regardless of the type of connection used.
4.1 AT Commands
AT commands are instructions used to control a modem. AT is the abbreviation of ATtention.
Since every command line starts with "AT" or "at" hence the name AT commands. Many of the
commands that are used to control wired dial-up modems are also supported by GSM/GPRS
modems and mobile phones. GSM/GPRS modems and mobile phones support an AT command
set that is specific to the GSM technology, which includes SMS-related commands like
AT+CMGS (Send SMS message), AT+CMSS (Send SMS message from storage), AT+CMGL
(List SMS messages) and AT+CMGR (Read SMS messages).
16
4.2 Basic Commands and Extended Commands
There are two types of AT commands:
• Basic commands
• Extended commands.
Basic commands are AT commands that do not start with "+". For example, D (Dial), A (Answer),
H (Hook control) and O (Return to online data state) are basic commands.
Extended commands are AT commands that start with "+". All GSM AT commands are extended
commands. For example, +CMGS (Send SMS message), +CMSS (Send SMS message from
storage), +CMGL (List SMS messages) and +CMGR (Read SMS messages) are extended
commands. All SMS messaging commands are extended AT commands.
Some of the tasks that can be achieved using AT commands with a GSM/GPRS modem or
mobile phone include:
• Get basic information about the mobile phone or GSM/GPRS modem. For example,
name of manufacturer (AT+CGMI), IMEI number (AT+CGSN)
• Get basic information about the subscriber. For example, IMSI number (AT+CIMI).
• Get the current status of the mobile phone or GSM/GPRS modem. For example, mobile
phone activity status (AT+CPAS)
• Establish a data connection or voice connection to a remote modem ATD (Dial),
ATA (Answer).
• Send and receive fax (ATD, ATA, AT+F*).
17
• Send (AT+CMGS, AT+CMSS), read (AT+CMGR, AT+CMGL), write (AT+CMGW) or delete
(AT+CMGD) SMS messages and obtain notifications of newly received SMS messages
(AT+CNMI).
• Read (AT+CPBR), write (AT+CPBW) or search (AT+CPBF) phonebook entries.
• Control the presentation of result codes / error messages of AT commands. For
example, you can control whether to enable certain error messages (AT+CMEE) and
whether error messages should be displayed in numeric format or verbose format
(AT+CMEE=1 or AT+CMEE=2).
• Get or change the configurations of the mobile phone or GSM/GPRS modem. For
example, change the GSM network (AT+COPS).
• Save and restore configurations of the mobile phone or GSM/GPRS modem. For
example, save (AT+CSAS) and restore (AT+CRES) settings related to SMS messaging such
as the SMS center address.
Generally, GSM/GPRS modems designed for wireless applications have better support of AT
commands than ordinary mobile phones.
18
CHAPTER 5
DESIGN
5.1 Software
Microsoft Windows XP OS
It is a series of software and graphical user interfaces produced by Microsoft. Microsoft named
the operating environment Windows and its availability is guaranteed.
SQL Express
SQL Express has gained a strong reputation for being the database of choice for the open
source community. It is free for personal use so fits my need for an inexpensive solution. If the
system was to become commercial the license is reasonable compared to other database
products like Oracle.
Visual Basic.Net
Visual Basic.Net provides a complete set of tools to simplify rapid application development.
The “Visual” part refers to the method used to create the GUI. Rather than writing numerous
lines of code to describe the location and appearance of interface elements.
The “Basic” part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code)
language.
19
5.2 Hardware
Computer
The computer will host the database for the exam results, the script to decipher the short
message and the SMS Gateway.
GSM Phone
Nokia 6070 was my choice model because of its compatibility with the AT commands that I
used to generate my application.
USB Data Cable
CA-52 was my data cable of choice since it is compatible with Nokia 6070 hence connection to
the PC.
GSM Modem
This was so as to facilitate the sending and receiving of text messages.
20
5.3 Approach
I decided to use a modular system of approach because I saw the solution could be broken into
four distinct parts. The benefit of a modular system is that I can test each part individually and
in future replacing the weak links in the chain.
Modules of approach:
• Developing a user-interface application that will necessitate entry of students’
examination results into the database.
• Creating a database and that will store the students’ examination results, incoming and
outgoing messages.
• Devising a way in which the GSM phone will communicate with the PC to aid in retrieval
of results from the database via SMS.
• A message server that would facilitate sending and receiving of SMSs during run-time.
Roles
Since I was the sole developer and end-user I felt it was important to ask myself a few critical
questions:
End-user: How easy is it for one to use the system?
Answer: The system will allow one to query your examination results simply by sending an SMS
to a pre-defined number.
21
Dean or Chairman: How much will the system cost?
Answer: The administration costs are minimal with the main cost being the reply SMS to
students. When the student base grows and the SMS traffic increases we can take out a service
contract with a mobile provider and get a direct SMSC link and lower cost per SMS for students.
Thus, the only capital cost is contracting a mobile service provider that will handle the bulk of
SMSs and also provide a pre-defined text prefix number.
Technical Analyst: How many SMS messages can the system handle?
Answer: With a good SMSC link the system can process, on average 15 text messages per
second.
Student: How confidential are my examination results?
Answer: Every student will have a secret pin number that he/she will use to query his/her
results. However, there will be a default pin number.
Programmer: How will I keep the code understandable?
Answer: VB.Net is already a fairly English language so it will be understandable to those
working on the project even at a later date. Commenting within the code also helps in
explaining part of the code.
22
Hardware Environment
Processor: Pentium 4
Hard Disk Storage: 160 GB
RAM: 512 MB
GSM mobile phone used to access the GSM Network. The GSM phone functioned as a GSM
modem.
Software Environment
OS: Windows XP
Database: SQL Express
Compiler Language: VB.Net
23
5.4 Implementation
The application is divided into 3 major modules:
• Database
• Phone to PC connectivity using AT commands
• User interface
The database stores the students’ details and incoming and outgoing messages.
Once this is developed, phone to PC connectivity then follows. This connectivity will allow the
GSM phone to communicate with the PC therefore acting as a modem. It would manage the
sending and retrieval of messages.
The user interface aids in entering student details into the database.
24
CHAPTER 6
RESULTS AND EVALUATION
6.1 RESULTS
Upon successful registration of students’ details, the details were stored in a database.
The student sends an SMS with service code to server. It is validates the service code and
processes the student request.
A result notification is later ensued.
The valid message syntax is:
PJ62 # Reg. No # PIN Number # R1
• PJ 62: request of SMS-ERQS service
• Reg. No: student’s unique registration number
• PIN Number: to curb against unauthorized view of one’s results.
• R1: 1st year results summary. R5 in the case of 5th years and so on.
The PIN Number was set at a default figure of 0000.
6.2 TESTING
Testing the application was mandatory so as to ensure it functions consistently and correctly.
System testing makes a logical assumption that if all the parts of the system are correct then
the goal will be successfully achieved. I conducted numerous tests on the application to
ascertain the SMS-RQS functionality and query response.
25
6.3 SETBACKS
While working on the SMS-ERQS some minor and major setbacks were encountered.
Minor Setbacks
1. While developing the application syntax errors like missing identifiers proved to be very
annoying.
2. Locating the correct driver that would facilitate my database connection could not pass
my mention.
3. During run-time the cost per tested transaction was 7/= this translated to the entire
testing process being shyly costly.
Major Setbacks
1. Configuring the GSM modem to send and receive messages during design time was not
something to write home about.
2. Another major setback was integrating all the modules together to have the application
function as a whole.
3. I had to purchase a phone that offered better and simpler compatibility features to the
AT commands. Nokia 6070 proved very appropriate.
26
CHAPTER 7
CONCLUSION
SMS-ERQS has been developed to case out the problems students face whenever they want to
view their results and champion for an improvement of the present system. This system is
expected to prove useful.
The goals expected to be achieved by this system are:
• Simplify the retrieval of exam results.
• Increasing productivity by spending less time to process the results.
• Avoiding errors by minimizing human interaction during the retrieval of the examination
results.
• Flexible for further enhancement.
After successfully developing the system and testing it, the results obtained were very
satisfactory. The system is easy to use, secure and available round the clock.
27
CHAPTER 8
RECOMMENDATIONS AND FUTURE WORK
The modular approach with which was used to develop this system has different modules
performing their tasks. This guarantees that should there be any changes that need to be done
to the system then it can be easily achieved by making the required change without necessarily
affecting the remaining part of the system.
This system was limited to SMS. However, the scope for future enhancement would see this
application being web-based as well. This will require a server-side scripting language e.g. PHP
that will execute scripts on the server where the website is located.
28
CHAPTER 9
BIBLIOGRAPHY
1. Wikipedia: The online English Encyclopedia
www.wikipedia.org
2. Microsoft developers website
www.learnvisualstudio.com
3. Databases
www.wdvl.com
4. How stuff works
www.howstuffworks.com
29
CHAPTER 10
APPENDIX
10.1 Excerpt of Code
10.1.1 SMS Based Data Access
Imports System.Data Imports RixDataAccessUtility Imports SmsBasedExamRRS.Core Public Class ExamResultDAO Public Sub New() End Sub Sub Insert(ByVal result As ExamResult) If Not Me.IsDuplicate(result) Then Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, result.ID) dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, result.StudentNumber) dataAccess.AddParameter("@Course", DbType.String, ParameterDirection.Input, result.Course) dataAccess.AddParameter("@UnitCode", DbType.String, ParameterDirection.Input, result.UnitCode.Code) dataAccess.AddParameter("@State", DbType.String, ParameterDirection.Input, result.State) dataAccess.AddParameter("@Grade", DbType.String, ParameterDirection.Input, result.Grade) cmd.CommandText = "Insert into ExamResults values(@StudentNumber,@Course,@UnitCode,@State,@Grade)" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) Else Throw New Exception("Duplicate results detected!") End If End Sub Sub Update(ByVal result As ExamResult) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, result.ID) dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, result.StudentNumber) dataAccess.AddParameter("@Course", DbType.String, ParameterDirection.Input, result.Course) dataAccess.AddParameter("@UnitCode", DbType.String, ParameterDirection.Input, result.UnitCode.Code)
30
dataAccess.AddParameter("@State", DbType.String, ParameterDirection.Input, result.State) dataAccess.AddParameter("@Grade", DbType.String, ParameterDirection.Input, result.Grade) cmd.CommandText = "Update ExamResults set Course=@Course,StudentNumber=@StudentNumber,UnitCode=@UnitCode,Grade=@Grade,State=@State Where ID=@ID" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) End Sub Sub Delete(ByVal result As ExamResult) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, result.ID) cmd.CommandText = "Delete ExamResults where ID=@ID" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) End Sub Function IsDuplicate(ByVal result As ExamResult) As Boolean Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, result.StudentNumber) dataAccess.AddParameter("@Course", DbType.String, ParameterDirection.Input, result.Course) dataAccess.AddParameter("@UnitCode", DbType.String, ParameterDirection.Input, result.UnitCode.Code) cmd.CommandText = "Select * From ExamResults Where StudentNumber=@StudentNumber AND Course=@Course AND UnitCode=@UnitCode" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Return reader.Read End Function Function Read() As List(Of ExamResult) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text cmd.CommandText = "Select ID From ExamResults" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim list As New List(Of ExamResult) While (reader.Read) list.Add(Me.FetchByID(Convert.ToInt32(reader("ID")))) End While reader.Close() Return list End Function Function FetchByID(ByVal id As Integer) As ExamResult Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, id) cmd.CommandText = "Select * From ExamResults Where ID=@ID"
31
Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim examResult As New ExamResult Dim unitDao As New UnitDAO If (reader.Read) Then examResult.ID = Convert.ToInt32(reader("ID")) examResult.Course = reader("Course") examResult.StudentNumber = reader("StudentNumber") examResult.UnitCode = unitDao.FetchByCode(reader("UnitCode")) examResult.Grade = Convert.ToInt32([Enum].Parse(GetType(Grades), reader("Grade").ToString)) examResult.State = Convert.ToInt32([Enum].Parse(GetType(ResultState), reader("State").ToString)) End If reader.Close() Return examResult End Function Function FetchByCode(ByVal code As String) As ExamResult Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@Code", DbType.String, ParameterDirection.Input, code) cmd.CommandText = "Select * From ExamResults Where Code=@Code" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim examResult As New ExamResult Dim unitDao As New UnitDAO If (reader.Read) Then examResult.ID = Convert.ToInt32(reader("ID")) examResult.Course = reader("Course") examResult.StudentNumber = reader("StudentNumber") examResult.UnitCode = unitDao.FetchByCode(reader("UnitCode")) examResult.Grade = Convert.ToInt32([Enum].Parse(GetType(Grades), reader("Grade").ToString)) examResult.State = Convert.ToInt32([Enum].Parse(GetType(ResultState), reader("State").ToString)) End If reader.Close() Return examResult End Function Function FetchByStudent_UnitCode(ByVal studentNumber As String, ByVal unitCode As String) As ExamResult 'If unitCode Is Nothing Then ' unitcode = "None" 'End If Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, studentNumber) dataAccess.AddParameter("@UnitCode", DbType.String, ParameterDirection.Input, unitCode) cmd.CommandText = "Select * From ExamResults Where StudentNumber=@StudentNumber AND UnitCode=@UnitCode" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim examResult As New ExamResult
32
Dim unitDao As New UnitDAO If (reader.Read) Then examResult.ID = Convert.ToInt32(reader("ID")) examResult.Course = reader("Course") examResult.StudentNumber = reader("StudentNumber") examResult.UnitCode = unitDao.FetchByCode(reader("UnitCode")) examResult.Grade = Convert.ToInt32([Enum].Parse(GetType(Grades), reader("Grade").ToString)) examResult.State = Convert.ToInt32([Enum].Parse(GetType(ResultState), reader("State").ToString)) End If reader.Close() Return examResult End Function Function FetchByStudent(ByVal studentNumber As String) As List(Of ExamResult) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, studentNumber) cmd.CommandText = "Select ID From ExamResults where StudentNumber=@StudentNumber" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim list As New List(Of ExamResult) While (reader.Read) list.Add(Me.FetchByID(Convert.ToInt32(reader("ID")))) End While reader.Close() Return list End Function Function FetchByStudent_Course(ByVal studentNumber As String, ByVal course As String) As List(Of ExamResult) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@StudentNumber", DbType.String, ParameterDirection.Input, studentNumber) dataAccess.AddParameter("@Course", DbType.String, ParameterDirection.Input, course) cmd.CommandText = "Select ID From ExamResults where StudentNumber=@StudentNumber AND Course=@Course" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim list As New List(Of ExamResult) While (reader.Read) list.Add(Me.FetchByID(Convert.ToInt32(reader("ID")))) End While reader.Close() Return list End Function End Class
33
10.1.2 Student Data Access
Imports System.Data Imports RixDataAccessUtility Imports SmsBasedExamRRS.Core Public Class StudentDAO Public Sub New() End Sub Sub Insert(ByVal student As Student) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, student.ID) dataAccess.AddParameter("@FirstName", DbType.String, ParameterDirection.Input, student.FirstName) dataAccess.AddParameter("@MiddleName", DbType.String, ParameterDirection.Input, student.MiddleName) dataAccess.AddParameter("@LastName", DbType.String, ParameterDirection.Input, student.LastName) dataAccess.AddParameter("@RegNumber", DbType.String, ParameterDirection.Input, student.RegistrationNumber) dataAccess.AddParameter("@Password", DbType.String, ParameterDirection.Input, student.Password) dataAccess.AddParameter("@RegisteredCourse", DbType.String, ParameterDirection.Input, student.RegistrationNumber) cmd.CommandText = "Insert into Students values(@FirstName,@MiddleName,@LastName,@RegNumber,@Password,@RegisteredCourse)" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) If (i > 0) Then 'Dim regCourseDao As New RegisteredCourseDAO 'For Each course As RegisteredCourse In student.RegisteredCourse ' 'If course.IsNew Then ' regCourseDao.Insert(course) ' 'Else ' ' regCourseDao.Update(course) ' 'End If 'Next End If End Sub Sub Update(ByVal student As Student) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, student.ID) dataAccess.AddParameter("@FirstName", DbType.String, ParameterDirection.Input, student.FirstName) dataAccess.AddParameter("@MiddleName", DbType.String, ParameterDirection.Input, student.MiddleName)
34
dataAccess.AddParameter("@LastName", DbType.String, ParameterDirection.Input, student.LastName) dataAccess.AddParameter("@RegNumber", DbType.String, ParameterDirection.Input, student.RegistrationNumber) dataAccess.AddParameter("@Password", DbType.String, ParameterDirection.Input, student.Password) dataAccess.AddParameter("@RegisteredCourse", DbType.String, ParameterDirection.Input, student.RegistrationNumber) cmd.CommandText = "Update Students set FirstName=@FirstName,MiddleName=@MiddleName,LastName=@LastName, " _ + "RegNumber=@RegNumber,Password=@Password,RegisteredCourse=@RegisteredCourse Where ID=@ID" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) If (i > 0) Then 'Dim regCourseDao As New RegisteredCourseDAO 'For Each course As RegisteredCourse In student.RegisteredCourse ' If (course.IsNew) Then ' regCourseDao.Insert(course) ' Else ' regCourseDao.Update(course) ' End If 'Next End If End Sub Sub Delete(ByVal student As Student) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, student.ID) cmd.CommandText = "Delete Students Where ID=@ID" Dim i As Integer = dataAccess.ExecuteNonQuery(cmd) If (i > 0) Then Dim regCourseDao As New RegisteredCourseDAO For Each course As RegisteredCourse In student.RegisteredCourse regCourseDao.Delete(course) Next End If End Sub Function IsDuplicate(ByVal student As Student) As Boolean End Function Function Read() As List(Of Student) Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text cmd.CommandText = "Select ID From Students" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim list As New List(Of Student) While (reader.Read)
35
list.Add(Me.FetchByID(Convert.ToInt32(reader("ID")))) End While Return list End Function Function FetchByID(ByVal id As Integer) As Student Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@ID", DbType.Int32, ParameterDirection.Input, id) cmd.CommandText = "Select * From Students Where ID=@ID" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim student As New Student Dim regCourseDao As New RegisteredCourseDAO If (reader.Read) Then student.ID = Convert.ToInt32(reader("ID")) student.FirstName = reader("FirstName") student.MiddleName = reader("MiddleName") student.LastName = reader("LastName") student.RegistrationNumber = reader("RegNumber") student.Password = reader("Password") student.RegisteredCourse = regCourseDao.Fetch(student.RegistrationNumber) End If Return student End Function Function FetchByRegistrationNumber(ByVal regNumber As String) As Student Dim dataAccess As New DataAccessUtility Dim cmd As IDbCommand = dataAccess.ICommand cmd.CommandType = CommandType.Text dataAccess.AddParameter("@RegNumber", DbType.String, ParameterDirection.Input, regNumber) cmd.CommandText = "Select * From Students Where RegNumber=@RegNumber" Dim reader As IDataReader = dataAccess.ExecuteReader(cmd) Dim student As New Student Dim regCourseDao As New RegisteredCourseDAO If (reader.Read) Then student.ID = Convert.ToInt32(reader("ID")) student.FirstName = reader("FirstName") student.MiddleName = reader("MiddleName") student.LastName = reader("LastName") student.RegistrationNumber = reader("RegNumber") student.Password = reader("Password") student.RegisteredCourse = regCourseDao.Fetch(student.RegistrationNumber) End If Return student End Function End Class