SeahYeowNgeeMFKE2007TTT

DATA TRANSMISSION BETWEEN PDA AND PC USING WIFI
FOR POCKET BARCODE APPLICATION
SEAH YEOW NGEE
UNIVERSITI TEKNOLOGI MALAYSIA
iii
To my dearest parents, brother and sisters,
for their continuous love, motivation, support and encouragement.
iv
ACKNOWLEDGEMENT
Throughout the period of doing this project, I received a lot of
encouragements and assistance from a few parties. Firstly, I would like to express my
sincere gratitude to my project supervisor, Associate Professor Dr. Syed Abdul
Rahman bin Syed Abu Bakar for his guidance, support, motivation and help
throughout this project.
I also like to express my heartiest appreciation to my parents, brothers and all
my family members for their endless support, encouragement and love. Special
thanks for my parents and brother for their understanding, care and ceaseless
supports in all my endeavors.
Thirdly, I would thanks Intel Penang Design Center for sponsoring my master
program and University Technology Malaysia lecturers for sacrificing their
weekends to travel to Penang for lecture and knowledge transfer that has indirectly
contribute some knowledge needed for me to do this project.
Finally, I would like to thank all my friends for their help and special thanks
to Miss Cho Swee Teng, Mr. Benny Khoo and Mr. Lawrence See for their sharing
and fruitful discussion.
v
ABSTRACT
Barcode system is a very common system that is widely used in various areas
in today businesses. Pocket Barcode application will be another key evolution for
barcode. Pocket barcode application that uses wireless network like WIFI is able to
enable barcode to be captured anywhere and extract the information on the fly from
server located somewhere else within the WIFI coverage area. Besides that, it can
save computation time of Personal Digital Assistance (PDA) and at the same time
utilize PDA (client) to communicate with PC (server) for more accurate information
like inventory, delivery and pricing of stocks. The image captured by PDA is
transferred back to server for processing and data extraction. In this project, client
and server programming model was used to program the “Pocket Barcode Reader”
client and “Pocket Barcode Server” applications. Actual data is transferred using
WIFI network from client to server and vice versa through asynchronous socket. The
asynchronous socket used transmission control protocol (TCP) to transmit data.
Microsoft C# 2005 language was used to program both applications. Microsoft
Windows Mobile 5.0 Software Development Kits was used to simulate “Pocket
Barcode Reader” client application. The result obtained from this project is client
program (Pocket Barcode Reader) that is able to transmit barcode pictures to server
program (Pocket Barcode Server) for real time decoding. The decoded result is then
transmitted back to client program for display.
vi
ABSTRAK
Sistem kod bar merupakan sistem yang sangat biasa digunakan di merata
tempat dalam dunia peniagaan hari ini. Penggunaan kod bar bergerak merupakan
suatu kemajuan dan perkembangan terkini. Penggunaan jaringan WIFI menbolehkan
gambar kod bar diambil di mana-mana sahaja dan data mengenai kod bar ini dapat
diproses dengan pantas selagi penggunanya berada di kawasan jaringan WIFI. Selain
itu, cara penggunaan sebegini membolehkan pembantu peribadi digit (PDA)
menjimatkan masa pemprosesannya. Tambahan pula, PDA (Pelanggan) boleh
memperolehi maklumat yang terkini daripada Komputer (Pelayan) seperti data
simpanan, penghantaran barang dan harga. Semua ini dapat dilakukan dengan
menghantar gambar-gambar yang ditangkap oleh PDA ke komputer untuk diproses
dan datanya akan dihantar balik kepada PDA. Dalam projek ini, model pelayanpelanggan (client-server) digunakan dalam mengaturcarakan “Pocket Barcode
Reader” dan “Pocket Barcode Server”. Data dihantar daripada pelanggan kepada
pelayan dan sebaliknya dengan menggunakan jaringan WIFI melalui soket. Soket
pula menggunakan protocol penghantaran kawalan (TCP) untuk menghantar data.
Aturcara kedua-dua program ditulis menggunakan bahasa aturcara Microsoft C#
2005. Perisian kit pembangunan Microsoft Windows Mobile 5.0 pula digunakan
untuk selaku program “Pocket Barcode Reader” yang berfungsi sebagai pelanggan.
Keputusan yang didapati daripada projek ini ialah aturcara pelanggan (“Pocket
Barcode Reader”) yang dapat menghantar gambar kod bar kepada aturcara pelayan
(“Pocket Barcode Server) untuk diproses. Data yang telah diproses akan dihantar
balik kepada aturcara pelanggan untuk dipaparkan.
vii
CONTENTS
CHAPTER
I
II
TITLE
PAGE
DECLARATION
ii
DEDICATION
iii
ACKNOWLEDGEMENT
iv
ABSTRACT
v
ABSTRAK
vi
CONTENTS
vii
LIST OF TABLES
xi
LIST OF FIGURES
xii
LIST OF APPENDIX
xv
INTRODUCTION
1.1 Project Background and Reviews
1
1.1.1 Barcodes and its type
2
1.2 Problem Statement
4
1.3 Objective and Scope of Project
4
1.4 Project Overview
5
1.5 Problems Challenges
6
1.6 Summary
7
BACKGROUND AND LITERATURE REVIEWS
2.1 Windows Mobile 5.0 and its SDKs
8
2.2 Network connections types and comparison
9
2.2.1 Bluetooh
9
viii
2.2.2 Infrared (irDA)
10
2.2.3 WIFI
11
2.2.4 Ethernet LAN
14
2.2.5 Comparison table for Bluetooh, infrared, WIFI and
Ethernet LAN
2.3 Wireless Application Protocol (WAP)
15
16
2.3.1 What is WAP?
17
2.3.2 OSI Model for wireless communication
18
2.3.2.1 Application Layer (WAE and WTA)
19
2.3.2.2 Session Layer (WSP)
19
2.3.2.3 Transaction Layer (WTP)
20
2.3.2.4 Wireless Transport Layer Security (WTLS)
21
2.3.2.5 Transport Layer (WDP)
22
2.4 Wireless Access Point vs Adhoc Network
22
2.4.1 Wireless Access Point Network
23
2.4.1 Adhoc Network
25
2.5 Development and Deployment: Tools, Emulators &
26
Devices
27
2.6 Summary
III
DATA TRANSMISSION USING WIFI
3.1 Pocket Barcode Reader Software Design
28
3.1.1 High Level System Model
29
3.1.2 Client module key features and functionallity
30
3.1.2.1 Pocket Barcode Reader Class Diagram
33
3.1.2.2 ClientSocket Class
35
3.1.2.3 Sending Image from Pocket Barcode
Reader to Barcode Server
3.1.3 Server module feature and functionality
38
39
3.1.3.1 Pocket Barcode Server Class Diagram
41
3.1.3.2 Server Socket class
42
ix
3.1.3.3 Sending ASCII code back to to Pocket
Barcode Reader
3.1.4 Common module
IV
44
45
3.2 Asynchronous socket connection
47
3.3 Summary
48
SIMULATION ENVIRONMENT AND RESULT
4.1 Simulation Environment Setup and Configuration
49
4.1.1 Windows Mobile 5.0 Emulator
50
4.1.2 Virtual Machine Network Service
53
4.1.2.1 Virtual Machine Service Installation and
Verification
V
54
4.2 Deployment of Pocket Barcode Reader to Emulator
58
4.3 Simulation Result and Analysis
58
4.3.1 Pocket Barcode Reader Client Application
58
4.3.2 Pocket Barcode Server Application
61
4.4 Sample barcode images simulation
65
4.5 Summary
69
FUTURE WORKS, DISCUSSION, AND CONCLUSION
5.1 Future works
70
5.1.1 Improvement on Pocket Barcode Reader
70
5.1.2 Improvement on Pocket Barcode Server
71
5.1.3 Overall system improvement
72
5.2 Discussions
72
5.3 Pros and Cons of Software Design
73
5.4 Summary and Conclusion
74
x
REFERENCES
APPENDIX A
75
POCKET BARCODE READER
SOURCE CODE
78
APPENDIX B POCKET BARCODE SERVER
SOURCE CODE
APPENDIX C COMMON MODULE SOURCE CODE
92
103
xi
LIST OF TABLES
TITLE
TABLE NO
2.1
Bandwidth and range comparison between various
PAGE
16
connections types
3.1
Pocket Barcode Reader Application States and Error
Code
33
3.2
ClientSocket class method and type
37
3.3
ServerSocket class method and type
44
3.4
Configuration class method and type
46
3.5
Network class method and type
47
3.6
Asynchronous methods used in ClientSocket and
ServerSocket Class
48
xii
LIST OF FIGURES
FIGURE NO
1.1
TITLE
Sample of UPC, EAN, ISBN and 2D barcodes;
PAGE
3
(a) UPC barcode,
(b) UPC barcode vE,
(c) EAN-8 barcode,
(d) EAN-13 barcode,
(e) 2-D barcode,
(f) ISBN barcode
1.2
Block diagram of proposed PDA and PC data
transmission model
5
2.1
OSI Model of Wireless Application Protocol
18
2.2
Wireless AP device and its adapters
23
2.3
An example of wireless access point network model
23
2.4
An example of overlap access point to cover wider
range and users
24
2.5
An example of ad hoc network model
25
2.6
Development and Deployment Environment, Tools
and Devices
26
3.1
High Level System Model of Pocket Barcode Reader
29
3.2
Pocket Barcode Reader Startup GUI
30
3.3
Pocket Barcode Reader “Options” GUI
31
3.4
Class Diagram of Pocket Barcode Reader
33
3.5
Pocket Barcode Server GUI
39
3.6
Class Diagram of Pocket Barcode Server
41
xiii
4.1
Mobile Devices Configuration page in Visual Studio
2005
4.2
Windows Mobile 5.0 Pocket PC Emulator properties
window
4.3
52
Windows Mobile 5.0 Pocket PC Emulator Network
Properties
4.5
51
Windows Mobile 5.0 Pocket PC Emulator General
Properties
4.4
50
53
LAN properties after installation of Virtual Machine
Network
54
4.6
List of Windows Mobile Pocket PC devices
55
4.7
Pocket PC Emulator start up page
56
4.8
Pocket PC Emulator Network Setting Properties
57
4.9
Pocket Barcode Reader Options Form
59
4.10
Pocket Barcode Reader connecting to server
60
4.11
Pocket Barcode Reader Image file selection box
60
4.12
Pocket Barcode Reader load image and send to server
61
4.13
Initial start up of Pocket Barcode Server application
62
4.14
Pocket Barcode Server after connected to client
62
4.15
Pocket Barcode Server “Barcode” Tab
63
4.16
Pocket Barcode Server “ASCII” Tab
63
4.17
Pocket Barcode Server “Decode” Tab
64
4.18
Pocket Barcode Server “SendToPDA” Tab
64
4.19
Pocket Barcode Server “About” Tab
65
4.20
Various type of barcode images simulation
68
(a) Glossy barcode
66
(b) Distorted barcode
66
(c) Distorted barcode
66
(d) National Instrument barcode
66
(e) blur barcode
67
(f) Plastic surface barcode
67
(g) Metal surface barcode
67
(h) Dark surface barcode
67
xiv
(i) Normal surface barcode
68
(j) Dirty surface barcode
68
(k) Reflective surface barcode
68
(l) Reflective surface barcode
68
xv
LIST OF APPENDIX
APPENDIX A
Pocket Barcode Reader Source Code
80
i. Main Form
ii. Options Form
iii. ClientSocket Class
APPENDIX B
Pocket Barcode Server Source Code
94
i. Main Form
ii. ServerSocket Class
APPENDIX C
Common Module Source Code
i. Network Class
ii. Configuration Class
105
CHAPTER I
INTRODUCTION
The information age in today’s world are characterized by rapid development
and change. It moves faster than earlier eras and the pace continues to speed up. The
continuous developments of computer technology in marketing, manufacturing,
distribution, communications, transportation, healthcare and many sectors have
played and continue to play a large part in accelerating change. For any business in
this fast changing world, the importance of collecting and processing information on
a timely basis is essential. In order to continue to be effective and able to respond to
new customer requirements, every sector requires reliable information in real time or
as close to it as possible. Due to this fact, barcode system is getting more and more
important in providing solution for today’s business needs in an efficient and
economical way. In addition to this, with well over a billion mobile PDA handsets
worldwide, wireless barcode system will be another key enabling to expand beyond
the traditional limitation of fixed-line barcode system.
1.1
Project Background and Reviews
Barcode system normally operated by using a set of PC and wired infra-red
scanner. This method of setup is the most popular and widely used in today
businesses. Due to it advantages in accuracy and effectiveness of data tracking, their
applications can be found in a vast range of organizations, including hypermarket
and retail stores (point-of sale [POS] systems), libraries, hospitals, schools and
factories (production and supply chain management). [11]
2
The traditional barcode system has successfully creeping into various
industries and provides effective yet economy system for a lot of businesses.
Although it has some portability limitation, it is still an un-removable system for
today businesses.
1.1.1
Barcodes and its types
In terms of business use, barcodes have been promoted largely as a machine-
readable “license plate,” where each label provides a unique serial number coded in
black and white bars linking to a database entry containing detailed information.
More recently, end users have sought to code more information; making the barcode
a portable database rather than just a database key. One good example is the Data
Matrix barcode, a two-dimensional (2D) matrix code as shown in Figure 1.1(e). A
Data Matrix symbol typically stores between one and 500 characters. The symbol is
also scalable, from a 1 millimeter square to a 14 inch square. Theoretically, a
maximum of 500 million characters to the inch is possible, but the practical density
will be limited by the resolution of the printing and reading technology used.
There are several varieties and standards for barcodes as shown in Figure 1.1.
The symbol found on most retail products around the world is based on UPC/ EAN
standards as shown in Figure 1.1(a), (b), (c) and (d). The Universal Product Code
(UPC), developed by the Uniform Code Council (UCC), was the first barcode
symbol widely adopted in the world. In 1973, the grocery industry formally
established UPC as the standard bar code symbol for product marking in the United
States. European interest in UPC led to the adoption of the European Article
Numbering (EAN) code format in 1976 (EAN, 2003).
3
(a) UPC barcode
(b) UPC barcode vE
(c) EAN-8 barcode
(d) EAN-13 barcode
(e) 2-D barcode
Figure 1.1
(f) ISBN barcode
Sample of UPC, EAN, ISBN and 2D barcodes
Today, EAN International is a global non-profit organization that creates,
develops, and manages jointly with the UCC open, global, multi-sector information
standards, and the EAN/ UCC standards. All businesses must apply for membership
in order to be assigned unique company identification number for use on all its
products. There are now five versions of UPC and two versions of EAN. The
Japanese Article Numbering (JAN) code has a single version identical to one of the
EAN versions. UPC and EAN symbols are fixed in length can only encode numbers,
and are continuous symbol using four element widths. The barcode used on books,
for example, is generated based on the International Standard Book Number (ISBN)
as shown in Figure 1.1(f). [11]
4
1.2
Problem Statement
Many of today working environment and industries require more and more
worker to leave their fixed working space in order to conduct their work at changing
location or while they are on the move. Due to this fact, mobile system is a must to
enable worker to be able conduct their work effectively.
One pertinent area of recent barcode system development is in methods of
enabling wireless barcode for personal transaction and information transfer. This has
been an active research area including its technology, methodology and algorithm in
performing and enabling those kinds of transactions. As of today, we can see that
mobile barcode system has been in advance hospital patient’s database tracking,
mobile ticketing, e-wallet, real-time inventory tracking and etc. However, its
application is still limited to only advance industries due to it cost, infrastructures
and etc.
1.3
Objective and Scope of Project
The main objective of the project is to develop programs to enable wireless
data transmission between PDA and PC for barcode system using WIFI. These
programs will act as a medium to transfer picture captured by PDA and send it to PC
for processing. Once processed, the PC will send the result of ASCII code back to the
PDA for display. By having this model, it will save the computation time of PDA
and at the same time speed up the decoding of barcode information. In addition, it
will enable PDA client to get more up-to-date and accurate information from server.
At the end of this project, two programs will be developed. First program is
the server program which will function as a server to receive multi-session
connections from PDA clients and able to send ASCII code back to respective client
that make request. Second program is the client program that will establish
connection with server and send barcode image captured by PDA camera to server
program for processing.
5
The scope of the project based on the objective above is; firstly, to identify
and determine the required program specification and available interface between
PDA and PC. Secondly is to determine the compatibility of operating system
between PDA and PC, its programming language and available development kits.
Thirdly is to develop and implement the networking model to enable data
transmission between PDA and PC using WIFI with Microsoft Visual Studio 2005 C
sharp programming integrated development environment (IDE). And finally, is to
simulate and test the program using Microsoft Windows Mobile 5.0 Software
Development Kit (SDK) emulator that runs Windows Mobile 5.0 with Virtual
Machines Network Services installed for WIFI simulation.
1.4
Project Overview
The overall block diagram representing the proposed data transmission
between PDA and PC model for barcode application is shown in Figure 1.2.
1. Barcode Image Capture
using PDA Camera
3. Router route client request to
server for processing
2. PDA barcode client transmit captured
image to server through WIFI
Figure 1.2
4. PC process request and send result
back to PDA
Block diagram of proposed PDA and PC data transmission model
A barcode image with minimum resolution of 640x480 captured by PDA
camera will be stored as .jpeg format file in PDA. This image will then be
6
transmitted through WIFI using file transfer protocol (FTP) to server program. The
role of wireless router is to route the request from client to server for processing.
After the PC receives the image, the image will be processed and ASCII code of
barcode info will be sent back to PDA through router.
The entire system uses three main components, PDA, PC and wireless router.
This configuration will allow maximum of 256 clients (PDA) connected at one time
per router. The speed of barcode decoding will vary based on the network bandwidth
and server processing power.
1.5
Problems Challenges
Today, majority barcode system is still relying on PC and wired scanner. This
system is not portable. Moreover, the existing mobile computing with wireless and
built-in scanner is very expensive. It cost around USD 1,500 per unit [10]. This cost
is too high and not economical for majority of today’s business.
Due to above problem, the main improvement needed for barcode system is
to provide an economical yet portable system for barcode scanning. The problem
that needs to be solved is how to enable wireless data transmission for PDA and PC
using WIFI on a regular PDA. However, compared to traditional barcode system,
mobile devices enable barcode system has some disadvantages that need to be solved
as below:
Limited memory and CPU – Mobile devices are usually not equipped
with the amount of memory and computational power in the CPU found
in desktop computers.
Small displays and limited input capabilities – for example, entering a
URL on a Web enabled mobile phone is cumbersome and slower than
typing with a keyboard.
Low bandwidth – in comparison to wired networks, wireless networks
have a lower bandwidth. This restricts the transfer of large data volumes.
7
Connection stability – due to fading, lost radio coverage, or deficient
capacity, wireless networks are often inaccessible for periods of time.
In order to solve limited memory and CPU processing power in mobile
barcode system, the decoding function which consumes the most processing power
will be shifted to the server. PDA will be used only to capture image, transmit image
to server and display result.
For small displays and limited input capabilities problem, it can be solved by
designing a simple yet comprehensive GUI with most frequent use button and
features required by barcode system. By having this simple GUI, it can reduce the
needs for user to type in input to operate the system. For low bandwidth problem, it
can be solved or minimized by using the minimum resolution of image required to
capture barcode.
Finally, for connection stability issue, it can be solved by integrating network
reliability checking feature into program itself to ensure there is a stable and reliable
connection before performing any transaction. In addition, packet checking algorithm
will be integrated as well to detect if there is any corrupted packet during
transmission through wireless network.
1.6
Summary
This chapter provides an overview of the barcode system, the challenges of
mobile barcode system, and its simplified implementation in barcode decoding
system. In the next chapter, the background and literature review of the key wireless
technology used in mobile barcode system will be reviewed.
CHAPTER II
BACKGROUND AND LITERATURE REVIEW
In this chapter, the background to enable mobile barcode system, including its
hardware, software and wireless transmission protocol used will be discussed. These
include Windows Mobile 5.0 operating system for PDA, Windows Mobile Software
Development Kits (SDK), Wireless Application Protocol (WAP), wireless router and
comparison between Infra-Red, Bluetooth and WIFI transmission methods.
2.1
Windows Mobile 5.0 and its Software Development Kits
Windows Mobile 5.0 was introduced by Microsoft on May 2005; it provides
increased access to rapidly improving PDA hardware capabilities including its highquality displays, cameras, increased memory sizes, and powerful communications
capabilities. The key features that are used in this project include its platform
application programming interfaces (APIs) that expose rich multimedia support, easy
interaction with device hardware such as cameras and improved communications
capabilities. This APIs will simplify the process of integrating camera and picture
functionality to barcode system in future. [10]
In addition, Windows Mobile 5.0 provides flexibility to programmer in both
native and managed versions of platform APIs. This will ease the process of
integrating the barcode encoder system that were written in C++ language with
remote procedural code that will be developed using C Sharp programming language.
[8]
9
Finally, Windows Mobile 5.0 comes with improved emulators, including a
new ARM emulator. This enables application testing with more accurate device
environment, and variety of different mobile devices environment can be tested
without physical devices. It also helps to reduce the number and level of tests that
need to be run directly on a device.
2.2
Network connections types and comparison
There are various types of established network connection to enable data
transfer between different devices such as Bluetooth, Infra-Red(irDA), Wi-Fi and
Local Area Network (LAN). Each of them has a different bandwidth, ranges,
advantages and disadvantages. Usually, type of connections is selected based on
application, environment and business needs. Below are introduction to a few key
wireless and wired network connection methods.
2.2.1
Bluetooth
Bluetooth is the industry standard for personal area network (PAN)
communication, a short-range wireless technology meant to replace wiring like
parallel cords and USB cables while maintaining high levels of security. It is named
for a short-range radio frequency (RF) technology that operates at 2.4 GHz and is
capable of transmitting voice and data. The effective range of Bluetooth devices is 32
feet (10 meters). Bluetooth transfers data at the rate of 1 Mbps, which is from three
to eight times the average speed of parallel and serial ports, respectively. [16]
Bluetooth can be used to wirelessly synchronize and transfer data among
devices. It can be thought of as a cable replacement technology. Typical uses
included automatically synchronizing data between PDA, notebook and palmtop
computers without connecting cables. It can also be used to access a network or the
internet.
10
The key features of Bluetooth technology are robustness, low power, and low
cost. The Bluetooth specification defines a uniform structure for a wide range of
devices to connect and communicate with each other. Bluetooth has achieved global
acceptance such that any Bluetooth enabled device, almost everywhere in the world,
can connect to other Bluetooth enabled devices in proximity. Bluetooth enabled
electronic devices connect and communicate wirelessly through short-range, ad hoc
networks known as Pico nets. Each device can simultaneously communicate with up
to seven other devices within a single Piconet. Each device can also belong to several
Pico nets simultaneously. Pico nets are established dynamically and automatically as
Bluetooth enabled devices enter and leave radio proximity. [6], [16]
2.2.2
Infra-red (IrDA)
IrDA stands for Infrared Data Association. The IrDA standard is a set of
specifications for providing a universal two-way wireless infrared data
communications, based on a practical cost, short-range point-to-point user model.
The standard defines the physical characteristics of the interface, the communications
protocols that provide for different needs, and the transmission speeds at which the
infrared device communicates.
The two basics of the infrared communication standards are IrDA-Data and
IrDA-Control. IrDA-Data defines the standard for the wireless, two-way infrared
data transmission between two devices and consists of a set of mandatory protocols:
PHY (Physical), IrLAP (Link Access), and IrLMP (Link Management). IrDAControl is the infrared standard that allows wireless peripherals such as keyboards,
mouse, game pads, joysticks, and other pointing devices to interact with many types
of host devices. Host devices include PCs, home appliances, game consoles, and
TV/Web set top boxes. IrDA-Control is not the same as the standard TV Remote
Control. IrDA-Control has its own set of mandatory protocols: PHY (Physical),
MAC (Media Access Control), and LLC (Logical Link Control). [16]
11
The IrDA-standard infrared connection technology key benefits include:
Offers a universal wireless standard for connecting all portable
infrared-enabled devices
Easy, effortless implementation
Economical alternative to other connectivity solutions
Reliable, high speed connection
Safe to use in any environment; can even be used during air travel
Eliminates the hassle of cables
Allows PC'
s and non-PC'
s devices to communicate with each other
Enhances mobility by allowing users to simply "plop and connect"
The standard fast infrared transmit mode (IrDA 1.1) provides capability to
transmit data up to 4 Mbits/sec while Serial Infrared transmit mode (IrDA 1.0)
provide capability of transmit data at 115.2 Kbits/sec.
2.2.3
WIFI
WIFI, or Wireless Fidelity, is a term that is used to refer to any product or
service using any type of 802.11 technologies. WIFI networks operate in the
unlicensed 2.4 and 5GHz radio bands, with IEEE 802.11b (Wireless B) that can run
at 11Mbps and the newer IEEE 802.11g (Wireless G) that can run at 54Mbps. By
comparison, Ethernet networks connect at 100Mbps. [3],[4].[6]
Both Wireless B and G can broadcast up to 150 feet. And its range can be
extended on Wireless G networks by overlapping broadcast points. This is known as
making a daisy chain. WIFI enabled devices (laptops or PDAs) can send and receive
data wirelessly from any location equipped with WIFI access. All of this wireless
access are going through access points (AP), installed within a WIFI location.
There are multiple standard of IEEE 802.11. Following are a few most
commonly and widely used standards:
12
(a)
IEEE 802.11 Standards
IEEE created the first WLAN standard in 1997. It was called 802.11. 802.11
standard works in radio signaling frequency - 2.4 GHz and only supported a
maximum bandwidth of 2 Mbps. This speed is too slow for most applications. For
this reason, ordinary 802.11 wireless products are not getting popular and it is no
longer being manufactured now. [7]
(b)
IEEE 802.11b Standards
The original 802.11 standard has being expanded by IEEE in July 1999,
creating the 802.11b specification. 802.11b supports bandwidth up to 11 Mbps,
which is more comparable to Ethernet. 802.11b uses the same radio signaling
frequency of 2.4 GHz - as 802.11 standards. Being an unregulated frequency,
802.11b gear can incur interference from microwave ovens, cordless phones, and
other appliances using the same 2.4 GHz range. However, by installing 802.11b box
a reasonable distance from other appliances, interference can easily be avoided. [7]
Below are the specifications of 802.11b standard:
Operating Frequency: 2.4GHz ISM
Transfer Rate (theoretical): 1, 2, 5.5, 11Mbps
Transfer Rate (throughput): 4Mbps (average)
Mechanism: Direct Sequence Spread Spectrum (DSSS)
Channels Available: 11 (3 non-overlapping)
Maximum Range: 175ft. (average)
The main advantages of 802.11b standards are lowest cost and its signal
range is best and is not easily obstructed. The disadvantages of 802.11b including
slowest maximum speed, supports fewer simultaneous users and appliances may
interfere on the unregulated frequency band.
13
(c)
IEEE 802.11a Standards
When 802.11b was developed, IEEE created a second extension to the
original 802.11 standard called 802.11a. 802.11a cost higher compared to 802.11b,
thus it doesn'
t gained popularity as much compared to 802.11b. Due to higher cost,
802.11a fits predominately in the business market, whereas 802.11b better serves the
home market. [7]
However, 802.11a supports bandwidth up to 54 Mbps and signals in a
regulated 5 GHz range. Compared to 802.11b, this higher frequency limits the range
of 802.11a. The higher frequency also means 802.11a signals have more difficulty
penetrating walls and other obstructions. Because 802.11a and 802.11b utilize
different frequencies, the two technologies are incompatible with each other.
Below are specifications of 802.11a standard:
Operating Frequency: 5.8 GHz
Transfer Rate (theoretical): up to 54Mbps
Transfer Rate (throughput): 20 - 36 (approximate average)
Mechanism: Orthogonal Frequency Division Multiplexing (OFDM)
Channels Available: 12 (all non-overlapping)
Maximum Range: 80ft. (average)
The main advantages of 802.11a are it provides fastest maximum speed,
supports more simultaneous users and regulated frequencies prevent signal
interference from other devices The disadvantages of 802.11a are highest cost and
shorter range signal that is more easily obstructed. [7]
(d)
IEEE 802.11g Standards
In 2002 and 2003, wireless LAN products supporting a new standard called
802.11g began to appear in the scene. 802.11g combined the best of both 802.11a
14
and 802.11b. 802.11g supports bandwidth up to 54 Mbps, and it uses the 2.4 GHz
frequency for greater range. In additional, it is backwards compatible with 802.11b,
meaning that 802.11g access points will work with 802.11b wireless network
adapters and vice versa. [7]
Below are the specifications of 802.11g standard:
Operating Frequency: 2.4 GHz
Transfer Rate (theoretical): 54Mbps
Transfer Rate (throughput): 20 - 30 (average)
Mechanism: Complimentary Code Keying (CCK), OFDM
Channels: 3 (1, 6, 11)
Maximum Range: 175ft (average)
The advantages of 802.11g include faster maximum speed, supports more
simultaneous users and signal range is best and is not easily obstructed. Its
disadvantages including higher costs compare to 802.11b and appliances may
interfere on the unregulated signal frequency. [3] [7]
2.2.4
Ethernet LAN
Ethernet has been a relatively inexpensive, reasonably fast, and very popular
LAN technology for several decades. Two individuals at Xerox PARC, Bob Metcalfe
and D.R. Boggs developed Ethernet beginning in 1972 and specifications based on
this work appeared in IEEE 802.3 in 1980. Ethernet has since become the most
popular and most widely deployed network technology in the world. [2]
Ethernet LAN typically uses coaxial cable or special grades of twisted pair
wires. Ethernet uses the CSMA/CD access method to handle simultaneous demands.
The most commonly installed Ethernet systems are called 10BASE-T and provide
transmission speeds up to 10 Mbps. Devices are connected to the cable and compete
15
for access using a Carrier Sense Multiple Access with Collision Detection
(CSMA/CD) protocol. [1] [2]
Fast Ethernet or 100BASE-T provides transmission speeds up to 100
megabits per second and is typically used for LAN backbone systems, supporting
workstations with 10BASE-T cards. Gigabit Ethernet provides an even higher level
of backbone support at 1000 megabits per second (1 gigabit or 1 billion bits per
second). 10-Gigabit Ethernet provides up to 10 billion bits per second. [2]
Naturally, Ethernet LAN is more secure compare to any wireless LAN. In
addition it is able to provide the highest data transfer rate compare to any other
wireless LAN. Its main disadvantage is not portable as it required wired to work.
2.2.5
Comparison table for Bluetooth, Infrared, WIFI and Ethernet LAN
Bluetooth, infrared, WIFI and Ethernet LAN are designed specifically for
different purpose and set of customer although they all are for data transmission
purpose. As shown in table 2.1, we can see that Bluetooth and Infrared have a
medium connection bandwidth. Both of these connections are design to enable quick
and fast connection in a simple network model. Their usage is usually for one-to-one
connection between mobile devices.
Wireless B and Wireless G are designed for multi users and it provides
reasonable fast bandwidth for most application. In addition, it allows expansion on
number of connections by overlapping access point.
16
Table 2.1
Connection
Types
Bluetooth
Bandwidth and range comparison between various connections types
Bandwidth
1Mbit/s
Type &
Wireless
- Support maximum 7 connections per Piconet
30 feet
- Future replacement for serial and parallel cable
115kbits
Infrared
(irDa 1.0)
Wireless
4Mbps
30cm
(irDA 1.1)
Wireless B
11Mbps
General Info
Range
Wireless
150feet
- Short-range
- Point-to-point user model
- Only two devices can connected at one time
- WIFI. Works with wireless G network
- WIFI. The fastest, most advanced wireless network
Wireless G
54Mbps
Wireless
available.
150feet (can
- Support multiple connection maxes up to 32 per
be daisy-
access point.
chained for
- One Wireless G router which has three channel can
more)
have 3 access point and connections up to 96 (3 x
32) connections
Ethernet
10Mbps to
Wired
- most inexpensive, fast and popular LAN
LAN
1000mbps
(max 30m)
- The most secure and established LAN
2.3
Wireless Application Protocol (WAP)
WAP is an abbreviation for Wireless Application Protocol, and simply put, it
is what makes it possible to access the Internet via wireless devices such as mobile
phones and personal digital assistants (PDAs). There are millions of mobile phones
all over the world, and they are being used by everyone from executives to taxi
drivers. With WAP, each of those phones can be used for comparing prices, selecting
products, purchasing, and tracking orders. [5]
17
2.3.1
What is WAP?
WAP is the set of rules governing the transmission and reception of data by
computer applications on, or via, wireless devices like mobile phones and PDAs. As
a matter of fact, WAP is not actually one single protocol. It is a collection of
protocols and specifications that cover everything from how the WAP device and the
user agent should work, to how the transport protocols interact with the bearers
themselves. [18]
WAP is a standardized technology for cross-platform, distributed computing,
very similar to the Internet’s combination of Hypertext Markup Language (HTML)
and Hypertext Transfer Protocol (HTTP), except that it includes one vital feature:
optimization for low-display capability, low-memory, and low-bandwidth devices,
such as personal digital assistants (PDAs), wireless phones, and pagers.
The major accomplishment of WAP is that it has managed to overcome the
drawbacks of handheld devices:
Small screens.
Limited free memory to run applications
Limited CPU capacity
Lower bandwidth.
WAP allows wireless devices to view specifically designed pages from the
Internet, using only plain text and very simple black-and-white pictures. The WAP
programming code at the Web site has to be explicitly designed and written for the
micro-browser used in that specific model of WAP device. The pages themselves
have to be small, because the data speed on mobile phones is limited—a lot slower
than a domestic modem. Also, the WAP-enabled devices have screens of different
shapes and sizes, so the same page can look very different depending on the actual
device you are using, quite independently of the version of the micro-browser being
used in the phone or PDAs itself. [17]
18
2.3.2
Open Systems Interconnection (OSI) Model for Wireless Communication
The basic construction of WAP architecture can be explained using the model
shown in Figure 2.1. The order of the independent levels which is a hierarchy has the
advantage that the system is very flexible and can be scaled up or down. There are
five different levels or stacks called the "WAP Stack" as shown below: [18]
Application Layer: Wireless Application Environment (WAE)
Session Layer: Wireless Session Protocol (WSP)
Transaction Layer: Wireless Transaction Protocol (WTP)
Security Layer: Wireless Transport Layer Security (WTLS)
Transport Layer: Wireless Datagram Protocol (WDP).
WAE User Agents
Wireless Application Environment (WAE)
Wireless Session Protocol (WSP)
Protocol
Layers
Wireless Transaction Protocol (WTP)
Service
and
Application
Wireless Transport Layer Security (WTLS)
UDP
Figure 2.1
WDP
OSI Model of Wireless Application Protocol
Each stack overlaps with the stack below. This stack architecture makes it
possible for software manufacturers to develop applications and services for certain
stacks. They may even develop services for stacks which are not specified yet.
The WAP stack is an entity of protocols which cover the wireless data transfer. The
diagram above shows the order of the different stacks and their protocols. This
includes the stacks responsible for the layout as well as the stacks responsible for the
actual data transfer. The highest level or stack is the one which deals with the layout.
A lower stack is responsible for the transfer and the security through WTLS
(Wireless Transport Layer Security). All stacks lower than this one are being called
19
network stack. Due to this hierarchy of stacks any changes made in the network
stacks will have no influence over the stacks above. The following sections will
explain in detail the functionality of each stack. [5] [17] [18]
2.3.2.1 Application Layer (WAE and WTA)
The environment for wireless applications (Wireless Application
Environment WAE) and the application for wireless phones (Wireless Telephony
Application WTA) are the highest layer in the hierarchy of WAP architecture. These
two are the main interface to the client device, which give and control the description
language, the script language of any application and the specifics of the telephony.
WAE and WTA have only a few easy functions on the client device, like the
maintenance of a history list, for example. [18]
2.3.2.2 Session Layer (Wireless Session Protocol WSP)
The Wireless Session Protocol (WSP) has all the specifications for a session.
It is the interface between the application layer and the transfer layer and delivers all
functions that are needed for wireless connections. A session mainly consists of 3
phases: start of the session, transferring information back and forth and the end of the
session. Additionally, a session can be interrupted and started again from the point
where it was interrupted.
WSP provides the upper-level application layer of WAP with a consistent
interface for two session services. The first is a connection-mode service that
operates above a transaction layer protocol WTP, and the second is a connectionless
service that operates above a secure or non-secure datagram transport service.
The Wireless Session Protocols currently offer services most suited for
browsing applications. WSP provides HTTP 1.1 functionality (it is a binary form of
20
HTTP) and incorporates new features such as long-lived sessions, a common facility
for data push, capability negotiation and session suspend/resume. The protocols in
the WSP family are optimized for low-bandwidth bearer networks with relatively
long latency. Requests and responses can include both headers and data. WSP
provides push and pull data transfer WSP functions on the transaction and datagram
services.
Messages can be in connection mode or connectionless. Connection mode
messages are carried over WTP. In this case the protocol consists of WTP protocol
messages with WSP PDUs as their data. Connectionless messages consist only of the
WSP PDUs. [18]
2.3.2.3 Transaction Layer (Wireless Transaction Protocol WTP)
The specifications for the transfer layer are in the Wireless Transaction
Protocol (WTP). Like the User Datagram Protocol (UDP), the WTP runs at the head
of the datagram service. Both the UDP and the WTP are a part of the standard
application from the TCP/IP to make the simplified protocol compatible to mobile
terminals. WTP supports chaining together protocol data and the delayed response to
reduce the number of transmissions. The protocol tries to optimize user interaction in
order that information can be received when needed.
The WTP provides the services necessary for interactive browsing
applications. During a browsing session the client requests information from a server
and the server responds with the information. This is referred to as a transaction.
WTP runs on a datagram service and possible a security service.
Advantages of WTP include:
Improved reliability over datagram services
Imported efficiency over connection oriented services
As a message oriented protocol, it is designed for services oriented towards
transactions.
21
WTP has 3 kinds of transaction services as below:
Class 0 Unreliable invoke messages with no result messages
Class 1: Reliable invoke messages with no result messages
Class 2: Reliable invoke messages with exactly one reliable result message.
The main features of WTP including reliability achieved by using unique
transaction identifiers, acknowledgements, duplicate removal and retransmissions. It
has no explicit set up or tears down phases. And, concatenation may be used to
convey multiple PDUs in one service data unit of the datagram transport. The basic
unit of interchange is an entire message, not a stream of bytes. Its mechanisms are
provided to minimize the number of transactions replayed as a result of duplicate
packets. [18]
2.3.2.4 Wireless Transport Layer Security WTLS
The Wireless Transport Layer Security (WTLS) is an optional layer or stack
which consists of description devices. A secure transmission is crucial for certain
applications such as e-commerce or WAP-banking and is a standard in these days.
Furthermore WTLS contains a check for data integrity, user authentication and
gateway security.
WTLS is a protocol is an extension of TLS protocol. It is used with the WAP
transport protocols and has been optimized for use over narrow-band communication
channels. The WTLS layer is above the transport protocol layer. The required
security layer of the protocol determines whether it is used or not. It provides a
secure transport service interface that preserves the transport service interface below;
additionally it provides an interface for managing secure connections. WTLS aims to
provide privacy, data integrity and authentication between two communication
applications. Among its features are datagram support, optimized handshaking and
dynamic key refreshing. It is optimised for low-bandwidth bearer networks with
relatively long latency.
22
The WTLS Record Protocol is a layered protocol. The Record Protocol takes
messages to be transmitted, optionally compresses the data, applies a MAC, encrypts,
and transmits the result. Received data is decrypted, verified, and decompressed, then
delivered to higher-level clients. Four record protocol clients are described in the
WTLS standard; the change cipher spec protocol, the handshake protocol, the alert
protocol and the application data protocol. If a WTLS implementation receives a
record type it does not understand, it ignores it. Several records can be concatenated
into one transport SDU. For example, several handshake messages can be transmitted
in one transport SDU. This is particularly useful with packet-oriented transports such
as GSM short messages. [17] [18]
2.3.2.5 Transport Layer (Wireless Datagram Protocol WDP)
The Wireless Datagram Protocol (WDP) represents the transfer or
transmission layer and is also the interface of the network layer to all the above
stacks/layers. With the help of WDP the transmission layer can be assimilated to the
specifications of a network operator. This means that WAP is completely
independent from any network operator. The transmission of SMS, USSD, CSD,
CDPD, IS-136 packet data and GPRS is supported. The Wireless Control Message
Protocol (WCMP) is an optional addition to WAP, which will inform users about
occurred errors. [18]
2.4
Wireless Access point vs Ad-hoc Network
Wireless networking can be categorized into two main categories. One is
infrastructure based network which is called as access point and the other one is Adhoc network which work without any fixed infrastructure. [7]
23
2.4.1
Wireless Access Point Networks
Wireless access point (WAP or AP) is a device as shown in Figure 2.2 (a)
that connects wireless communication devices together to form a wireless network. It
acts as a bridge between the wired network and wireless devices. It allows multiple
devices to connect through it. It can relay data between wireless devices and wired
devices. Several WAPs can link together to form a larger network that allows
"roaming". Wireless access points have IP addresses for configuration. [15]
(a)
(b)
Figure 2.2
Wireless AP device and its adapters
In order to connect to wireless AP, portable devices have a built-in wireless
adapter or external adapter as shown in Figure 2.2 (b). Wireless AP connection
model are different from ad hoc network. It is a centralized network connection as
shown in Figure 2.3.
Wireless Access Point
Wireless connection
Network Boundary
Figure 2.3
An example of wireless access point network model
24
In Figure 2.3 network, wireless AP will manage connection to each portable
device individually. An IP address will be allocated to this device when they connect
through a “Dynamic Host Configuration Protocol” (DHCP) server. Number of
connections to wireless AP varies from Wireless B to Wireless G and Wireless A.
Wireless A is design for corporate user which can handle high number of
connections per access point, while wireless B and wireless G support fewer
connections per access point. [16]
WAP allows expansion by using wireless bridges as shown in Figure 2.4. A
bridge can connect two or more wireless networks in a large corporate, across the
street or campus. Bridges attach network together through point-to-point or point-tomultipoint connections. By increasing number of AP, the number of connections per
network can be increased accordingly in a multiple of 32 for wireless B and wireless
G and multiple of 64 for wireless A.
Access Point A
Access Point B
Figure 2.4
Access Point C
An example of overlap access point to cover wider range and users
25
2.4.2
Ad Hoc Networks
An ad hoc network is a collection of two or more devices equipped with
wireless communications and networking capability. Such devices can communicate
with another node that is immediately within their radio range (peer-to-peer
communication) or one that is outside their radio range (remote-to-remote
communication) using intermediate node(s) to relay or forward the packet from the
source (sender) towards the destination (receiver). [12]
An ad hoc wireless network is self-organizing and adaptive. This means that a
formed network can be de-formed on-the-fly without the need for any system
administration. The ad hoc network can be heterogeneous, i.e., the nodes can be of
different types (PDA, laptop or mobile phone) with different computation, storage
and communication capabilities. See Figure 2.5 for details. [12].[13]
Wireless connection
Network Boundary
Figure 2.5
An example of ad hoc network model
As an ad hoc wireless network, it does not rely on any fixed network entities;
the network itself is essentially infrastructureless. Ad hoc network rely on forwarding
data packets sent by other nodes, this method consume a lot of power. [13]
Typically ad-hoc networks are established among small number of stations,
for a specific purpose and for a short period of time. Since they are setup as a quick
alternative to the infrastructure network, they are usually not protected and generally
26
violate most of the security policies. They lack good authentication mechanism for
users to participate in the network and also lack encryption mechanism for data
transfer, thus risk exposing important information. If the mobile clients participating
in the ad-hoc network are also connected to the wired network then the entire
network data is at risk.
2.5
Development and Deployment: Tools, Emulators & Devices
The design and implementation of mobile applications is not straightforward
as desktop applications. Usually, programmer can'
t easily estimate the risk of a
project due to the difficulties to compare the various capabilities of existing software
platforms for mobile devices. Beside this, the design and implementation of user
interfaces for mobile devices and applications is very different from what is done for
desktop PCs due to the different form factors and context of use. [14],[15]
Development Environment
Smart Devices Extensions
Visual Studio .Net 2005
Mobile Barcode Client
development with offline
capability
.NET Compact Framework
.NET Framework
ActiveSync/
Ethernet
On-screen device
emulators using
WM5.0 SDK
Deployment Environment
Figure 2.6
Development and Deployment Environment, Tools and Devices
However, for windows mobile 5.0 there are established tools set to ease the
development process that tackle most of the issue in windows mobile CE and
27
windows mobile 2003. From Figure 2.6, there are two environments, one is the
development environment and other is the deployment environment. At initial stage,
PDA client program can be developed and tested without a physical device in
development environment. An emulator will be used to simulate the mobile
applications. This method of development has been proven to improve the
development process and debug capability. In addition, developer can avoid the
hassle of downloading the program to mobile devices for testing and debug.
After the program has been tested and worked well in emulator, developer
can deploy it through the deployment environment. In this environment, mobile
applications will be tested in a real device. At the same time, developer can still
debug and view the process of code running in mobile device using debugger from
PCs.
Based on development models in Figure 2.6, a single integrated development
environment (IDE) can be used for both barcode client and server applications. This
indirectly can promote single language programming for both applications. And, at
the same time it provides the capability to enable code reuse across platform. If
without this capability, barcode client can only be developed using embedded C that
is design for mobile device instead of C sharp programming language.
2.6
Summary
In this chapter, all the tools, methodology and protocol that will be used in
this project including WIFI, WAP protocol, development environment and
deployment methodology has been discussed. In next chapter, algorithm use to
enable client and server connection, program flowchart and high level mobile
barcode working model will be explained in detail.
CHAPTER III
DATA TRANSMISSION USING WIFI
This chapter presents the detail on how wireless data transmission between
PDA and PC for barcode application is being established, remote procedural calls,
the research methodologies used for the entire projects and high level components
used in the entire pocket mobile barcode system.
3.1
Pocket Barcode Reader Software Design
The Pocket Barcode Reader data transmission using WIFI modules is written
using object-oriented design programming method. It promotes reusability of module,
self contain objects and ease the debugging process as each individual module can be
modified and updated independently.
The entire Pocket Barcode Reader System consists of two projects in
Microsoft Visual Studio 2005 as below:
The Pocket Barcode Reader client that runs on Pocket PC and uses the .NET
Compact Framework, and
The Pocket Barcode Server that runs on PC and uses full .NET Framework.
29
3.1.1
High Level System Model
Figure 3.1 shows that the pocket barcode reader application contains three
main components, client module, server module and common module. Each of these
modules has its own functionality and they communicate to each other logically
while client and server socket connect to each other through WIFI network.
Common
Client
Global Network Setting
Network Terminator
Encoding System
Decoding System
Socket Callback
XML Writer
Figure 3.1
PDA
GUI
Client
Notification
Client Socket
Server
PC
GUI
Server Socket
Server
Notification
Barcode Decoder System
High Level System Model of Pocket Barcode Reader
Both server and client use the common module which contains all the
necessary network protocol and helper classes needed by both server and client. Due
to this fact, the common module is placed in another directory and a link to both
projects is being created to promote sharing and ensure both projects use the same
protocol to communicate with each other through socket, save configuration in the
same format and use the same method to encode and decode data.
30
3.1.2
Client module key features and functionality
The pocket barcode reader client module main function is to provide user the
ease to use GUI to capture image and custom control button as shown in Figure 3.2.
Image capture using camera is displayed and stored in memory prior to any
transmission to server. Image will only be transmitted to server when user clicks the
“Send” button. All events status that is triggered by user action or during
transmission will be reported on status reporting bar real-time.
Image capture
from camera
String return from
barcode server
Status reporting bar
Figure 3.2
Pocket Barcode Reader Startup GUI
The “Send” and “Connect” button are sensitive to network connection. When,
the client is not connected, “Send” button is disabled as no transmission can be done
without establishes connection. “Connect” button is enabled when there is no
connection between barcode client and barcode server. It will be disabled
31
automatically when the barcode client successfully establish a connection to barcode
server.
The “options” button will display another screen that shows the program
version, developer name and an editable IP address drop down lists for user to
change the server IP address.
Figure 3.3
Pocket Barcode Reader “Options” GUI
As shown in Figure 3.3, the drop down lists contains number from 0 to 255.
This is to ease user when they need to enter IP address on PDA that does not have
keyboard. Once this IP address is entered, it will be automatically save to XML
configuration file when “ok” button on top of menu is clicked.
32
Table 3.1
Pocket Barcode Reader Application states and error code
States
Connected to server
Offline
Comment
Connection between server and client has been
established and ready for data transmission
No connection
Sent barcode image
Server receive barcode image
Image has been successfully send from client
to server
Server receive image and successfully return
result to client
Server didn’t receive image and return a
Server didn’t receive barcode image failure code where success variable is set to
false
Pocket barcode reader will display this
message when the following events occur:
- Connection between server and client broke
Socket error
- Server access denied
- Socket buffer overflow
- Unable to find specify server
- Unable to establish connection
- Unknown error
Table 3.1 shows all the possible messages and states that will be reported on
status bar during program execution. This includes messages for barcode data
transmission event and when any unexpected error is detected. The simplify
messages is displayed on the status bar and detail error will be displayed on text box
to help user understand and fix the problem.
33
3.1.2.1 Pocket Barcode Reader Client Class diagram
PocketBarcodeReader
GUI
btnClear_Click()
btnOptions_Click()
btnSend_Click()
ConnectToServer()
DisconnectFromServer()
NotifyCallback()
ShowOptionsForm()
UpdateButtons()
ProcessClientSocketCmd()
OptionsForm
GetDefaultAddress()
GetHostAdress()
LoadSettings()
SaveSettings()
OptionsForm()
OptionsForm_Closing()
OptionsForm_Load()
Global
Global()
SettingsDefault
GetInt()
GetString()
GetValue()
Registry()
Configuration
Configuration()
GetFilePath()
GetInt()
GetString()
Read()
RestoreDefault()
SetValue()
Write()
Inheritance
Uses
Figure 3.4
IpAddress
PortNumber
Registry
Values
Remarks:
SettingKeys
ClientSocket
ClientSocket()
Connect()
ConnectCallback()
Receive()
ReceiveCallback()
ReceiveExec()
Send()
SendCallback()
SendFile()
Network
CheckForTerminator()
GetBytes()
GetInt32()
WriteInt32()
WriteString()
Class Diagram of Pocket Barcode Reader
34
Figure 3.4 shows the detail class diagram connection in pocket barcode
reader application. Pocket Barcode Reader GUI and Options form are classes
inherited from Microsoft System.Windows.Forms class. It extends the feature from
System.Windows.Forms by adding function to the forms, button and picture box.
The functions will be called when there is any event occur on the forms like when
buttons is clicked, form is being closed and etc.
OptionsForm and ClientSocket classes are being used by Pocket Barcode
Reader main form as an object. Before Pocket Barcode Reader can use any methods
in both of the forms, it needs to instantiate an object of OptionsForm and
ClientSocket. Once the object has been instantiated, Pocket Barcode Reader can start
calling method or function in OptionsForm and ClientSocket classes. Multiple
objects can be instantiated based on the need. For example, the pocket barcode reader
can establish multiple connection to a server by establishing multiple client socket
and each socket will create a different port that connect to the server in parallel.
Other classes like SettingKeys, Registry, Global, SettingDefaults and
Network are support classes that do not require instantiation of object before use.
They can be used directly as all methods in this class are static. They provide
constant data like the IpAddress, port number, the keys to be used in XML
configuration file, network terminator bytes, method to get static data like the file
path and etc. Among all the support classes, only Configuration class requires object
instantiation. This is because each ClientSocket will have its own settings that need
to tie to Configuration. Thus, the ability to provide multiple configurations for
multiple different ClientSocket is required.
35
3.1.2.2 ClientSocket Class
The ClientSocket class is a wrapper to System.Net.Socket namespace. This
socket class has several methods, properties and constructors. The first step to
establish a connection is to create socket object based on this class. The following
code segment shows how to create the socket:
_socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
The first parameter specified is the address family which will later be used in
data transmission. InterNetwork option is being selected as the AddressFamily in this
project as it is referring to the IPv4 network, the most common standard used in
today network world. Other options available included NetBios, IPv6, AppleTalk,
FireFox and etc. The next argument specify the socket type used. In this project, a
reliable two way connection is needed in the socket for the application to
communicate in both way directly. In this case the stream socket is used instead of
the unreliable connectionless sockets – datagrams. Finally, the TCP is specified as
the protocol to be used in this application data transmission. TCP is selected because
it has built in data error checked and it is more reliable compared to UDP protocol.
Once the socket has been created, a connection to the server is needed since
TCP is a connection based communication protocol. In order to connect to the server,
the IP address and port of the server is required. In .NET framework, there is a class
under the System.Net namespace called IPEndPoint which represents a network
computer as an IP address and port number. The IPEndPoint has two constructors. It
takes a IP address and Port number and another takes long and port number. Since
this project is a client server based project, and we know the IP address of the server,
so, we will used IP address and Port number as the constructor. Below is a sample of
how an IPEndPoint constructor is called:
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
36
As shown in the code segment, the first argument given is the ipAddress
followed by the port number. However, before the ipAddress is provided, we need to
parse it using methods provided by IPAddress class to convert it from string to actual
IP address. Below are the code segment used to establish connection to server.
IPAddress ipAddress = IPAddress.Parse(address);
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
_socket = new Socket(AddressFamily.,
SocketType.Stream, ProtocolType.);
_socket.BeginConnect(endPoint, _connectCallback, null);
The above code segment is the most fundamental code needed to establish
connection to the server before any data can be transmitted. If the provided
ipAddress and port are correct, connection will be established successfully. If the
Server is not running then an exception called SocketException will be thrown.
Below are the exceptions that will be thrown if the server is not running or client
socket unable to reach the server due to security issue.
"No connection could be made because the target machine actively refused it."
Similarly, it the connection to server somehow dies, the following exception
will be thrown and data transmission in both ways will be stopped.
"An existing connection was forcibly closed by the remote host"
Table 3.2 below shows a summary of class method and type available in
ClientSocket class.
Table 3.2
ClientSocket class method and type
Method
Type
ClientSocket
Public
Connect
Public
Comments
Default method used when ClientSocket Class
is instantiated
Establish connection to specify IP address and
37
port and set type of connection to TCP
Disconnect
Public
Connected
Public
Send
Public
Receive
Public
SendFile
Public
Shutdown socket and close all connection
gracefully.
Function to check if the socket is still connected
or not. This method will return Boolean value
Reset async event and after sent data and then
send terminator bytes to stop the transmission
Listener to socket port for any result return
from server
Read from file stream (Image file), concatenate
terminator bytes and send to server
Executes function when server returns result.
ReceiveExec
Public
Pass data received from server to
ProcessCommand
Remove network terminator bytes and raise
ProcessCommand
Private
RaiseNotifyEvent
Private
Call respective notify event and pass data to it
ConnectCallback
Private
Async callback when socket connected
SendCallback
Private
Async callback when socket send completed
ReceiveCallback
Private
Async callback when socket receive completed
notify event
Method like Send, Receive, SendFile and Connect are wrapper on top of
System.Net.Sockets namespace. All of these methods use asynchronous method to
communicate to server. Detail on asynchronous socket will be discussed in later
session.
RaiseNotifyEvent, ConnectCallback, SendCallback and receiveCallback are
methods that tie to asynchronous socket connection and will be activated when there
is an event in socket. It is declared as private method as it is not needed by other
class and internal to ClientSocket class only. The major function of this callback is to
38
provide status to application on what is going on and result of data transmission
between the client and server.
3.1.2.3 Sending Image from Pocket Barcode Reader to Barcode Server
The Pocket Barcode Reader send file to server through SendFile method
provided by the ClientSocket class module. Below is the code segment that shows
how the SendFile method is used by the client to send file to the server when “Send”
button is clicked.
_client.SendFile(sImageLocation);
The _client is an object created once the connection is established. The
SendFile method takes a string of image location where the image file located to be
sent to the server.
In the SendFile method in ClientSocket class, the image file will be opened
and put into FileStream called fs before sending to server.
FileStream fs = new FileStream(_sFileName,FileMode.Open);
byte[] barcodeImage = new byte[fs.Length];
fs.Read(barcodeImage,0,barcodeImage.Length);
_socket.Send(barcodeImage);
_socket will then call Send method from the ClientSocket to the server. Once
the image transfer bytes from bytes to server is completed, _socket will then call
another BeginSend to send a network terminator bytes to server to notify that the
data transmission has completed.
_socket.BeginSend(Network.TerminatorBytes, 0,
Network.TerminatorBytes.Length,
SocketFlags.None, _sendCallback, true);
39
The first argument used to notify the ending of the transmission is the
Terminator bytes defined in the Network class, followed by its length and a method
tie to it to inform client when the server receives the final bytes from the client.
3.1.3
Server module features and functionality
The Pocket Barcode Server key functions is to receive image from client,
decode it and return an ASCII code to client with information extracted from the
barcode. Once Pocket Barcode Decoder is activated; it will actively listen to port
13200 on its address. In order to connect to server, the client must initiate connection
through the same port number.
Figure 3.5
Pocket Barcode Server GUI
Figure 3.5 shows total of five tabs available to display information in server
GUI that are required to provide detail view on data transmission between client and
server. However, all these tabs can be disabled in real application as the purpose of
the server is to extract image barcode and return information to client. No user
interference is required at the server side other than starting up the daemon. In this
project, all the information like barcode image receive from server, ASCII code, the
40
decoder result and data to send back to PDA are displayed to ease the debugging
process and to show detail of data that transmitted to client and received from client.
The bottom part of the GUI show the status of the server application, when
startup the server will show that it is listening for client at its IP address for example
at 202.87.223.150. This IP address will change accordingly depending on the IP
address that was assigned to the server operating system.
In the server application, the socket processes are schedule to run in other
threads of system to prevent GUI from lagging while waiting for socket to return it
results. Multi threaded programming method was used to ensure that the application
is able to handle multiple connection and startup multiple connection to listen and
process request from client. As the nature of server is to provide service to client, it
has an all time a live process that listen to client.
41
3.1.3.1 Pocket Barcode Server Class diagram
PocketBarcodeServer
GUI
btnClear_Click()
btnOptions_Click()
btnSend_Click()
ConnectToServer()
DisconnectFromServer()
NotifyCallback()
ShowOptionsForm()
UpdateButtons()
ProcessClientSocketCmd()
Global
ServerSocket
Global()
SettingsDefault
Configuration
Values
Configuration()
GetFilePath()
GetInt()
GetString()
Read()
RestoreDefault()
SetValue()
Write()
SettingKeys
Remarks:
Inheritance
Uses
Figure 3.6
IpAddress
PortNumber
ServerSocket()
Start()
Stop()
Restart()
Listen()
Send()
SendCallback()
ReceiveFileStream()
ProcessCommand()
RaiseNotifyEvent()
DecodeBarcode()
Network
CheckForTerminator()
GetBytes()
GetInt32()
WriteInt32()
WriteString()
Class Diagram of Pocket Barcode Server
From Figure 3.6 shows that there are total of 6 classes developed in server
application. Classes that require instantiation of objects include the
42
PocketBarcodeServer GUI and ServerSocket class. An object needs to be created for
both of these classes before its function can be used.
The PocketBarcodeServer GUI is an inherited class from
Systems.Windows.Forms. It extends class from forms to create tab, button, picture
box and text box for server GUI application. The GUI class also uses ServerSocket,
Global and SettingKeys class. Once the application startup, the GUI main form will
create an object from ServerSocket and named it as _listen to listen to port 13200 for
any connection from client.
SettingDefault and Configuration are support classes to Global class, while
Network class is a support class to ServerSocket class. All of these support classes
are static classes that do not require instantiation of object and can be used directly
except the Configuration class which requires an object to be instantiated before use.
3.1.3.2 ServerSocket class
ServerSocket class is a wrapper on top of System.Net.Socket namespace. It is
coded using connection oriented networking model. The server listener socket is
activated and sends to run at the background as a thread that is active at all time until
a connection is established. Shown below is how the listener process is sent to the
thread pool.
// create a new thread that handle client connection
ThreadPool.QueueUserWorkItem(new WaitCallback(Listen));
System.Threading namespace is used to enable multithreaded programming
in this application. From the code segment, the Listen process is sent to the
ThreadPool queue. This type of coding will ensure the GUI of the application will
not become irresponsive while waiting for the socket to listen to any connection from
client.
43
Table 3.3
ServerSocket class method and type
Method
Type
ServerSocket
Public
Comments
Default method used when ServerSocket Class
is instantiated
Responsible to listen to port 13200 while there
Listen
Private
is no connection to server. Process command
and response to client request once connection
is established
Start
Public
Check connection status, start a new thread of
Listen socket when called.
Close _socket socket connection and _listen
Stop
Public
socket connection. Shutdown both ways of
transmission, send and receive.
Restart
Public
Call Stop and then Start to restart the socket
connection.
Send data from extracted barcode info, items
Send
Public
name and price. Add terminator bytes to the end
of the sending string to notify client on data end
point.
Create file stream to store data receive from
ReceiveFileStream
Public
client and save it to a file in system. Once
complete raise a notify command to inform
server.
Remove network terminator bytes, convert the
ProcessCommand
Private
data to array of bytes and invoke notify event
that data has been received for further
processing.
DecodeBarcode
Public
Call BarcodeDLL to decode the image and
return a string of barcode information.
44
Table 3.3 shows the main methods provided by the ServerClient class. Listen,
Start, Stop, Restart and Send are a wrapper method of System.Net.Socket. Where as,
Listen and ProcessCommand are private methods that provide support to the
ServerClient class. DecodeBarcode is a function that used BarcodeDLL library to
extract barcode information from the bitmap file.
3.1.3.3 Sending ASCII Code back to Pocket Barcode Reader
Once the server receive image from Pocket Barcode Reader it will invoke a
few methods before sending back the result. The following code segments show the
details.
string sBarcode = _server.DecodeBarcode(
Global.GetBarcodeImagePath());
string sendBack = GetItemNameAndPrice(sBarcode);
First, the DecodeBarcode method from the ServerSocket is called to the
barcode data. Then, the barcode data is sent to GetItemNameAndPrice method to
retrieve the relevant barcode information from the server. Once the information is
available, it is ready to be sent back to Pocket Barcode Reader. Before sending the
information, the result is being encoded to ASCII code as shown in the following
code.
ASCIIEncoding asen = new ASCIIEncoding();
byte[] dataToSend = asen.GetBytes(sendBack);
_server.Send(dataToSend);
Once the result is converted to ASCII bytes, it will be sent to the Pocket
Barcode Reader using the Send method provided by the ServerSocket. The Send
method will then add terminator bytes, check the result of the transmission and
perform necessary validation to ensure the result is successfully transmitted to the
client through WIFI network.
45
3.1.4
Common module
There are variables and methods that are common to both client and server
programs in this design. It is listed in Table 3.4 and Table 3.5. In order to enable
sharing of common methods and variable between client and server application, the
Configuration and Network class are shared. They are linked to each of the projects
and can be used by calling Common namespace.
In client and server programs, there are a few other different classes that are
grouped together with Configuration and Network classes as a common namespace
to provide support to its main program. However they are not shared between client
and server like the Configuration and Network classes. For example, Global,
SettingDefaults, SettingKeys and Registry classes are specified to Pocket Barcode
Reader application only. Pocket Server has all the classes except Registry class
which is not needed. However, all the classes are defined differently and serve
different purpose compared to Pocket Barcode Reader class.
Table 3.4
Configuration class method and type
Method
Type
Configuration
Public
SetValue
Public
Comments
Default method called when configuration is
instantiated
Update internal list value and configuration file
if autowrite configuration setting is true
Return specified configuration as integer. When
GetInt
Public
the value is loaded from configuration, it is a
String type
Read
Public
Write
Public
Read XML configuration file and populate the
list with value from configuration file.
Write setting like IpAddress and Port into the
specified XML configuration file.
46
Restore default configuration specified by
RestoreDefault
Public
SettingsDefault class and remove the
configuration file previously saved.
GetFilePath
Public
Return path where the program execute. This
path is then used to store the configuration file.
Table 3.4 shows all methods provided by the Configuration class. All the
methods in this class can be used after the Configuration class is instantiated as an
object. This configuration class is able to provide configuration or setting to multiple
socket when instantiate as different object to be used in different socket connection.
Table 3.5
Network class method and type
Method
Type
Comments
Return the terminator string used for both
Terminator
Public
TerminatorBytes
Public
CheckForTerminator
Public
GetInt32
Public
Return data in 32 integer format
GetBytes
Public
Convert data to bytes and return its value
WriteInt32
Public
WriteString
Public
client and server program
Return terminator string in an ASCII bytes
form
Routine to check whether the terminatorbytes
is a valid terminator or not.
Convert integer 32 data to bytes form and write
it to memory stream
Convert string data to bytes form and write it to
memory stream
Table 3.5 shows methods that are available in Network class. All the methods
shown are static methods that can be used directly from Pocket Barcode Reader and
Pocket Server socket class without instantiation of objects. This Network class are
shared between Pocket Barcode Reader and Pocket Server application because both
of the application needs to know the exact same terminator bytes used in application
in order to determine the ending point of one data transmission. The
47
CheckForTerminator method is used recursively while receiving data. Once the
terminator bytes matched, the CheckForTerminator will return a Boolean value true.
3.2
Asynchronous socket connection
In this project, both Pocket Barcode Reader and Pocket Barcode Server
exchanged data using an asynchronous method over the TCP sockets. Both of the
GUI’s are not blocked because the operation of the socket is always running in
separated system supplied threads.
Both the ClientSocket and ServerSocket classes use the asynchronous socket
methods provided by the System.Net.Sockets namespace. The following table shows
the keys main methods used by both classes.
Table 3.6 Asynchronous methods used in ClientSocket and ServerSocket Class
Socket method
Comments
BeginConnect
Requests a connection to the server.
BeginSend
Sends the data (barcode image) to the server.
BeginReceive
Receives the acknowledgment from the server.
Shutdown
Prepares the socket to be shutdown by sending and
receiving any data on the socket.
Close
Closes the socket and frees up any underlying
resources.
When each of the methods is called, an AsyncCallback delegate is passed to
it and it will be invoked when the socket operation has completed. Through this
delegate, the operation status of the socket can be tracked and status of the socket can
be updated to user accordingly when the operation completed.
48
3.3
Summary
This chapter explained the design of Pocket Barcode Reader and Pocket
Server applications in an object oriented way. Most of the key features and methods
of each class used in the applications are also elaborated. This includes how the class
can be used and their relationships between each other are clearly explained. Next
chapter will discuss on how the above application is being simulated in Windows
Mobile 5.0 Pocket Emulator and the detail on the environment used and its
configuration.
CHAPTER IV
SIMULATION ENVIRONMENT AND RESULT
This chapter presents the simulation environment and result from simulation
using Pocket PC emulator for both Pocket Barcode Reader and Server applications.
The simulation is done to prove that the written application is working as expected
and it is able to provide mobile Pocket PC with limited processing power the
capability to utilize PC to perform more CPU and memory intensive tasks.
4.1
Simulation Environment Setup and Configuration
The Pocket Barcode Reader and Pocket Barcode Server are coded and tested
using Microsoft Visual Studio 2005 version 8.0.50727.42 and Microsoft .Net
framework version 2.0.50727. Both of these applications are bundled together with
Microsoft Visual Studio .Net 2005 Professional license to Intel. However, any other
compatible version can be used to simulate and test these Pocket Barcode
applications.
After installation of Microsoft Studio .Net 2005 Professional, some plug-in
from Microsoft like the Windows Mobile 5.0 Emulator and Virtual Private Network
Service is required to enable simulation. Both of these applications are free ware that
can be downloaded from Microsoft web sites. A proper steps to install the plug-in is
required to enable working Virtual Private Network, else, the emulator will prompt
to not able to enumerate the network.
50
4.1.1
Windows Mobile 5.0 Emulator
Windows Mobile 5.0 Emulator comes together with Windows Mobile 5.0
Software development kits for Pocket PC. It can be downloaded from Microsoft
Windows Mobile web sites under the “Download Categories” and “Mobile Devices”.
Prior to installation of this software development kits, Visual Studio 2005 Standard
or higher version must be installed.
Once the installation is completed, the mobile devices need to be configured
through Visual Studio interfaces by going to Tools
Options and Select Devices as
show in Figure 4.1 below:
Figure 4.1
Mobile Devices Configuration page in Visual Studio 2005
From Figure 4.1, there are multiple platforms of devices that can deploy the
application, including Pocket PC 2003, Smart Phone 2003, Windows CE 5.0 and
Windows Mobile 5.0 Pocket PC. In this project, we are interested on Windows
Mobile 5.0 Pocket PC Emulator, so we set this device as the default device for
simulation. Once the device is selected, we need to set the properties including its
RAM size, preferred Network Connection method and etc.
51
Once the properties button is clicked, the following figure that enable setting
path of the device image, transport type and bootstrapper will be shown.
Figure 4.2
Windows Mobile 5.0 Pocket PC Emulator properties window
The output location will specify where to install the program that we going to
deploy into the device emulator. This output location also applicable to actual device
when it is deployed through active sync. Usually, program is deployed to the selected
area, the “Program File Folders”.
The Transport is the method used to transfer the application to the devices
and the Bootstrapper is the boot up code use in ARM processor. In this simulation,
we will use the default parameter set which is the DMA Transport and provided
device emulation startup code.
The most critical configuration to enable proper WIFI network simulation is
located under the “Emulator Options” button. Figure 4.3 shows the available function
and configuration tabs that can be used to set the memory size, display and preferred
network connection method.
52
Figure 4.3
Windows Mobile 5.0 Pocket PC Emulator General Properties
In the emulator properties, we need to specify the shared folder for access to
file in PC to get the sample barcode images. Once the shared folder is specified, the
emulator will access the shared folder as storage devices like memory card that are
plug in to PDA physically.
The minimum memory requirement on device for proper simulation of the
entire program is 128MB. This 128MB RAM will be used as storage area for
program, files and Pocket PC default program.
Once the shared folder and memory is set, we need to specify the network
card that the emulator will use for connection to PC and internet. This option is
available at the “Network” tab. We need to enable NE2000 PCMCIA network
adapter and bind it to connected network card. However, there is an option to select
either physical network card or Wireless network card, we can also allow the
emulator to automatically select any available network connection by selecting
“Connected network card” as shown in Figure 4.4.
53
Figure 4.4
Windows Mobile 5.0 Pocket PC Emulator Network Properties
The other two network adapters, “CS8900 network adapter” and “Host-only
networking” shown in Figure 4.4 are not required in this simulation. It is just an
alternative option to enable emulator to connect to PC for network simulation. Prior
to enabling any of the above network adapters, a virtual network driver is required.
Virtual network service detail will be explained in next topic.
4.1.2
Virtual Machine Network Service
Virtual Machine Network Service is the most critical service to enable
wireless network simulation in Pocket PC emulator. Prior to any connection between
PC and the Pocket PC emulator through network, the Virtual Machine Network
Service driver must be installed.
The Virtual Machine Network Service will enable device emulator operating
system to emulate its own network connection virtually. This is achieved when the
virtual machine network service virtualized the host machine and enables the
54
capability of multiple IP address to be assigned to each of the virtual machines like
Pocket PC emulator. The IP address assigned to the virtual Pocket PC emulator is
different from the host machine IP address, thus it suits the need of this Pocket
Barcode Reader program that will generate a different IP address for client and
server program.
4.1.2.1 Virtual Machine Service Installation and Verification
The Virtual Network Machine Service driver version 2.4.0.24 released on 19
September 2003 is an unsupported driver from Microsoft available for free. It can be
downloaded at:
http://www.microsoft.com/downloads/details.aspx?familyid=dc8332d6-565f-4a57be8c-1d4718d3af65&displaylang=en
Once the download of the netsvwrap.msi is completed, it can be installed directly
through the standard installation process.
Figure 4.5
LAN properties after installation of Virtual Machine Network
55
After the installation, the virtual machine network service will be available at
the local area network connection items as shown in Figure 4.5. This service must
also be enabled in LAN properties to allow the virtual machine network service to
function properly.
Once the installation of both Virtual Network Machine Service and Pocket
PC emulator are completed we can start to connect to the device to verify the success
of installation. There are multiple ways to connect to device including through Visual
Studio Tool
Tools
Connect to Device or using Device Emulator Manager. Both
yield the same result. Once we choose to connect to device, a list of devices that are
available will be displayed as shown in Figure 4.6.
Figure 4.6
List of Windows Mobile Pocket PC devices
In this project, the Pocket Barcode Reader application are simulated using
emulator, thus we choose “Windows Mobile 5.0 Pocket PC Emulator” as the devices
to be simulated. Once the device is selected, it can be connected using the “Connect”
button as shown in Figure 4.6.
56
Internet connection
Figure 4.7
Network connection
Pocket PC Emulator start up page
Figure 4.7 shows the startup page of the Pocket PC emulator. There are two
symbols that this project is interested on, which is the network connection and the
internet connection status symbol. If these symbols are as shown in Figure 4.7, it
shows that the virtual network connection has been successfully setup.
The Internet connection shown that the devices are able to access to internet,
where as the network connection meant that the device are able to send and transmit
file through network between the host PC and the emulator. The network connection
is critical here as it enables the device to connect to PC for sample barcode images.
57
The IP address of the device emulator can be determined by going to Start
Settings, follow by select “Connections tabs” and click on “Network card”. The
network adapter that has been binded to emulator is the NE2000 Compatible
Ethernet Driver. Select the NE2000 Compatible Ethernet Driver as shown in Figure
4.8.
Figure 4.8
Pocket PC Emulator Network Setting Properties
From Figure 4.8, the IP address assigned to the emulator are automatically
from the DHCP server directly. It contains the same subnet mask and domain as the
host IP address, but with different address. This IP address will be captured by the
Pocket Barcode Server once the Pocket Barcode Reader application make a
connection to the server application.
58
4.2
Deployment of Pocket Barcode Reader to Emulator
The pocket barcode reader can be deployed directly to the emulator through
the Microsoft Visual Studio 2005 Deploy Solution function. By selecting, Build
Deploy Solution, the solution will be automatically built and deployed to the device
emulator directly. The executable of the program will be located at the “Program File
Folders” of the Pocket PC emulator as specified in the devices configuration menu in
earlier stage.
Once the deployment successfully completed, the emulator will automatically
startup the program. Thus, the simulation, debug and testing of the pocket application
can be carried out.
4.3
Simulation result and analysis
4.3.1
Pocket Barcode Reader Client Application
The Pocket Barcode Reader application has been designed with simple and
easy to use GUI for convenience of the user and to fix into the small screen factor
Pocket PC. It has built in system to determine the previous configuration and
network connection state.
In the initial startup, the program will check for availability of previous
configuration. If the configuration is not available, the application will prompt user
to enter the necessary information for the application to function properly. If user
selected “Yes”, the program will automatically load the options form instead of the
main pocket barcode form for user to enter the IP address require to connection to the
server application. If “No” is selected, user will be directly to the main form with the
“Send” button disabled as there is no connection can be established without server IP
address.
59
(a)
Figure 4.9
(b)
Pocket Barcode Reader Options Form
Figure 4.9 (a) shows the prompt asking the user whether the user would like
to enter the IP address during a clean initial startup of the program. Figure 4.9(b)
shows the options form after the user selects “Yes”. The options has four drop down
box for the user to select the server IP address on Pocket PC that does not have a
proper keyboard to enter the value. After all the values of IP address are entered, the
user can click “ok” on top right of the screen to continue. The program will
automatically connect to the server if the entered IP address is a valid and accessible
address.
Figure 4.10 (a) and (b) shows the detail screen and connection status of the
Pocket Barcode Reader application after the user has entered the IP addresses and
click “ok” to confirm it. The “Send” button is being disabled before the connection
establishes and it will be automatically enabled after the connection to server is
completed successfully.
60
Client socket contacting
server and trying to
establish connection.
“Send button is disabled
(a)
Figure 4.10
Client socket successfully
connected to server and
ready to transmit data.
“Send” button is enabled
(b)
Pocket Barcode Reader connecting to server
Once connection to server is successfully established, the client program can
start transmitting picture to server by clicking on the picture box to load picture and
then followed by “Send” button. Figure 4.11 is the file folder that will be displayed
Figure 4.11
Pocket Barcode Reader Image file selection box
61
after user click on the image box. Picture will be loaded for display on the image box
after user selects the picture as shown in Figure 4.12(a).
(a)
Figure 4.12
(b)
Pocket Barcode Reader load image and send to server
Figure 4.12(b) shows the return result from server with barcode, item and
price details after user click the “Send” button to send to server for decode and
extract item information. Once the barcode result is return, it shows that the program
has completed one transaction in getting the barcode image send to server, decode
barcode information and display the ASCII code from PC on Pocket PC.
4.3.2
Pocket Barcode Server Application
This section will explain and show the detail on Pocket Barcode Server
application that is responsible to decode the barcode image receive from server
automatically and return the ASCII code back to Pocket PC once the decoding and
data extraction are done.
62
Server IP address, where it start
listening to any connection from
client actively once program start
up
Figure 4.13
Initial start up of Pocket Barcode Server application
Figure 4.13 shows the screen of initial start up of Pocket Barcode Server
application. The program like any other server will actively listen to any connection
from its client on its IP address.
Client IP addresses and port number
where the server connected to.
Figure 4.14
Pocket Barcode Server after connected to client
Once there is a connection to client, the server will display the IP address and
the port number of the connected client as shown in Figure 4.14. No other connection
is allowed when there is already a connection between the client and server. With
this connection, the server is ready to serve the client and transmit data between the
client and server.
63
Figure 4.15
Pocket Barcode Server “Barcode” Tab
Once the image is transmitted from Pocket Barcode Reader, it will be
displayed immediately on the “Barcode” Tab as shown in Figure 4.15. Then, the
application will perform the decoding, data extraction and conversion of any string to
ASCII code to be transmitted back to Pocket Barcode Reader application.
Figure 4.16 shows the ASCII code and its size that will be transmitted back to
Pocket Barcode Reader. This information is obtained after the server completed the
barcode decoding and data extraction from simple database created in the server
application.
Figure 4.16
Pocket Barcode Server “ASCII” Tab
64
Figure 4.17
Pocket Barcode Server “Decode” Tab
The “Decode” Tab shows in Figure 4.17 display the information of the
decoded barcode portion. It also recorded down all the previous transaction barcode
information and time when the transaction occurs for tracking purpose.
Figure 4.18 shows the detail information of the extracted barcode information
that will be sent back to Pocket Barcode Reader. This information has been
formatted and can be displayed directly in Pocket Barcode Reader application
without any further processing. In this tab, the previous decoded information is also
recorded for tracking purpose.
Figure 4.18
Pocket Barcode Server “SendToPDA” Tab
65
Figure 4.19
Pocket Barcode Server “About” Tab
Finally, the “About” tab shown the information of version, developer and
copyright of the application.
4.4
Sample barcode images simulation
Both the Pocket Barcode Reader and Pocket Barcode Server applications
have been tested and verified using multiple sample barcode images to prove the
system is working. The system is working perfectly and expected in all the sample
barcode images simulation.
The simulation uses images from various different sample barcodes with
different image properties, including glossy barcode images, blur barcode images,
low contrast images, dark image and etc as shown in Figure 4.20. All the images are
bitmap images that can be processed directly by the decoder system.
66
(a) Glossy barcode
(c) Distorted barcode
(b) Distorted barcode
(d) National Instrument barcode
67
(e) blur barcode
(g) Metal surface barcode
(f) Plastic surface barcode
(h) Dark surface barcode
68
(i) Normal surface barcode
(k) Reflective surface barcode
Figure 4.20
(j) Dirty surface barcode
(l) Reflective surface barcode
Various type of barcode images simulation
69
4.5
Summary
This chapter explained and discussed on the environment setup and
configuration for Pocket Barcode application simulation and the simulation results
using a few sample pocket barcode images. The simulation successfully showed
positive result. All sample barcode images were successfully decoded and detail of
the item information has been extracted from simple database for transmit back to
Pocket PC for display.
CHAPTER V
FUTURE WORKS, DISCUSSION AND CONCLUSION
The design and simulation of Pocket Barcode Reader application shows that
the wireless Pocket Barcode system are usable and are able to provide effective yet
low cost system in today businesses. It successfully overcomes the limited CPU
processing power, low memory and small screen resolution problems in mobile
devices.
5.1
Future works
5.1.1
Improvement on Pocket Barcode Reader
The current Pocket Barcode Reader application does not have a connection to
the Pocket PC camera, thus it is not able to capture any image directly from Pocket
PC camera when deploy on actual devices. This feature needs to be enabled when
there is a physical device available by calling the .NET compact camera API. The
API should be used to enable picture from camera display on the main form of the
Pocket PC. Once user presses the “Send” button, it should automatically capture the
image and send to server for decoding.
During offline mode where there is no wireless connection available, the
Pocket Barcode Reader application should be designed to save the captured image in
a temporary area. Once there is a wireless connection, the Pocket Barcode Reader
71
software should automatically connect to the server, retrieve and process all the
captured image and return the information needed by the user.
Finally, the Pocket Barcode Reader application can include some encryption
method to ensure the data is encrypted before sending through the network. This is to
ensure that critical business transaction is secured and safe from information thief.
However the encryption from the client application should be kept simple and
simplify to reduce the processing time. In addition, the encryption key should be
changeable based on user request.
5.1.2
Improvement on Pocket Barcode Server
The key improvement require on Pocket Barcode Server application is the
ability to accept multiple clients at one time. The server should have databases of
client IP address and port number that connected to it. Thus, it can differentiate
which client is making request and where the result should be sent back. A simple
hash keys that hold the information should be sufficient in this case. However, a
listener socket should be enabled all time. When multiple connections is allowed, the
server program should set some limit to number of connection and enable multi
threaded method in processing multiple clients request in parallel. This is to ensure
the response time to each of the client is not impacted when server is busy processing
request.
Secondly, the Pocket Barcode Server application should integrate widely
industry use database like Microsoft SQL or MySQL to store information of barcode
and detail items information and pricing. This is to ensure all the information
requires are able to store in more organized way and it is able to retrieve immediately
when needed.
Finally, for the encryption system, the server should also include some
mechanism to encrypt the ASCII code that it will send back to the Pocket Barcode
Reader. Encryption will get more complicated when there is a multiple clients with
72
different encryption keys set. The server should have a method to differentiate the
encryption key from client or design a common encryption method that is applicable
to all clients when receiving information from server.
5.1.3
Overall system improvement
To ensure this system is relevant and applicable to today world, it should be
integrated with other Point of Sales System like UBS, Aplus, Quicken and etc. In
today business, a complete solution for the entire business is required. With the
mobile capability that is built into the application, it should be able to provide better
and yet efficient solutions for future businesses.
5.2
Discussions
Mobile devices and application are getting more and more popular in today’s
world. With Pocket Barcode Reader application in place, it will add more value to
today’s mobile devices. This includes enabling users to extract information from
barcode on the fly and get up-to-date information directly from database through
WIFI network.
There are many ways of enabling data transmission between PDA and PC
through WIFI. This includes multiple sockets connection and multiple pipe transfer
to improve the data transfer rate. In current application, the image size used for
simulation is from 200k to 1.5 MB. The transfer time is about 1 to 8 seconds per
picture depending on the size. This timing is an approximation because the emulator
transfer rate is also depending on the host CPU processing power. If faster host PC is
used to run the emulator, faster result may be obtained.
Temporary buffer to store data transferred through socket can influence the
speed of the transmission. The current size set in application is 1024 bytes buffer size.
73
Buffer size is important in application design. Too small buffer size will cause buffer
overrun problem, while too large buffer size will slow down the speed. A balance
between the size and speed is required depending on the type of data and its size to
be transferred through the network.
The Virtual Machine Network Service driver used to simulate the WIFI
network is an unsupported driver from Microsoft; it is sometime not reliable and will
break if there is an issue with network connection or DHCP server. However, the
problem can be resolved by reinstalling and reconfigure it when it breaks. Once the
reinstallation and configuration is completed, a machine restart is required to flush
out the previous settings that are still resided in the system.
5.3
Pros and Cons of the software design
The advantages of the Pocket Barcode Reader is it is able to send capture
image directly to Pocket Barcode Server through the WIFI network and get the
decoded data back in real time. This will ensure user gets the latest and updated
information from server. In addition, it’s built in automated network connection and
detection system makes it easy and convenience for user to use and reduce the need
for more complicated GUI at PDA.
From the software perspective, the Pocket Barcode Reader application is
written in a way such that it uses less memory and disk space. The total size of the
compiled and able to execute program is only 22 kilobytes. Thus this software can
run on any system with minimum of 16 MB memory. It uses less system resource, so
it will not consume the entire Pocket PC processing power and memory. This will
enable user to perform other task at the same time while running the Pocket Barcode
Reader application at the background.
For the Pocket Barcode Reader application, the main disadvantage is it is not
able to process any barcode images when there is no wireless network connection
74
available. The software will not be able to decode the barcode or provide any offline
capability to save the image for processing at later time.
For the Pocket Barcode Server application, it is only able to handle one
connection at a time. Thus, if multiple clients require connection at the same time, it
will not be able to accept it. This is the current limitation of the server application
where after a successful connection is made to one client, the Pocket Barcode Server
sockets stops listening to the port for any other connections. This prevents other
client to make connection to it.
5.4
Summary and Conclusion
This project has successfully achieved its goal by enabling wireless data
transmission using WIFI from PDA to PC for barcode application. Its successfully
solve the limited memory and processing power issues in mobile devices by
transmitting the picture from mobile devices to PC for decoding and processing.
The entire system has been tested and simulated with multiple difference type
of barcode images. The results obtained are promising. The concept of the client
server model for Pocket Barcode System is working well as expected. The objectives
of this project defined earlier are fully met. Besides that, the barcode decoder system
has been successfully integrated to the system to form a complete barcode system.
As a conclusion, the objectives of this project have been achieved by enabling
client server socket model to transmit data through WIFI for Pocket Barcode
application.
75
REFERENCES
1.
James F, Kurose & Keoth W.Ross, Computer Networking: A top down
approach featuring the internet, Addison-Wesley, Chap 1: 49,64 Chap. 2:
103-105,Chap3: 196-248, Chap 7: 604-610 2002
2.
Stallings, Data & Computer Communications, Prentice Hall, Chap.2: 2744, 2004, Chap 17: 543,563 7th ed.
3.
Neil Reid and Ron Seide, 802.11 (Wi-Fi) Networking Handbook,
McGraw-Hill, 2003
4.
Marcel van der Heijden et al, Understanding WAP: Wireless Applications,
Devices and Services, Artech House, Chap. 1, 2000
5.
Lee, Stephen, WAP: A Beginner’s Guide, McGraw-Hill Profesional, Chap.
1: 18-39, Chap. 4: 70-81, 2001
6.
Stefano Basagni, Mobile Ad Hoc Networking, John Wiley & Sons, Chap.
1:19,47, Chap. 3: 69, 89, 2004
7.
Janice Reynolds, Going Wi-Fi: A Practical Guide to Planning and
Building an 802.11 Network, CMP Books, 2003
8.
Suddeth, Jeffery, Programming C# with Visual Studio .NET 2005, Lulu
Press Incorporated, 2006
9.
Mark Ridgeway, .NET wireless Programming, Sybex, 2002
76
10.
Barcoding Corp, Mobile Computers with Wireless Barcode Scanners,
http://www.barcoding.com/wireless/wireless_barcode_scanners.shtml ,
10 September 2006
11.
Stuart J. Barnes and Eusebio Scornavacca, Unwired Business: Cases in
Mobile Business, Idea Group Publishing, Chap. V:66-77 2006
12.
Lujun Jia et al, Ad Hoc network topology control and routing, SPAA, pg
220-221, June 2003
13.
Jinyang Li, Charles Blake et al, Capacity of Ad Hoc wireless networks,
M.I.T laboratory of computer science, pg 61, 2001
14.
Microsoft, Introduction to Windows Mobile Programming,
http://www.microsoft.com/windowsmobile/default.mspx, 15 September
2006
15.
Axmor, Pocket PC Development, http://www.axmor.com/pocketpcdevelopment.aspx, 21 September 2006
16.
Lewis, Barry, Wireless Networks for Dummies, John Wiley & Sons, Chap.
4:61-82, 2004
17.
Furht Borivoje, Wireless Internet Handbook: Technologies, Standards
and Application, Auerbach Publishers Incorporated, pg18-23, 2004
18.
Chen, Lei Da, Mobile Commerce Application Development, Cybertech
publishing, pg22-34, Dec 2005.
19.
Joel Murach, murach’s C# 2005, Mike Murach & Associates,
Incorporation, chap 9, pg244-250, chap 6 pg 154-166, chap23 pg720-738,
2006
77
20.
Arora, Geentanjali, Microsoft C# Professional Projects, Course
Technology, chap 6 93-106, 2002
21.
Hunter, David, Beginning XML (3rd Edition), John Wiley & Sons, Part
IV, pg435-469, 2005
22.
Blum, Richard, C# Network Programming, Sybex Incorporated, chap 5
pg 167-207, 2002
23.
Lee, Wei Meng, .Net Mobile Web Developer’s Guide, Syngress
Publishing, Chap 4 pg 173-186, 2002
78
APPENDIX A
POCKET BARCODE READER SOURCE CODE
i. Main From
/*****************************************************************
*
* MainForm of Pocket Barcode Reader Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: Main form of pocket barcorde reader application
*
that call all the sub function when user click
*
on GUI. It also process command from socket to
*
display the status of network connection.
*
****************************************************************/
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
Common;
namespace PocketBarcodeReader
{
public partial class MainForm : Form
{
// Instantiate new socket communications for client (PDA
client barcode program)
ClientSocket _client = new ClientSocket();
// Place holder for event handler request from socket
EventHandler _processCommand;
// Variable to hold socket notification arguments for
processing
NotifyCommand _notifyCommand;
79
// Object variable to hold address where the notification
argurment and data is stored
object _notifyData;
// Variable to store image location each time new image is
loaded
// Can be used to store path to where camera image is
captured
string sImageLocation;
private System.Windows.Forms.OpenFileDialog openFileDialog;
public MainForm()
{
InitializeComponent();
this.Closing += new
System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.openFileDialog = new
System.Windows.Forms.OpenFileDialog();
}
// Shows option form for user to enter IP address when
"Options" button is clicked
// or when program load up without IP address configure
private void ShowOptionsForm()
{
OptionsForm form = new OptionsForm();
form.ShowDialog();
}
private void btnOptions_Click(object sender, EventArgs e)
{
ShowOptionsForm();
}
// The main entry point for the pocket barcode application
[MTAThread]
static void Main()
{
Application.Run(new MainForm());
}
private void MainForm_Load(object sender, System.EventArgs e)
{
// Prompt user if server ip address is not set
// This prompt will only be shown in first use before
the configuration file is saved
// IP address is considered empty if it match with
0.0.0.0 - defined in Global.cs module
if (Global.Configuration.GetString(SettingKeys.IpAddress)
== Global.Const.EmptyAddress)
{
if (MessageBox.Show(
"Would you like to set the server IP address
now?",
this.Text, MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1) ==
DialogResult.Yes)
{
80
ShowOptionsForm();
}
}
// Setup callbacks
_client.Notify += new
ClientSocket.NotifyEventHandler(NotifyCallback);
_processCommand = new EventHandler(ProcessSocketCommand);
// Enable command buttons
UpdateButtons();
// Connect to server when first startup
ConnectToServer();
}
// Close main form and exit program
private void MainForm_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
DisconnectFromServer();
}
private void NotifyCallback(NotifyCommand command, object
data)
{
try
{
lock (this)
{
_notifyCommand = command;
_notifyData = data;
Invoke(_processCommand);
}
}
catch
{
}
}
private void ConnectToServer()
{
// only connect if user has set the server ip address
if (Global.Configuration.GetString(SettingKeys.IpAddress)
== Global.Const.EmptyAddress)
{
textBox1.Text = "Need to set the server IP address.";
return;
}
statusBar1.Text = "Connecting to server ... ";
_client.Connect(
Global.Configuration.GetString(SettingKeys.IpAddress),
Global.Configuration.GetInt(SettingKeys.PortNumber));
}
private void DisconnectFromServer()
{
statusBar1.Text = "Offline";
_client.Disconnect();
81
}
// Process socket notification, executes on GUI's thread
private void ProcessSocketCommand(object sender, EventArgs
args)
{
string status = "";
switch (_notifyCommand)
{
case NotifyCommand.Connected:
bool connected = (bool)_notifyData;
status = connected ?
"Connected to server" :
"Offline";
break;
case NotifyCommand.SentData:
status = "Sent barcode image";
_client.Receive();
break;
case NotifyCommand.ReceivedData:
// bool success = (bool)_notifyData;
bool success = true;
byte[] dataReceived = (byte[])_notifyData;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dataReceived.Length; i++)
sb.Append(Convert.ToChar(dataReceived[i]));
textBox1.Text = sb.ToString();
status = success ?
"Server received barcode image" :
"Server did not receive barcode image";
break;
case NotifyCommand.Error:
textBox1.Text = "Socket error\r\n" +
(string)_notifyData;
DisconnectFromServer();
break;
}
UpdateButtons();
statusBar1.Text = status;
}
private void UpdateButtons()
{
btnSend.Enabled = _client.Connected;
btnConnect.Enabled = !btnSend.Enabled;
}
private void btnConnect_Click(object sender, EventArgs e)
{
ConnectToServer();
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
statusBar1.Text = "Sending ASCII code ... ";
82
string str = textBox1.Text;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] dataToSend = asen.GetBytes(str);
// To send text file, use this method
// _client.Send(dataToSend);
// Sending file and shown path of file to send
textBox1.Text = "sending " + sImageLocation;
_client.SendFile(sImageLocation);
}
catch (Exception ex)
{
statusBar1.Text = "Error";
textBox1.Text = ex.Message;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Save file location for use when user click send
// When camera is integrated, this should be updated
// accordingly
openFileDialog.Filter = "Bitmap files
(*.bmp)|*.bmp|All files (*.*)|*.*";
sImageLocation = openFileDialog.FileName;
pictureBox1.Image = new Bitmap(sImageLocation);
// Clear text box once there is a new image loaded
textBox1.Text = "";
}
}
}
}
83
ii. Options Form
/*******************************************************************
***
*
* Options form of Pocket Barcode Reader Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: Options form display all the possible IP address
*
in drop down box for convenience of user when they
*
need to enter a new IP address for connection
*
to server program. If there is a configuration file
*
options form will load the configuration from XML
file
*
********************************************************************
**/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using Common;
namespace PocketBarcodeReader
{
public partial class OptionsForm : Form
{
public OptionsForm()
{
InitializeComponent();
this.Closing += new
System.ComponentModel.CancelEventHandler(this.OptionsForm_Closing);
this.Load += new
System.EventHandler(this.OptionsForm_Load);
}
// Get the path where the program store when form load
// This variable is needed later to store the configuration
file
private void OptionsForm_Load(object sender,
System.EventArgs e)
{
AssemblyName name =
Assembly.GetExecutingAssembly().GetName();
// Initialize fields with configuration from config file
save if any
LoadSettings();
}
84
private void OptionsForm_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
// Save configuration to config file using XML format
SaveSettings();
}
//
// Helper methods
//
// Save configuration to XML config file
private void SaveSettings()
{
// IP address that were selected in drop down box
Global.Configuration.SetValue(SettingKeys.IpAddress,
string.Format("{0}.{1}.{2}.{3}",
listAdd1.SelectedIndex,
listAdd2.SelectedIndex,
listAdd3.SelectedIndex,
listAdd4.SelectedIndex));
}
private void LoadSettings()
{
// Initialize IP address in droplist values
for (int i = 0; i <= 255; i++)
{
listAdd1.Items.Add(i);
listAdd2.Items.Add(i);
listAdd3.Items.Add(i);
listAdd4.Items.Add(i);
}
// IP address
string adr =
Global.Configuration.GetString(SettingKeys.IpAddress);
// If user has not specified an address, try to
determine the
// ip address of the server or get default address
if (adr == Global.Const.EmptyAddress)
adr = GetDefaultAddress();
try
{
// Select values in drop lists
string[] parts = adr.Split('.');
if (parts.Length == 4)
{
listAdd1.SelectedIndex =
Convert.ToInt32(parts[0]);
listAdd2.SelectedIndex =
Convert.ToInt32(parts[1]);
listAdd3.SelectedIndex =
Convert.ToInt32(parts[2]);
listAdd4.SelectedIndex =
Convert.ToInt32(parts[3]);
}
85
}
catch
{
// invalid ip address
}
}
// Returns default system IP address
private string GetDefaultAddress()
{
return Global.Const.EmptyAddress;
}
// Return ip address for the specified host
private string GetHostAddress(string host)
{
string result = Global.Const.EmptyAddress;
try
{
// Get ip address for the host
IPHostEntry entry = Dns.GetHostByName(host);
if (entry != null)
result = entry.AddressList[0].ToString();
}
catch
{
// Could not resolve host
}
return result;
}
}
}
86
iii. ClientSocket class
/*****************************************************************
*
* ClientSocket Class for Pocket Barcode Reader Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: ClientSocket class is responsible to perform
*
data sending and receiving using socket. An object
*
of ClientSocket must be instantiated before use.
*
ClientSocket class uses method from Network,
Configuration
*
and Global class. It also responsible to hookup
*
all the network callback for status update
*
****************************************************************/
using
using
using
using
using
using
using
using
using
using
using
System;
System.Net;
System.Net.Sockets;
System.Threading;
System.IO;
System.Text;
System.Configuration;
System.Collections.Generic;
System.Diagnostics;
System.Windows.Forms;
Common;
namespace PocketBarcodeReader
{
// Type of notify command allowed and declared
public enum NotifyCommand
{
Connected,
SentData,
ReceivedData,
Error
}
public class ClientSocket
{
public delegate void NotifyEventHandler(NotifyCommand
command, object data);
public event NotifyEventHandler Notify;
// Place hold the temporary socket that exchanges
information with server
Socket _socket;
// Holds information sent back from server in buffer
byte[] _readBuffer = new byte[1];
// Asynchronous method used to synchronize the shutdown
process, terminate
// any pending async calls before Disconnect returns
87
ManualResetEvent _asyncEvent = new ManualResetEvent(true);
// Default disconnecting to false
bool _disconnecting = false;
// async callbacks objects
AsyncCallback _connectCallback, _sendCallback;
public ClientSocket()
{
// Hookup async callbacks
_connectCallback = new AsyncCallback(ConnectCallback);
_sendCallback = new AsyncCallback(SendCallback);
}
// Connect to specified address and port number
public void Connect(string address, int port)
{
// Make sure disconnected before attempt to make any
connection
Disconnect();
// Connect to the server with specified IP address and
port
IPAddress ipAddress = IPAddress.Parse(address);
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
_socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_asyncEvent.Reset();
_socket.BeginConnect(endPoint, _connectCallback, null);
}
public void Disconnect()
{
// Return right away if have not created socket
if (_socket == null)
{
return;
}
// Set this flag so client will not raise any error
notification
// events when disconnecting from barcode server
_disconnecting = true;
try
{
// Shutdown the socket from send and receive - both
way
_socket.Shutdown(SocketShutdown.Both);
}
catch { }
try
{
// Then, close the socket which terminates any
pending
// async operations
_socket.Close();
// Wait for any async operation to complete
_asyncEvent.WaitOne();
88
}
catch { }
_disconnecting = false;
}
// Returns true if the socket is connected to the server.
The property
// Socket.Connected does not always indicate if the socket
is currently
// connected, this polls the socket to determine the latest
connection state.
public bool Connected
{
get
{
// Return right away if have not created socket
if (_socket == null)
{
return false;
}
// The socket is not connected if the Connected
property is false
if (!_socket.Connected)
{
return false;
}
try
{
// Poll for error to see if socket is connected
or not
return !_socket.Poll(1, SelectMode.SelectError);
}
catch
{
return false;
}
}
}
public void Send(byte[] data)
{
_socket.BeginSend(data, 0, data.Length,
SocketFlags.None, null, null);
_asyncEvent.Reset();
_socket.BeginSend(Network.TerminatorBytes, 0,
Network.TerminatorBytes.Length,
SocketFlags.None, _sendCallback, true);
}
public void SendFile(string _sFileName)
{
// PocketPC .NET compact framework doesn't accept
SendFile api.
// thus we need a customize Send method to send image
file
89
// The following method is not allowed in .NET compact
framework
// _socket.SendFile(_sFilename, null, null,
TransmitFileOptions.UseDefaultWorkerThread);
FileStream fs = new FileStream(_sFileName,FileMode.Open);
byte[] barcodeImage = new byte[fs.Length];
fs.Read(barcodeImage,0,barcodeImage.Length);
_socket.Send(barcodeImage);
// Async send of binary data to server.
// Terminator bytes was appended at the back of the
binary stream
// for server to identify end of file sending and return
result
_socket.BeginSend(Network.TerminatorBytes, 0,
Network.TerminatorBytes.Length,
SocketFlags.None, _sendCallback, true);
// Close file handle
fs.Close();
}
// Start a thread to listen and wait for result from server
after
// image is sent
public void Receive()
{
ThreadPool.QueueUserWorkItem(new
WaitCallback(ReceiveExec));
}
// Read data from server
public void ReceiveExec(Object state)
{
_asyncEvent.Reset();
// _socket.BeginReceive(_readBuffer, 0,
_readBuffer.Length,
//
SocketFlags.None, _receiveCallback, null);
// reset everything for the next read message
bool bReadMessage = true;
int bytesRead = 0;
int totalBytes = 0;
// hold incoming data
byte[] buf = new byte[1024];
MemoryStream streamRead = new MemoryStream();
while (bReadMessage)
{
// loop the reads incoming message
// buf is temp holder and the MemoryStream
// contains all of the bits
bytesRead = _socket.Receive(buf);
if (bytesRead > 0)
{
streamRead.Write(buf, 0, bytesRead);
90
bReadMessage
= !Network.CheckForTerminator(streamRead.ToArray());
totalBytes += bytesRead;
}
else
{
// client disconnected
// Restart();
throw (new Exception("Client disconnected."));
}
}
// done reading incoming message, now process the
command
ProcessCommand(streamRead);
streamRead.Close();
}
// Process command based on data received
private void ProcessCommand(MemoryStream streamRead)
{
try
{
// Remove message terminator before data is used
streamRead.SetLength(streamRead.Length Network.Terminator.Length);
// Get the command data
streamRead.Position = 0;
byte[] data = streamRead.ToArray();
RaiseNotifyEvent(NotifyCommand.ReceivedData, data);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
// Raise notification event
private void RaiseNotifyEvent(NotifyCommand command, object
data)
{
// the async operation has completed
_asyncEvent.Set();
// don't raise notification events when disconnecting
if ((this.Notify != null) && !_disconnecting)
Notify(command, data);
}
// Async callbacks when connection successfully
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Pass connection status with event
_socket.EndConnect(ar);
RaiseNotifyEvent(NotifyCommand.Connected,
this.Connected);
}
catch (Exception ex)
{
91
RaiseNotifyEvent(NotifyCommand.Error, ex.Message);
}
}
// Async callback when sending complete
private void SendCallback(IAsyncResult ar)
{
try
{
// Pass status of send event and raise notification
_socket.EndSend(ar);
RaiseNotifyEvent(NotifyCommand.SentData, null);
}
catch (Exception ex)
{
RaiseNotifyEvent(NotifyCommand.Error, ex.Message);
}
}
// Async callback when receive complete
private void ReceiveCallback(IAsyncResult ar)
{
try
{
_socket.EndReceive(ar);
// The barcode server sends an acknowledgement back
// that is stored in the read buffer
// We assumpt once receive the ASCII code, server
has
// successfully receive the image.
RaiseNotifyEvent(NotifyCommand.ReceivedData,
_readBuffer[0] == 1 ? true : false);
}
catch( Exception ex)
{
RaiseNotifyEvent(NotifyCommand.Error, ex.Message);
}
}
}
}
92
APPENDIX B
POCKET BARCODE SERVER SOURCE CODE
i. Main form
/*****************************************************************
*
* MainForm of Pocket Barcode Server Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: Main form of pocket barcorde server application
*
are responsible to call functions that are required
*
to process and decode request from client.
*
It will automatically display the underlying process
*
and status of request processing. Historical data
will
*
also be displayed for tracking purpose.
*
****************************************************************/
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace BarcodeServer
{
public partial class MainForm : Form
{
// data received over socket
byte[] dataReceived;
string sDataToSendBack;
string sExtractedBarcode;
// network communication
ServerSocket _server = new ServerSocket();
// Control.Invoke callback, used to process the
// socket notification event on the GUI's thread
93
delegate void ProcessSocketCommandHandler(NotifyCommand
command, object data);
ProcessSocketCommandHandler _processCommand;
private System.Windows.Forms.OpenFileDialog openFileDialog;
public MainForm()
{
InitializeComponent();
this.Load += new System.EventHandler(this.MainForm_Load);
this.openFileDialog = new
System.Windows.Forms.OpenFileDialog();
openFileDialog.Filter = "Bitmap files (*.bmp)|*.bmp|All
files (*.*)|*.*";
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
private void MainForm_Load(object sender, System.EventArgs e)
{
// init Configuration from config file
// hookup callbacks
_processCommand = new
ProcessSocketCommandHandler(ProcessSocketCommand);
_server.Notify += new
ServerSocket.NotifyEventHandler(NotifyCallback);
// listen for client socket
_server.Start(Global.Configuration.GetInt(SettingKeys.PortNumber));
}
private void NotifyCallback(NotifyCommand command, object
data)
{
// need to call Invoke before can update UI elements
object[] args = { command, data };
Invoke(_processCommand, args);
}
// helper methods
// received a socket notification
private void ProcessSocketCommand(NotifyCommand command,
object data)
{
// holds the status message for the command
string status = "";
switch (command)
{
case NotifyCommand.Listen:
94
status = string.Format("Listening for client on
{0} ...", (string)data);
break;
case NotifyCommand.Connected:
status = "Connected to client " + (string)data;
break;
case NotifyCommand.Disconnected:
status = "Disconnected from client";
break;
case NotifyCommand.ReceivedData:
status = "Received barcode at " +
DateTime.Now.ToLongTimeString();
dataReceived = (byte[])data;
CallToBarcodeDecoderForResult();
DisplayPicture();
UpdateViews();
break;
}
// update status
statusBar.Text = status;
}
private void DisplayPicture()
{
// pictureBox1.ImageLocation = "c:\\test.jpg";
pictureBox1.ImageLocation = Global.GetBarcodeImagePath();
}
private void CallToBarcodeDecoderForResult()
{
// send back barcode decoder result after receive image
// string sendBack = textBoxSendPDA.Text;
string sBarcode =
_server.DecodeBarcode(Global.GetBarcodeImagePath());
string sResult = GetItemNameAndPrice(sBarcode);
string sSendBack = string.Format(
"Barcode: {0} \r\n{1}",
sBarcode, sResult);
sDataToSendBack = sSendBack;
sExtractedBarcode = sBarcode;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] dataToSend = asen.GetBytes(sSendBack);
_server.Send(dataToSend);
}
// temporary database use to retrieve barcode items and
price
// this portion should be replaced with database like mySQL
in future
private String GetItemNameAndPrice(String sBarcode)
{
String sItemName = null;
String sPrice = null;
if (sBarcode.Equals("9-556439-881297 (EAN-13)"))
{
sItemName = "Chocolate water";
sPrice = "RM 2.50";
}
95
else if (sBarcode.Equals("9-556116-220357 (EAN-13)"))
{
sItemName = "Metallite Spray";
sPrice = "RM 7.50";
}
else if (sBarcode.Equals("9-556570-312506 (EAN-13)"))
{
sItemName = "1.5 Liters Coca-cola";
sPrice = "RM 3.50";
}
else if (sBarcode.Equals("4-808647-220012 (EAN-13)"))
{
sItemName = "Custard powder";
sPrice = "RM 6.20";
}
else if (sBarcode.Equals("8-851932-107341 (EAN-13)"))
{
sItemName = "Vanilla Ice-Cream";
sPrice = "RM 4.99";
}
else if (sBarcode.Equals("9-556627-000547 (EAN-13)"))
{
sItemName = "Food Coloring";
sPrice = "RM 3.80";
}
else if (sBarcode.Equals("0-20800-90178-9 (UPC-A)"))
{
sItemName = "Febreeze 1 liter";
sPrice = "RM 4.99";
}
else if (sBarcode.Equals("9-556772-300813 (EAN-13)"))
{
sItemName = "Hair Cream";
sPrice = "RM 12.90";
}
else if (sBarcode.Equals("9-556231-110045 (EAN-13)"))
{
sItemName = "Gardenia";
sPrice = "RM 1.90";
}
else if (sBarcode.Equals("9-556439-881297 (EAN-13)"))
{
sItemName = "Chocolate water";
sPrice = "RM 2.50";
}
else if (sBarcode.Equals("3-178044-044452 (EAN-13)"))
{
sItemName = "National Instrument Barcode";
sPrice = "RM 99.99";
}
else if (sBarcode.Equals("6-71214-23456-9 (UPC-A)"))
{
sItemName = "Modified images";
sPrice = "RM 99.99";
}
else if (sBarcode.Equals("
9-556500-000015 (EAN-13)
"))
{
sItemName = "Eveready Battery";
sPrice = "RM 7.99";
}
96
else
{
sItemName = "Unknown";
sPrice = "RM 0.00";
}
String sResult = String.Format(
"Item : {0} \r\nPrice : {1}
\r\n\r\n",
sItemName,sPrice);
return sResult;
}
private void UpdateViews()
{
if (dataReceived == null)
return;
try
{
ASCIIEncoding asen = new ASCIIEncoding();
byte[] sASCIIData = asen.GetBytes(sDataToSendBack);
textBoxASCII.Text = string.Format(
"Stream length : {0} bytes\r\n\r\n{1}",
sASCIIData.Length,
BitConverter.ToString(sASCIIData));
textBoxDecode.Text += string.Format(
"Barcode number: {0} Received on: {1} \r\n",
sExtractedBarcode,
DateTime.Now.ToLongTimeString());
textBoxSendPDA.Text += sDataToSendBack;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sDataToSendBack.Length; i++)
sb.Append(Convert.ToChar(sDataToSendBack[i]));
//textBoxDecode.Text = sb.ToString();
}
catch (Exception ex)
{
string msg = "The barcode data corrupted. Additional
info:\r\n\r\n" +
ex.Message;
textBoxDecode.Text = msg;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
textBoxSendPDA.Text = "";
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.ImageLocation = openFileDialog.FileName;
String sBarcode =
_server.DecodeBarcode(openFileDialog.FileName);
String sItemNameAndPrice =
GetItemNameAndPrice(sBarcode);
97
// textBoxDecode.Text = sBarcode;
textBoxDecode.Text += string.Format(
"Barcode: {0} - Received on:
{1} \r\n",
sBarcode,
DateTime.Now.ToLongTimeString());
textBoxSendPDA.Text += sItemNameAndPrice;
sDataToSendBack = sItemNameAndPrice;
}
}
}
}
98
ii. ServerSocket Class
/*****************************************************************
*
* ServerSocket for Pocket Barcode Server Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: ServerSocket class is responsible to perform
*
data sending and receiving using socket. An object
*
of ServerSocket must be instantiated before use.
*
ServerSocket class listener can be activated by
calling
*
program direcly after object instantion.
*
****************************************************************/
using
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Net;
System.Net.Sockets;
System.Threading;
System.Web;
System.IO;
System.Text;
System.Diagnostics;
System.Collections.Generic;
System.Windows.Forms;
System.Drawing;
BarcodeDLL;
Common;
namespace BarcodeServer
{
// Socket notification commands
public enum NotifyCommand
{
Listen,
Connected,
Disconnected,
ReceivedData
}
public class ServerSocket
{
int _port;
Socket _listen;
Socket _socket;
// used for socket notifications
public delegate void NotifyEventHandler(NotifyCommand
command, object data);
public event NotifyEventHandler Notify;
public ServerSocket()
{
}
// start listening for client socket connection
99
public void
{
// save
_port =
// make
Stop();
Start(int portNumber)
port number
portNumber;
sure stop if currently connected
// create a new thread that handle client connection
ThreadPool.QueueUserWorkItem(new WaitCallback(Listen));
}
// shutdown the socket
public void Stop()
{
if (_socket != null)
{
if (_socket.Connected)
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
_socket = null;
RaiseNotifyEvent(NotifyCommand.Disconnected, null);
}
if (_listen != null)
{
_listen.Close();
_listen = null;
}
}
// Restart the socket
public void Restart()
{
Stop();
Start(_port);
}
private void Listen(object state)
{
// establish connecton with client
IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint endPoint = new IPEndPoint(ipAddress, _port);
try
{
// listen for client connection
_listen = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_listen.Blocking = true;
_listen.Bind(endPoint);
_listen.Listen(0);
// listening
RaiseNotifyEvent(NotifyCommand.Listen,
endPoint.Address.ToString());
// block here until establish a connection
_socket = _listen.Accept();
100
// we connected with a client, shutdown the listen
socket
// so we won't connect with another client
_listen.Close();
// connected
RaiseNotifyEvent(NotifyCommand.Connected,
_socket.RemoteEndPoint.ToString());
// sit in this loop until connection is broken
// handle client commands and send back response
bool bListen = true;
while (bListen)
{
// reset everything for the next read message
bool bReadMessage = true;
int bytesRead = 0;
int totalBytes = 0;
// hold incoming data
byte[] buf = new byte[1024];
MemoryStream streamRead = new MemoryStream();
while (bReadMessage)
{
// Loop the reads incoming message
// buf is temp holder and the MemoryStream
// contains all of the bits
bytesRead = _socket.Receive(buf);
if (bytesRead > 0)
{
streamRead.Write(buf, 0, bytesRead);
bReadMessage
= !Network.CheckForTerminator(streamRead.ToArray());
totalBytes += bytesRead;
}
else
{
// client disconnected
Restart();
throw (new Exception("Client
disconnected."));
}
}
ReceiveFileStream(streamRead);
streamRead.Close();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public void ReceiveFileStream(MemoryStream streamRead)
{
streamRead.SetLength(streamRead.Length Network.Terminator.Length);
101
streamRead.Position = 0;
string _ImagePath = Global.GetBarcodeImagePath();
FileStream fs = new FileStream(_ImagePath,
FileMode.Create);
byte[] stBytes = streamRead.ToArray();
fs.Write(stBytes, 0, stBytes.Length);
fs.Flush();
fs.Close();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data = asen.GetBytes("Picture saved");
RaiseNotifyEvent(NotifyCommand.ReceivedData, data);
}
AsyncCallback _sendCallback;
public void Send(byte[] data)
{
if (_sendCallback == null)
{
_sendCallback = new AsyncCallback(SendCallback);
}
_socket.BeginSend(data, 0, data.Length,
SocketFlags.None, null, null);
//TOCHECK: _asyncEvent.Reset();
_socket.BeginSend(Network.TerminatorBytes, 0,
Network.TerminatorBytes.Length,
SocketFlags.None, _sendCallback, true);
}
public String DecodeBarcode(String sFile)
{
Bitmap bm = new Bitmap(sFile);
String sBarcode = BarcodeReader.DecodeBarcode(bm);
return sBarcode;
}
private void SendCallback(IAsyncResult ar)
{
try
{
_socket.EndSend(ar);
// RaiseNotifyEvent(NotifyCommand.SentData, null);
}
catch (Exception ex)
{
// RaiseNotifyEvent(NotifyCommand.Error, ex.Message);
}
}
private void ProcessCommand(MemoryStream streamRead)
{
try
{
// remove message terminator
streamRead.SetLength(streamRead.Length Network.Terminator.Length);
// get the command data
streamRead.Position = 0;
102
byte[] data = streamRead.ToArray();
RaiseNotifyEvent(NotifyCommand.ReceivedData, data);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
// Raise Notification event
private void RaiseNotifyEvent(NotifyCommand command, object
data)
{
if (this.Notify != null)
Notify(command, data);
}
}
}
103
APPENDIX C
COMMON MODULE SOURCE CODE
i. Network Class
/*****************************************************************
*
* Network class for Pocket Barcode Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: Network class is a helper class. It contained
*
the fundamental information that are shared between
*
ClientSocket and ServerSocket, like the terminator
bytes
*
and its method to check for valid terminator bytes
*
****************************************************************/
using
using
using
using
using
using
System;
System.Text;
System.Collections;
System.IO;
System.Runtime.InteropServices;
System.Drawing;
namespace Common
{
public class Network
{
static public string Terminator
{
get {
return "<data_end>";
}
}
static public byte[] TerminatorBytes
{
get
{
return ASCIIEncoding.ASCII.GetBytes(Terminator);
}
}
104
private Network()
{
}
static public bool CheckForTerminator(byte[] data)
{
if (data == null || data.Length < Terminator.Length)
{
return false;
}
string endBuf = Encoding.ASCII.GetString(data,
(int)(data.Length - Terminator.Length),
(int)Terminator.Length);
return Network.Terminator.Equals(endBuf);
}
static public void WriteInt32(MemoryStream stream, Int32
data)
{
stream.Write(BitConverter.GetBytes(data), 0,
Marshal.SizeOf(data));
}
static public void WriteString(MemoryStream stream, string
data)
{
WriteInt32(stream, data.Length);
stream.Write(ASCIIEncoding.ASCII.GetBytes(data), 0,
data.Length);
}
static public Int32 GetInt32(byte[] bits, ref int bitsIndex)
{
Int32 data = BitConverter.ToInt32(bits, bitsIndex);
bitsIndex += Marshal.SizeOf(data);
return data;
}
static public byte[] GetBytes(byte[] bits, ref int bitsIndex,
int length)
{
byte[] data = new byte[length];
Buffer.BlockCopy(bits, bitsIndex, data, 0, length);
bitsIndex += length;
return data;
}
}
}
105
ii. Configuration Class
/*****************************************************************
*
* Configuration class for Pocket Barcode Application
*
* Author
: Seah, Yeow Ngee
* Date
: 23 Feb 2007
*
* Supervised by: Assoc. Prof. Dr. Syed Abdul Rahman Syed Abu Bakar
*
* Description: Configuraiton class is responsible for writing and
*
retrieving program configution. Its used XML to
*
to store configuration.
*
****************************************************************/
using
using
using
using
using
using
System;
System.Collections;
System.Xml;
System.IO;
System.Diagnostics;
System.Windows.Forms;
namespace Common
{
public class Configuration
{
// Internal variables and list
Hashtable _list = new Hashtable();
string _filePath = "";
bool _autoWrite = true;
string[,] _defaultValues;
public bool AutoWrite
{
get { return _autoWrite; }
set { _autoWrite = value; }
}
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
public Configuration()
{
_filePath = GetFilePath();
Read();
}
public Configuration(string[,] defaultValues)
{
// Store default values, use later when populate list
_defaultValues = defaultValues;
// Get full path to file
_filePath = GetFilePath();
// Populate list with configuration from file
106
Read();
}
// Public method
// Set setting value. Update underlying file if AutoUpdate
is true.
public void SetValue(string key, object value)
{
// update internal list
_list[key] = value;
// update Configuration file
if (_autoWrite)
Write();
}
// Return specified Configuration as string.
public string GetString(string key)
{
object result = _list[key];
return (result == null) ? "" : result.ToString();
}
// Return specified Configuration as integer.
public int GetInt(string key)
{
string result = GetString(key);
return (result == "") ? 0 : Convert.ToInt32(result);
}
// Return specified Configuration as boolean
public bool GetBool(string key)
{
string result = GetString(key);
return (result == "") ? false :
Convert.ToBoolean(result);
}
// Read Configuration file.
public void Read()
{
// First, remove all items from list
_list.Clear();
// Next, populate list with default values
for (int i = 0; i < _defaultValues.GetLength(0); i++)
_list[_defaultValues[i, 0]] = _defaultValues[i, 1];
// Last, populate list with items from file
// Open Configuration file
if (File.Exists(_filePath))
{
XmlTextReader reader = new XmlTextReader(_filePath);
// Go through the file, read the xml file and
// populate internal list with 'add' elements
while (reader.Read())
{
107
if ((reader.NodeType == XmlNodeType.Element) &&
(reader.Name == "add"))
_list[reader.GetAttribute("key")] =
reader.GetAttribute("value");
}
reader.Close();
}
}
// Write Configuration to the .config file.
public void Write()
{
// Header elements
using (StreamWriter writer = File.CreateText(_filePath))
{
writer.WriteLine("<configuration>");
writer.WriteLine("\t<appSettings>");
// Go through internal list and create 'add' element
for each item
IDictionaryEnumerator enumerator =
_list.GetEnumerator();
while (enumerator.MoveNext())
{
writer.WriteLine("\t\t<add key=\"{0}\"
value=\"{1}\" />",
enumerator.Key.ToString(),
enumerator.Value);
}
// Footer elements
writer.WriteLine("\t</appSettings>");
writer.WriteLine("</configuration>");
writer.Close();
}
}
// Overwrite Configuration with default values.
public void RestoreDefault()
{
try
{
// Easiest way is to delete the file and
// repopulate internal list with defaults
File.Delete(FilePath);
Read();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
// Private methods
// Return full path to Configuration file. Appends .config
to the assembly name
private string GetFilePath()
{
108
return
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
+ ".config";
}
}
}