geographic information system

89
UNIVERSITY OF GHANA DEPARTMENT OF COMPUTER SCIENCE LEGON A DISTRICT BASED ONLINE GEOGRAPHIC INFORMATION SYSTEM FOR HEALTH, EDUCATION, WATER AND SANITATION FACILITIES. BY THOMAS ASIBEY BONSU INDEX NUMBER: 10270619 A PROJECT PRESENTED TO THE COMPUTER SCIENCE DEPARTMENT, UNIVERSITY OF GHANA, LEGON, IN PARTIAL FULFILMENT OF THE REQUIREMENT FOR THE AWARD OF THE

Upload: independent

Post on 31-Mar-2023

0 views

Category:

Documents


0 download

TRANSCRIPT

UNIVERSITY OF GHANA

DEPARTMENT OF COMPUTER SCIENCE

LEGON

A DISTRICT BASED ONLINE GEOGRAPHIC INFORMATION SYSTEM FOR HEALTH,

EDUCATION, WATER AND SANITATION FACILITIES. BY THOMAS ASIBEY BONSU INDEX NUMBER:10270619

A PROJECT PRESENTED TO THE COMPUTER SCIENCE DEPARTMENT, UNIVERSITY OF GHANA, LEGON, IN PARTIAL FULFILMENT OF THE REQUIREMENT FOR THEAWARD OF THE

BACHELOR OF SCIENCE DEGREE IN COMPUTER AND STATISTICS.

MAY 2012

1

DECLARATION

I, Thomas Asibey Bonsu declare that this project being submitted to the department of

Computer science as a dissertation for the award of a degree in computer science and

Statistics is of my own work and that all references have been fully acknowledged. This

work however has never been submitted either in whole or partby anyone to the university

or any other in any part of the world.

Signature………………………. Signature……………………

Student: Thomas Asibey Bonsu Supervisor: Mr. R.D Appiah

Date:……../………./………………. Date:………/………../……………

2

DEDICATION

This project is dedicated to God Almighty for seeing me through my academic work and

enabling me with the wisdom to carry out my project and my parents Mr. Felix Bonsu and

Mrs.Esther Bonsu

3

ACKNOWLEDGEMENT

I am very grateful to God for seeing me through my education at the university and

particularly this project. His favour and grace was always abundant.

My sincere thanks also go to my supervisor, Mr. R.D. Appiah for his directions and advice

during the course of this project and for supervising me.

I am also very grateful and thankful to Mr. Henry Baffoe, Mr. Collins Asamoah and all other

friends and helpers who came my way during the course of thisproject and whose help I

couldn’t have done without.

I also want to show my appreciation to all lecturers at the computer science department of

the University of Ghana for their support and inspiration during my period of study at the

University.

Finally, to everyone who has been of any help to me in taking this project a success, I say am

grateful and may God bless you all.

4

TABLE OF CONTENT

Declaration ………….. …………………………………………………………………………………… I

Dedication…………………………………………………………………………………………………….. II

Acknowledgement ……………………………………………………………………. …………………….III

Table of contents IV

Chapter 1: Introduction…………………………………………………………………………….. 8

1.1. Background of study…………………………………………………………………8

1.2 Scope……………………………………………………………………………………….8

1.3 Title………………………………………………………………………………………….9

1.4 Aim………………………………………………………………………………………….9

1.5 Objectives…………………………………………………………………………………9

1.6 Methodology…………………………………………………………………………….10

1.6.1 Planning Phase……………………………………………………………….10

1.6.2 Analysis Phase…………………………………………………………………10

1.6.3 Design Phase…………………………………………………………………….11

1.6.4 Implementation Phase………………………………………………………11

CHAPTER 2: LITERATURE REVIEW

2.1 Introduction……………………………………………………………………………………12

2.2 Background Information on GIS ……………………………………………………..12

2.3 Overview of Information System………………………………………………………..13

2.3.1 Components of information system………………………………………13

2.3.2 Information System Application Types…………………………………..14

2.3.3 Decision support System……………………………………………………….14

5

2.4 Geospatial Technologies…………………………………………………………………………………14

2.4.1 Global Positioning System……………………………………………………....14

2.4.2 Personal Digital Assistance………………………………………………………15

2.4.3 Remote Sensing………………………………………………………………………15

2.5 GIS tools used……………………………………………………………………………………..15

2.5.1 ArcGIS-Mymmical………………………………………………………………………15

2.5.2 ArcGIS Explorer…………………………………………………………………………16

2.5.3 Map Publisher……………………………………………………………………………..16

2.6 Database and Database Management System…………………………………………16

2.6.1 Importance of database and database management system…………….16

2.7 Microsoft SQL……………………………………………………………………………………………17

CHAPTER 3: INTRODUCTION TO THE SYSTEM

3.2 Problems with the existing system……………………………………………………………18

3.3 The systems components…………………………………………………………………………18

3.4 Entity Relationship Analysis and Model…………………………………………………….18

3.4.2 Types of Relationships………………………………………………………………………21

3.4.3 keys……………………………………………………………………………………………………21

3.5 Data Integrity…………………………………………………………………………………………..21

3.6 Normal Forms…………………………………………………………………………………………..22

3.7 Proposed System……………………………………………………………………………………..22

3.8 General Overview of Developmental design of the proposed and the existing design ………………………………………………………………………………………………………………………….23

CHAPTER 4: PROPOSED SYSTM DESIGN

4.1 Designing User Procedures………………………………………………………………………..24

4.2 Database Tables……………………………………………………………………………………….24

6

4.4 Requirements and Objectives of the System………………………………………………………30

4.5 Program Design……………………………………………………………………………………….32

CHAPTER 5: SYSTEM IMPLEMENTATION AND TESTING

5.1 Application Development………………………………………………………………………34

5.2. Testing…………………………………………………………………………………………………..34

5.2.1. Unit Testing…………………………………………………………………………………..35

5.2.2. Integration Testing………………………………………………………………………….35

5.2.3. Acceptance Testing…………………………………………………………………………35

5.3. Documentation……………………………………………………………………………………………35

5.4 File conversion……………………………………………………………………………………………36

5.5 Changeover…………………………………………………………………………………………………36

5.6 Training………………………………………………………………………………………………………37

5.7 Conclusion…………………………………………………………………………………………………37

CHAPTER SIX CONCLUSION AND RECOMMENDATION

6.1 Conclusion…………………………………………………………………………………………………38

6.2 Recommendation………………………………………………………………………………………38

REFERENCES

USER MANUAL

APPENDICES

7

CHAPTER ONE

INTRODUCTION

1.1. BACKGROUND

It can be attested to the fact that the priority of every government for any developing country is to be able to build up proper infrastructure (Roads, schools, health facilities, water and sanitation facilities, energy facilities, etc) as a backbone for further growth and expansion of the economy.

A quick observation and research has revealed the absence of such a comprehensive database which is represented in a spatial manner to show distribution patterns for quick and easy interpretation which enhances effective decision making. The capacity to take relevant decisions timely and with a bit more precision depends on the availability of such tools to support the making of such decisions.

Geographic information system is an immerging technology whichhas the capability of representing real world situations onto an information system. It deals with actual location of real world object, the shape of the object and other attributes being captured into this information system such that it is astrue as the real world is, at any given time.

With such a tool available and the need for proper decision support tool for identified stakeholders as the government, local authorities, donor agencies, investors etc, it thereforebecomes relevant and necessary to try and use this immerging technology to solve this decision support system gap that exists.

1.2. SCOPE

A brief introduction to the functionalities of the project in terms of what answers decision

makers and other stakeholders would be receiving from the system includes the following;

- How many Primary, JHS and SHS are in a particular area ofinterest

- How are these schools distributed within the area

- What is the facility’s current state and who owns it- Is there the need to put up similar facilities within

the same location.

- Are existing facilities enough for a particular area, etc

8

This is a decision support tool, which will present very relevant information to interested stakeholders to support critical decision making in these areas (Education, Health, Water and Sanitation) of interest, through a GIS web mapping technology.

1.3 TITLE

A DISTRICT BASED ONLINE GEOGRAPHIC INFORMATION SYSTEM FOR HEALTH, EDUCATION, WATER AND SANITATION FACILITIES.

1.4. AIM

As highlighted in the problem statement, there exist a need for such a decision support tool to aid effective decision making in the areas of educational, health, water and sanitation with respect to facilities in these areas.

To develop an online GIS based database on facilities in thevarious sectors with virtual information about location, stateof the facilities and dispersion for decision makers and stakeholders.

1.5. OBJECTIVES

1) To create a spatial database of educational, health and water and sanitation facilities for yendi district.

2) To develop an online mapping application to present detailed information of these sectors in a visually appealing format.

3) Develop geolocation, filter and fetch tools and search identify tools to allow stakeholders perform basic spatial analyses like zoom to a location

of interest, finding out the type and number of schools orhospitals, or clinics or SHS or functioning boreholes etc within an area of interest.

4) Host this information on the web.

5) To provide guidelines to ensure effective maintenance of such database.

9

1.6. METHODOLOGY

In developing the required system, it has to go through the various software developments

life cycles. The methodologies specifically used in developingthe required system are the

combination of the waterfall and rapid prototyping methodology. The two were selected

because with the waterfall requirements are determined at the early stage of the system

development life cycle. The rapid prototyping ensures that the user gets access to each

phase of the system to check if it meets the specified requirements. The various phases in

developing are explained below;

1.6.1. PLANNING PHASE

This phase involves the initial assessment of the problems with the existing system and

feasibility study. The identified problems were as a result ofstakeholders complaints of

difficulties in having a quick access to a database of the facilities in the community.

Collection of data for this project was done by interview withthe geographical institutions

from time to time.

1.6.2. ANALYSIS PHASE

The existing system is thoroughly reviewed and analyzed to find possible solutions. The

individual components are analyzed to find how they can be improved. Hosting the

database on the internet which represent real world object in a spatial manner and makes

Its accessibility easier was the preferred solution found to solve the problem. Also, user

requirements, existing system evaluation and logical system design was considered.

10

1.6.3. DESIGN PHASE

At this phase, the programming language and platform used, hardware requirement and

software requirement were considered. Below are the details;

Hardware SpecificationProcessor Single 800 MHz or higherRAM 512 MB or higherDisk Storage 100 GB or HigherUPS On-line UPS 650 VA

Software SpecificationOperating system Windows 7Web Server Internet Information ServiceDatabase Server MySQLMap Publisher Map publisher 8.o

Programming language Visual basic.net(VB.NET)

1.6.4. IMPLEMENTATION PHASE

This section involved coding, testing and debugging, installation and finally running. Visual

basic.Net (VB.NET) which provides all the features that are required to develop a graphical

user interface as ready to use components and MYSQL for dynamic database was used.

11

CHAPTER TWO

LITERATURE REVIEW

2.1. INTRODUCTION

Leveraging technological advancement to equip social issues indeveloping countries has always been difficult for past and present government. It becomes much difficult for government, investors and stakeholders to have a clear knowledge about communities which are not well developed in terms of health, education and proper layout of water and sanitation facilities. Hence my project proposes using geographic information system (GIS) as the framework for decision supporttool for community leaders and more specifically to assist them to prioritize infrastructure maintenance. Geographic information system which is an emerging system thus has the

capability of representing real world situations onto an information system for easy and quick understanding. This paper presents a global “state of practice” GIS for managing the district’s facilities (health, education, water and sanitation) with emphasis on Yendi district.

2.2 BACKGROUND INFORMATION ON GIS

A Geographic Information System (sometimes called geographical information systems) or GIS can be described as general purpose computer based technique for handling geographic data in digital form in order to capture, store, manipulate, analyze, manage and display diverse sets of spatial or geo-referenced data . ( Peter. A. 1998. Principles of geographical information systems ., http://ukcatalogue.oup.com/product , 21st February,2012.)

In essence, GIS relates database records and their associatedattributes data to a physical location, thereby creating a “small map”. Visualization of discrete parts of these data on a GIS applications can then display the intersection of various “themes” as well as the spatial relationships between various features .( Vanier D.J. “GIS” as an integrated decision support for municipal asset management., www.nrc-cnrc.gc.ca/obj. 4th February,2012.)

GIS are spatial database of digital maps which store information on various phenomena and their locations. GIS makes it possible to know the exact locations of real world objects and its features through its representation on map or some more sophisticated devices like the GPS.

12

2.3. Overview of an information system

An information system can be defined as an asset of procedure that collects (retrieve) process, store and disseminate information to support decision making and control.(laudon.1998.ManagementInformationSystem.http://www.kulzick.com/stu/typesys.htm. 10th February 2012.)

An information system is an organized combination of people, hardware, software, communication networks and a data resourcethat collects, transform, and disseminate information in an organization.

Both definitions express the need for an input, process and output for information systems to be complete. An information system incorporates technology but is also concerned with information and organizational activities.

2.3.1 Components of an information system

Information Systems consists of components that work together to achieve the objectives of providing information.

People: They are the most important element in a computer based information system. Information personnel are the peoplewho manage, run, program and maintain the system. The people also include the users of the information system.

Procedures: These include the strategies, policies, methods and rules for using the system. These procedures describe whenprogram is executed.

Hardware: Consist of computer equipments that are used to perform input, processing and output of information. Input devices include keyboard, scanners, mouse etc. Processing devices are CPU and main memory. Some output devices are printers and computer screens.

Database: They are organized collection of facts and information consisting of two or more related data fields.

Network: This enables electronic transmission of signals for communication, which enables an organization to carry out their processes and tasks through effective computer network.

Software: Consists of computer programs that drive the operation of the computer. These programs allow a computer to process information.

13

2.3.2 Information System Application Types

The most common types of information systems used are transaction processing systems, management information systemsand decision support systems. Others include electronic and commerce systems. These categories depend on the level of use of the data.

2.3.3 Decision support system (DSS)

By the 1980s, the dramatic improvements in technology resultedin information systems that were less expensive but more powerful than earlier systems. People at all levels of organizations began using personal computers to do a variety of tasks; they were no longer dependent on IS department for their information needs. So people quickly recognized computersystems could support additional decision making activities.

A decision support system is thus an organized collection of people, procedures, software, database and devices used to support problem specific decision making. The focus of DSS is on decision making effectiveness.

The essential elements of DSS include a collection of models used to support a decision maker or user (model base), a collection of facts and information to assist in decision

making (database, and systems and procedures that help decision makers and other users interact with the DSS.

In addition to DSS that support individual decision making, group decision support systems and executive support systems use the same approach of a DSS. A group support system, also called Group Decision Support System, includes the DSS elements just described and software called groupware, to helpgroups make effective decisions.

2.4 GEOSPATIAL TECHNOLOGIES

2.4.1 Global Positioning systems

GPS is a satellite based positioning systems operated by the US Department of defence. The location of the GPS unit is determined by performing triangular calculations on the location of reference satellites at the time of the reading, and the GPS unit while considering the time lag for the signalto reach the unit. The GPS unit must have a unobstructured view of the sky, a clear line of site to the satellites, and limited cloud cover. Multipath

14

interference, caused by signals bouncing off neighbouring objects, alters signal travel time and reduces the accuracy ofcalculations.

Prior to 2000, GPS accuracy was limited to ± 100 metres because of random timings errors introduced by the US militaryto limit GPS misuse by the adversaries. Today, relatively inexpensive hand-held GPS units are accurate to ± 10 metres depending on the number of reference satellites used,(minimum of four)and their location overhead. Differential GPS or DGPS relies on at least four satellites and a real time connection to a known local reference point; this dramatically increases

accuracy to ± 1 metre. Depending on the type of reference point used the amount of post processing, the duration of observation and the location of satellites, DGPS accuracy can be ± 2 mm horizontally triple that vertically.

2.4.2. Personal Digital Assistance

The popularity of PDAs as they are sometimes called, as business/personal notepads and aide-memories has pushed this tool into specialized data collection. These handheld units greatly reduce the amount of paper needed in the field eliminate potential transcription errors from paper to the corporate database. PDAs can directly interface to GPS (to establish location); can download GIS maps (to sight and geolocate neighboring assets).

2.4.3. Remote sensing

Remote sensing is described as imaging without touching, and within the scope of this paper refers to the use of aircraft or satellites to collect geographic information. A satellite image is often the most practical way to acquire usable geographic information. Although this type imagery will help the identification of buried facilities, it is a good way to identify roads and buildings and can assist in geolocating manholes and catch basins by providing reasonably accurate spatial data. Commercial services supply high resolution, ortho-rectified images with a pixel resolution of 2.5 metres($5000US in 2003) that are suitable for superimposition on and validation of existing GIS maps.

2.5. GIS TOOLS USED

2.5.1 ArcGis-Mymical

It’s used for working with maps and geographic information. Also, is used for creating and using maps; compiling geographic data; analyzing mapped information; sharing and

discovering geographic information; using maps and geographic information in a range of

15

applications and managing geographic information in a database. The system provides infrastructure for making maps and geographic information available throughout a community and openly on web. ESSI is one of the companies and almost anindustry standard providing the GIS market with quite a numberof GIS products. ArcGIS has strong spatial analytical capabilities.

2.5.2 ArcGIS Explorer

is a free GIS viewer that gives you an easy way to explore, visualize, and share GIS information. ArcGIS Explorer adds value to any GIS because it helps you deliver your authoritative data to a broad audience.

With ArcGIS Explorer, you can

Access ready-to-use ArcGIS Online base maps and layers. Fuse your local data with map services to create custom

maps. Add photos, reports, videos, and other information to

your maps. Perform spatial analysis (e.g., visibility, modelling,

proximity search).

2.5.3 Map Publisher

The Map Publisher is the software that pieces together data from several sources to create your maps. It is made by using the workbench in a standard Map Viewer install. The process ofmaking maps is fundamentally the same as using the 3.7 Map Translators; however, it has improvements that now simplify the detailed process of making maps. You can connect to several different databases, import the data, merge the data, and then configure the display and the data.

2.6. Database and Database Management System

A database is a group of related files and a Database Management System (DBMS) is the software designed to create, store and manipulate a database.

2.6.1 Importance of Database and DBMS

1. Elimination of program-to-program dependency: Using DBMS the organization of the information is stored with the information, not the application software.

2. Reducing data redundancy: Because all information is storedin one place (database),

data redundancy is greatly reduced not eliminated together.

16

3. Ensuring data security: It can allow information access to only those people who actually need it.

2.7 Microsoft SQL

Structured Query Language (SQL) is the standard language for interaction with databases.

SQL controls access to your data to ensure that multiple users can work with it

concurrently, to provide fast access and also ensures only authorized users can obtain access.

17

CHAPTER THREE

SYSTEM ANALYSIS

3.1. INTRODUCTION TO THE EXISTING SYSTEM

In case of the existing system, the detailed database for the various facilities could be accessed by those who are very close to the system. The system could only provide raw database without a user friendly interface. In trying to have information about the status, ownership, location and number of a particular facility or facilities in an area, the

appropriate authorities in charge of that specific facility iscontacted to gain access to the database. This system slows developments and in making decisions because it becomes very difficult at times to have access to detailed database for a particular facility. Stakeholders, Government and other interested parties usually finds it time consuming in their attempt to get access to a specific data to enhance or facilitate effective decision making.

Information could be accessed through the following means;

1. People closer to the system accessed the database by running sql queries on their computers. The queries therefore output the requested data in a poor user friendly format.

2. Stakeholders and other users had to contact the appropriate authorities of the various facilities for thedatabase of a particular facility.

3.2. PROBLEMS WITH THE EXISTING SYSTEM

The problems with the existing system that has led to its upgrade are listed below;

1. It retards developments since the database does not give a true picture of the real world objects. It is only raw data that are accessible to the interested party.

2. Having access to a data can be sometimes frustrating and time consuming because of the lengthy process involved in getting the data when one is not closer to the system.

3.3. THE SYSTEM’S COMPONENETS

Flow diagrams: are the first tools for the systems componentsto systems processes, the data store or files used by the processes, any external entities that interact with the systemand the information or data flow.

Data store file: it is the repository of the data and remainsthe data in the system. Processes can retrieve data from a

store or enter data into a store. Symbolically, thin lines parallel to each other and having a unique name represent a data store.

18

Processes: they show what the system does. Each process has one or more data inputs and produces one or more data outputs.In designing processes are symbolised by circles in DATA FLOW DIAGRAMS (DFD). Every process has a unique name and number inserted in the circle that processes in the DFD’s.

External Entities: are outside the system. T hey either use the systems output or simply input data into the system. The designer of the system has no control over the external entities. For eg. The system to be designed, the external entities are symbolically represented by a square or rectangle

KEY

Process

Data Flow

External Entity

3.4. ENTTITY RELATIONSHIP (E-R) ANALYSIS AND MODEL

Entity relationship analysis uses 3 major abstractions to describe data.

Entity

An entity is an object with distinct set of properties that iseasily identified. Entities are the building blocks of a database. An entity is represented using rectangle that

school

contains the name of the entity. Entities may treated as nouns.

Relationships

A relationship is used to establish a link or connection between a pair of logically related entities. It is an association between entities. Separate entities can have relationships with each other.

19

Attributes

An attribute is a property of entity that differentiates the entity from other entities and gives information the entity.

ID

name

status

3.4.1. Types of Relationships

Three types of relationships can exist between entities. Theseare:

1. One- to- one (1:1)

2. One-to-many (1: M)

3. Many-to-many (M: M)

Facility

One-to-one Relationship

Two entities have a One-to-one relationship if for every instance of the first entity, there is only one instance of the second entity. Consider for example a region, for each community there can be only one hospital.

1 M

One-to-Many Relationship

Two entities relate in a one-to-one if for every instance of the first entity, there can be zero, one or several instances of the second entity and for every instance of the second entity, these exactly one instance of the first entity. For example, a region having more schools.

Many-to-Many Relationship

Two entities relate in a many-to-many relationship when every instance of the first entity, thee can be multiple instances of the second entity, and for every instance of the second entity, there can be multiple instances of the first entity.

20

3.4.2. KEYS

Entering data integrity ensures that the data in the database is correct and valid. The various types of keys that have beenidentified are:

PRIMARY KEY

A candidate key that is chosen to identify each row uniquely. It cannot have a NULL value.

CANDIDATE KEY

Community owns Hospital

An attribute or a set of attributes, that uniquely identifies a row.

ALTERNATE KEY

A candidate key that is chosen as a primary key is an alternate key.

COMPOSITE KEY

In certain tables a single attribute cannot be used to identify rows uniquely and a combination of two or more attributes used as primary key. Such keys are called compositekeys.

FOREIGN KEY

When a primary key of one table appears as attribute in another table, it is called the foreign key in second table. Aforeign is also used to relate two tables.

3.5. DATA INTEGRITY

Data integrity falls into the following categories:

Entity Integrity

This ensures that each row can be uniquely identified by an attribute called primary key.

Domain Integrity

It refers to the range of valid entries for a given column. Itensures there are only valid entries in the column.

Referential Integrity

This ensures that for every value of foreign key, there is a matching value of the primary key.

21

3.6. NORMAL FORMS

Normalisation results in the formation of tables that satisfy certain specified constraints and represent certain normal forms. The normal forms are used to ensure that various types of anomalies and inconsistencies are not introduced in the database. Normal forms are table structures with minimum redundancy. Some of the normal forms are explained below;

First Normal Form

A table is said to be in 1NF when each cell of the table contains precisely one value.

Second Normal Form

A table is said to be in 2NF when it is in 1NF and every attribute in the row is functionally dependent upon the whole key, and not just part of the key. The situation can lead to insertion, deletion and updating.

Third Normal Form

A relation is said to be in 2NF when it is in 2NF and every non-key attributes is functionally dependent only on the primary key.

3.7. PROPOSED SYSTEM

The online mapping for facilities would present facility information as it exists in the real world, with its associated attribute information in a very easy and friendly interface. It would make very easy and practical to access such information.

The existing system stops at where data is capture into the database. There is no concrete visual display mechanism to present back such information to interested stakeholders. And also information in the existing system could not be accessed globally. This is what the proposed system would accomplish.

The proposed system would present the detailed information globally via the internet to all users as its relevance would be much appreciated.

ADVANTAGES OF THE PROPOSED SYSTEM

1. Has a wider audience and coverage since the data is made available globally to a larger number of users and interested stakeholders. Hence any user with a computer and internet access can have access to the information presented on the site.

22

2. There is true representation or picture of real world objects in digital format. That is, the format of presentationis almost like real world situations.

3. It assists stakeholders, government officials in taking decisions at a very faster rate, since they are presented witha mapping system showing facilities and their respective locations

4. The system present a more interactive and user friendly interface.

5. This technology enhances developments, because a developmental activity becomes easy when one is presented witha comprehensive visual layout of facilities in a specific area.

DISADVANTAGE OF THE PROPOSED SYSTEM

1. Stakeholders without internet access won’t be able to have access to the system.

3.8. GENERAL OVERVIEW DEVELOPMENTAL DESIGN OF THE PROPOSED ANDEXISTIMG SYSTEM

Existing system

Proposed system

23

CHAPTER FOUR

SYSTEM DESIGN

4.1. INTRODUCTION

This chapter continues the linear cycle by describing detaileddesign, which starts after broad deign has been completed. Theoutput from broad design is a set of logical data flow diagrams. Detailed design uses the processes and data stores

Facility Info

Questionnaires

Database END USER

TEXTUAL

Facility Info

Questionnaire Admin and Data entry

Database Web interface

IIS Server

Internet

Visually interactive

End User

End User

End UserEnd User

within automation boundary to specify programs and database. It also uses the flows outside the boundary to specify the user procedures. Finally the interface between the user and the computer system is designed.

4.2. DESIGNING USER PROCEDURES

User defines what people must do for the system to work. Two types design are important in user procedure design. One is functional design that is, making sure the system does what itis supposed to do. Functional design defines the task necessary to make the system work. These tasks must transform and move the data in the way specified by logical design. The other is job design that specifies what people must do within the tasks.

Flowcharting is one of the earliest representation tools for physical systems. A flowchart uses a finite set of symbols to represent system components. The following symbols are used torepresent computer components:

Flowchart symbols for non-computing components

Data

Connector

Process

Decision

Terminator Document

Data Flow

24

FLOW CHART DIAGRAM FOR THE WEB INTERFACE

NO YES

No YES

NOYES

25

SELECT FACILITY

IF SINGLE

ENABLE ADMINLEVEL

START

IF ADMIN LEVEL

CHOOSE ADMINLEVEL

If select

SELECT ADMINPARAMETER

CLICK SEARCH

DISPLAY SEARCH

END

4.3. DATABASE TABLES

ENTITY: SANITATION FACILITIES

Description: This table store general information on the various sanitation facilities.

Primary key: sanitation ID

FOREIGN KEY: COMMUNITY ID

Field Name

Data type Description

ID Int Sanitation facility identification

STRUCTURE Varchar Type of sanitation facility

OWNERSHIP Varchar Owner of the facilityLATITUDE Float latitudeLONGITUDE Float Coverage areaCOMMUNITY Varchar Where the facility is

locatedSTATUS Varchar Current state of the

facilityGENDER Varchar GenderPICTURE Image Picture of the facility

ENTITY: Education Facility

Description: This table stores information collected on the various education facilities.

PRIMARY KEY: ID

FOREIGN KEY: COMMUNITY ID

Field Na,e Data Type DescriptionID Int Education facility

IdentificationName Test Name of FacilityType Varchar Type of Facility

Ownership VarcharOwner of the Facility

Latitude Float Area coveredLongitude Float longitudeCommunity Varchar Where facility is

locatedStatus Varchar Current state of

facilityPicture Image View of the

facility

26

ENTITY: Health Facility

Description: This table stores information on the health facilities

Field Name

Data Type Description

IDINT

Health Facility Identification

NameVarchar

Name of Facility

Type Varchar Type of facility

Ownership Varchar Owner of facility

Latitude Float Latitude

Longitude Float Longitude

CommunityVarchar

Location of facility

Status Varchar Current state of facilityPicture Image

View of the facility

ENTITY: WATER FACILITIES

DESCRIPTION: This table stores information on the water facilities.

Foreign key: ID

Field Name

Data Type Description

ID INT Water facility identification

Source Varchar Source of waterType Varchar TypePoer Source

Varchar Source of power for the facility

Ownership Varchar Owner of the facilityLatitude Float LatitudeLongitude Float LongitudeCommunity Varchar Location of the facility

Status Varchar Current state of the facility

Picture Image View of the facility27

ENTITY: COMMUNITY

DESCRIPTION: This table holds information about the community

Primary key: Community code

Field Nmae Data Type DescriptionCommunity ID

INT Identification for community

Community Code

INT Identification code for a community

Community Name

Varchar Name of a community

LatitudeFloat Latitude

LongitudeFloat Longitude

KeyfeatureVarchar Known feature in a community

28

ENTITY RELATIONSHIP DIAGRAM FOR THE DATABASE

NameCode

Health facility

Contains

NameID ID

status

OwnerSANITATION FACILITY

GENDEROwner

STRUCTUREIDNAME

STATUS

29

4.4. OBJECTIVES

Functional Requirements: These state the new or amended functional system requirements and include:

1. A computer with a network access connected to a central computer (known as the server) running access server.

CommunityKey feature

HAS

COMMUNITY

DISTRICT

NAME

ID

ID

TYPE

Education facility

PICTURE

OWNER

STATUS

DOMINATED LANGUAGE

DISTRICT

IS FOUNDIN

NAME

ID

WATER FACILITY

SOURCEPOWER SOURCE

TYPE

ID

Operational objectives

This defines the performance standard to be achieved by the new system and include:

1. Change systems processes from computer based to on-line based system..

2. Easy generation of accurate and timely reports for effective decision-making.

3. Quick and easy to generate outputs.

Cost

There are two types of cost involved in the development of thenew system. They are

Development cost: consists of monies spent on all resources used to develop the system.

Operational cost: consist of cost incurred in operational activities of the new system.

Hardware Requirements

The minimum hardware requirements needed to run the new systeminclude;

1. A computer with Pentium ( p-1) microprocessor or above witha minimum of 64MB RAM.

Software Requirements

The new system requires a computer running SQL server as the back-end database engine.

Computer Interface

The computer interface is an important part of user proceduresdesign. It defines how the

users interact with a computer and has an important bearing on user’s acceptance of a

system. A good and easy-to use computer interface will make auser’s job more straightforward and pleasant. Consequently, the users will carry out the required work more

30

effectively. The purpose of the computer interface is quite simple. It is to capture information about the system from theusers and make this information available to all systems users. The supply of information is called the systems output.In any case the system output will be the reports that the system generate.

Online design used in this project calls for user-machine dialogues that permit rapid interchange of information betweencomputers and human users.

User Dialog

Different methods are used in online user dialog. The most commonly used and adopted in the design of the interface for this project is the menus and template.

Menus

A menu system presents the user with a set of actions and requires the user to select one of them. Once an option is selected, another menu is presented. Actions are selected, selecting options using the mouse.

Template

Templates are equivalent to forms on a computer. A form is presented on the screen and the user is requested to fill the form. Usually several labelled fields are provided and users enter data into the blank spaces.

Application Architecture

The system architecture is an important feature in an application because it defines the elements in the applicationand how elements in the application interact and what functionality each element provides. The three types of systems architecture are single-tier, two-tier and multi-tier.

Single-tier Application

In a single-tier application, only one layer supports the presentation, application logic, and data services. The data itself can be stored in any location such as on a server. However the functionality for accessing the data is part of the application. An example of a single-tier is Microsoft Excel where the application logic includes the calculation of total, spell check and other mathematical functions.

31

Two-tier Applications

Two-tier or standard client/server applications, group presentation and application logic components on the client machine and access a shared data source using a network connection. In a two-tier application, the user interface and business rules are a single layer that runs on a client computer (Microsoft press 1999). Separate application, such asSQL server or Oracle databases servers, provide the data services. Client/server applications are often two-tier applications such as visual basic application that calls a SQLserver stored procedure to provide data for the application. The visual basic application is one layer whiles the SQL Server data services are another layer.

The code for the user interface and business rules would not necessarily have to be within the same project; the visual basic application would call a dynamic link library (DLL) thataccess the data. Two-tier applications work well in

department-scale applications with low number of users (under 100), a single database, and secure, fast networking.

Multi-tier Applications

These are logic concepts. The three tiers are generally described as user (first), business (second or middle) and data (third); however, there can be more than three-tiers in amulti-tier application.

Because of this fact, multi-tier applications are sometimes referred to as n-tier applications where n is any number greater than or equal to three.

4.5. PROGRAM DESIGN

This aspect looks at the platform chosen for the design of both the front-end (User interface) and back-end database.

Front-End

The front-end development compiler chosen was Visual Basic 6.0(VB6)

Enterprise edition: It enables the programmer to design innovative user interfaces taking advantage of other applications from manipulating text and graphics to working with databases (MSDN 2000).

32

Back-End

The back-end or Database engine chosen was SQL. This permits multiple clients on the

network access, retrieval and manipulative right to data whiles protecting the data from

malicious use. It also provides an easy and flexible way of generating quick, easy to use and

comprehensive querying system for information processing. It flexibility and availability as

well as affordability compared to other Database engines made it the best choice for such

project.

33

CHAPTER FIVE

SYSTEM IMPLEMENTATION AND TESTING

5.1. INTRODUCTION

This chapter describes the detail steps taken to code, test and implement the programs that

are designed in the new system. The implementation plan describes how the system will be

developed, deployed, installed and transitioned into an operational system. The stages of

the implementation plan includes;

1. Application Development

2. Testing

3. Documentation

3. File Conversion

4. Changeover

5. Training

5.2. Application Development

This stage involves the implementation of the coding of the system design of geographic

information system. This actual coding was done with visual basic.Net (VB.Net). The coding

process followed the structured approach in developing the application. The design of the

system were classified in modules and coded accordingly. Thesemodules were finally

integrated by using coding that enables them to interlink to each other. Likewise the reports

were coded in different modules according to their functionality in the system application.

5.3. Testing

System testing is an integral and important part of the purpose of the software

development process. This part of the process ensures that bugs ( or errors) are recognized

34

as early as possible to be corrected. System testing ensures that the entire integrated

software system meets requirements. It tests a configuration to ensure known and

predictable results. System testing is based on process descriptions and flows, emphasizing

pre-driven process links and integration points. The tests that were performed for the new system is to achieve its purpose were unit, integrated and acceptance testing.

5.2.1. Unit testing

The first test in the development process is the unit test. The source code was divided into

modules, which in turn were divided into smaller units called units. These units have specific

behaviour. The test done on these units is called unit test. Unit tests ensure that each

unique path of the project performs accurately to the documented specifications and

contains clearly defined and expected results.

5.2.2. Integration testing

Integration testing follows unit testing and precedes system testing. This is testing in which

modules are combined and tested as a group. Modules are typically code modules,

individual application, client and server applications on a network, etc.

5.2.3. Acceptance testing

Testing to verify a product meets user specified requirements.A user does this type o

f testing on a product that is developed externally.

5.3. Documentation

The system documentation is the written descriptions and procedures about a program and

how to use it. A thorough documentation was at each stage of the development process.

For the purpose of future maintenance and enhancement, documentation is essential tool

to make the software complete.

35

Again, documentation would be important to people like users, operators and programmers

in the future as a reference guide.

5.4. File conversion

File conversion is the conversion of the computer data from one form data to another. The

objectives of file conversion is to maintain all of the data,and as much of the embedded

information as possible. But since most of the computer forms were designed to relate to

the existing files, there will not be great variation in the format.

5.5. Changeover

System changeover means the approach used to put the new system in place of the older system.

There are several changeover approaches such as parallel, direct, pilot, and phased operations method.

Direct implementation: This is when the user stops using the old system completely and start using the new system.

Parallel Implementation: This is the strategy whereby the old and the new systems are used

simultaneously until the new system is shown to be reliable.

Phased Implementation: Parts of the new system are phased intothe old one separately at

different times or all at once in groups in this implementation strategy.

Pilot Implementation: This is when the entire system is tied out by only some users of the

system and implemented with the remaining users when the reliability of the new system is proved.

The direct implementation will be used in this project.

In this project, there will be complete changeover from the older system to the new system.

36

5.6. Training

The training of the users who will use the new system is very important. The training will

enable the users adjust more easily and understand what entails in the usage of the new

system.

Therefore, all necessary training activities must be scheduledand coordinated. The training

session will particularly cover the system administrator. Thepeople will be shown how to

operate the system.

5.7. Conclusion

This chapter outlines the procedures involved in the implementation of the new system and

their functionality. The procedures include how the report wasdesigned to complement the

other major procedures such as testing, documentation, file conversion, changeover and

training to make the new system application complete.

37

CHAPTER SIX

CONCLUSION AND RECOMMENDATION

6.1. CONCLUSION

The project has been as challenging as it has been educative to me; it has enabled me to

utilize all the knowledge acquired over the three years of myeducation in the university.

The course taken in System Analysis and Design as well as High-Programming and System

Programming has helped me enormously to define, analyze and develop the program.

The course taken in Data Communication and Networking also helped me know the type of

networks available as well as the clients/server architecture. Choosing the platform to

develop the system was not all that easy but by consulting other programmers, I was able

to pick one, which was expensive and common to develop the system. The need for

consultation is therefore obvious.

After implementing and hosting the system on the web, users and stakeholders will be able

to access and acquire information about the respective facilities within the shortest period

of time and facilitate decision making as far as the facilities are concerned

6.2. RECOMMENDATION

1. It is highly recommended that in order for the system to run smoothly a Qualified

Systems Analyst be employed to see to the day to day smooth running of the system.

2. It is also recommended that a regular training session should be organized for the staff

that will be operating the system and also manuals or guidelines that can be used as

reference when they face any difficulties.

3. The system designer should be consulted on any challenges in using the system.

38

REFERENCES

1. Burmough,P. A. 1998. Principles of geographical informationsystems., http://ukcatalogue.oup.com/product, 21st February,2012.

2. Vanier D.J.2002. “GIS” as an integrated decision support for municipal asset management. www.nrc-cnrc.gc.ca/obj. 4th February,2012.

3. laudon.1998.ManagementInformationSystem.http://www.kulzick.com/stu/typesys.htm. 10th February 2012.

4. Aguilar-Manjarrez, J., 1992. Construction of a GIS for Tobasco State Mexico. Establishment of technicaland social decision models for aquaculture development. MSc Thesis, University of Stirling, UK.

5. Aguilar-Manjarrez, J., Ross, L.G., 1995. Geographical information systems (GIS), environmental modelsfor aquaculture development in Sinaloa state, Mexico.

6. Arnold, W.S., Norris, H.A., White, M.W., 2000. Integrated resource management using geographicalinformation system technology: shellfish aquaculture in Florida, USA. Aquacultural Eng., in press.

38

USER MANUAL

A DISTRICT BASED ONLINE GEOGRAPHIC INFORAMATION SYSTEM FOR HEALTH, EDUCATION, WATER AND SANITATION FACILITIES.

39

INTRODUCTION

To begin using or accessing the detailed data online, the userhas to launch the browser and

type in ‘local host/facility mapping’ in the address bar of the browser. This will load and

displays the homepage. The user can access the data of a particular facility, view the

corresponding map and upload the details of a new facility by clicking the DATA BUTTON,

MAP BUTTON and REPOSITORY BUTTON on the leftmost part of the page respectively.

Shown below is the homepage of the website.

40

The DATA button is used to access the detailed data of a specific facility. The facility form appears when the data button on the leftmost part of the page is clicked.

Shown below is the data form page.

A User is suppose to select only one sector or facility in order to proceed with the search. An

error is generated when two sectors are selected. After selecting the sector the district is

ticked under the administration level. On selecting the Yendidistrict various searches can

be performed. Shown below is the search page for education facilities in Yendi district.

41

The Map page also appears when the user click on the MAP button. The user can view the location of the various educational facilities in the district and their respective communities when education is ticked in the map page.

42

A user can also view the various location of the water and sanitation facilities in the district

by clicking on water and sanitation at the map page.

The download button is used to download any report generated from any search. Shown below is the total number of education facilities in the district

43

New detailed data for new facilities can be uploaded by clicking on the REPOSITORY button

on the homepage. Picture of the facility, description of the facility and the user who is

uploading the data is typed in the boxes.

44

APPENDICES

SOURCE CODES

Data form

Imports System.Data.SqlClientImports System.DataPartial Class frmData Inherits System.Web.UI.Page Dim myClassObj As New mySQLConnection.mySQLCon : Dim sortdir As String Dim myCurrentDS As New DataSet : Dim cSector As String : Dim exObj As New GridViewExportUtil Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged If CheckSelected() = 1 Then Session("Sector") = CheckBoxList1.SelectedItem.Value.Trim Session("curSectorText") = CheckBoxList1.SelectedItem.Text.Trim FillAttributesCombo(cmbFilterColumn, myClassObj.GetAllColumns(Session("Sector"))) cmbFilterColumn.Items.Add("All(*)") cmbFilterColumn.Text = "All(*)" rbLevels.Enabled = True If rbLevels.Items(0).Selected Or rbLevels.Items(1).Selected Then btnSearch.Enabled = True End If Session("curQuery") = "" ElseIf CheckSelected() > 1 Then MsgBox("Please select a single sector at a time") btnSearch.Enabled = False Session("Sector") = "" Session("curSectorText") = "" cmbFilterColumn.Items.Clear() cmbFilterVal.Items.Clear() dgCurrentData.Visible = False iSortDir.ImageUrl = "" lblQueryResult.Text = "No of records: " rbLevels.Enabled = False rbLevels.ClearSelection() Else btnSearch.Enabled = False Session("Sector") = "" Session("curSectorText") = "" cmbFilterColumn.Items.Clear() cmbFilterVal.Items.Clear() dgCurrentData.Visible = False iSortDir.ImageUrl = "" lblQueryResult.Text = "No of records: " rbLevels.Enabled = False rbLevels.ClearSelection() End If 'lblErrorMsg.Text = "The current sector is : " & Session("curSectorText")

End Sub45

Protected Sub rbLevels_SelectedIndexChanged(ByVal sender As Object, ByVal eAs System.EventArgs) Handles rbLevels.SelectedIndexChanged Try cSector = CType(Session("Sector"), String) cmbSublevel.Items.Clear() cmbSublevel.Text = "" cmbFilterColumn.Text = "All(*)" 'Reset the filter so that no filter column is set cmbFilterVal.Items.Clear() 'Remove all items from dropdown value upon change of administrative level If Not cSector.Trim.Equals("") Then dgCurrentData.Visible = False 'Hide the datagrid from the user till proper query is built iSortDir.ImageUrl = "" 'Clear the sort direction of the last direction image lblQueryResult.Text = "No of Records Affected:" 'Revert thedisplay information to the default lblDescription.Text = "" btnSearch.Enabled = False 'Disable the search button until proper query is built If rbLevels.Items(0).Selected Then 'District level selected(index changed from 2 to 0) Session("selLevel") = "District" myClassObj.FillLevelCombo("District", cmbLevelValues) cmbLevelValues.Items.Add("Choose value") cmbLevelValues.Text = "Choose value" lblLevelSelected.Text = "Choose a district" lblSublevel.Text = "" Exit Try End If If rbLevels.Items(1).Selected Then 'Community level selected (index changed from 3 to 1) Session("selLevel") = "Community" myClassObj.FillLevelCombo("Community", cmbLevelValues) cmbLevelValues.Items.Add("Choose value") cmbLevelValues.Text = "Choose value" lblLevelSelected.Text = "Choose a community" lblSublevel.Text = "" Exit Try End If Else MsgBox("No sector selected. Please a sector to view its data") 'Display this error prompt if no sector has been selected btnSearch.Enabled = False End If

Catch ex As Exception MsgBox(ex.Message) End Try End Sub

46

Protected Sub dgCurrentData_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dgCurrentData.PageIndexChanging Try dgCurrentData.SelectedIndex = -1 'Deselecting the selected row upon reload If Not Session("curQuery").ToString.Equals("") Then Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) '& lblOrderBy.Text) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.PageIndex = e.NewPageIndex dgCurrentData.DataBind() dgCurrentData.SelectedIndex = -1 Image1.ImageUrl = "" End If Catch ex As Exception

End Try End Sub

Protected Sub dgCurrentData_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgCurrentData.SelectedIndexChanged If dgCurrentData.SelectedIndex > -1 Then Image1.ImageUrl = "~/Images/" & dgCurrentData.SelectedRow.Cells(2).Text & ".jpg" End If End Sub

Protected Sub dgCurrentData_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgCurrentData.Sorted If lblSortby.Text = "ASC" Then lblSortby.Text = "DESC" iSortDir.ImageUrl = "~/Images/ascending.gif"

Else lblSortby.Text = "ASC" iSortDir.ImageUrl = "~/Images/descending.gif" End If End Sub

Protected Sub dgCurrentData_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles dgCurrentData.Sorting Try If lblSortby.Text.Equals("") Then lblSortby.Text = "ASC" End If If Not Session("curQuery").ToString.Equals("") Then dgCurrentData.SelectedIndex = -1 Image1.ImageUrl = "" lblOrderby.Text = ", 'ORDER BY [" & e.SortExpression & "] "& lblSortby.Text.Trim & "'" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String) & lblOrderby.Text) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) 47

dgCurrentData.DataBind() End If Catch ex As Exception

End Try End Sub 'Check for number of selected items in the checkboxlist Private Function CheckSelected() As Integer Dim mysel As Integer = 0 Try For i As Integer = 0 To CheckBoxList1.Items.Count - 1 With CheckBoxList1 If .Items(i).Selected Then mysel += 1 End If End With Next Catch ex As Exception

End Try Return mysel End Function Private Sub MsgBox(ByVal strMessage As String) 'Begin building the script Dim strScript As String = "<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf

strScript += "alert(""" & strMessage & """)" & vbCrLf strScript += "</SCRIPT>" 'Register the script for the client side ClientScript.RegisterStartupScript(GetType(String), "messageBox", strScript) End Sub Public Sub FillAttributesCombo(ByVal cmb As DropDownList, ByVal dc As Collection) Try cmb.Items.Clear() For i As Integer = 1 To dc.Count If Not (dc.Item(i).ToString.Contains("ID") Or dc.Item(i).ToString.Contains("Latitude") Or dc.Item(i).ToString.Contains("Longitude") Or dc.Item(i).ToString.Contains("Picture")) Then cmb.Items.Add(dc.Item(i)) End If Next Catch ex As Exception MsgBox("Fill column error: " + ex.Message) End Try End Sub Public Sub DisablesButtons() CType(Me.Master.FindControl("btnRepository"), Button).Enabled = True CType(Me.Master.FindControl("btnData"), Button).Enabled = True CType(Me.Master.FindControl("btnLogout"), Button).Enabled = True CType(Me.Master.FindControl("btnMaps"), Button).Enabled = True End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 48

Try If Page.IsPostBack Then If Not CType(Session("curQuery"), String).Equals("") Then Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"),DataSet).Tables(0) dgCurrentData.DataBind() End If Else 'Session("curSectorSel") = "" 'btnFilterSearch.Enabled = False End If Catch ex As Exception

End Try

End Sub

Protected Sub cmbLevelValues_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbLevelValues.SelectedIndexChanged Dim sublevelqry As String = "" Try Session("CurlevelValue") = cmbLevelValues.SelectedItem If Not Session("CurlevelValue").ToString.Equals("") Then Select Case Session("selLevel") Case "District" sublevelqry = "Select distinct([CommunityName]) from tblCommunity where CommunityCode in (select ComID from tblCommunityDetails where District in (select DistrictID from tblDistrict where DistrictName= '" & Session("CurlevelValue").ToString & "')) order by [CommunityName] Asc" lblSublevel.Text = "Communities in " & Session("CurlevelValue").ToString.ToLower & " district" myClassObj.FillLevelCombo(sublevelqry, cmbSublevel) cmbSublevel.Items.Add("Choose value") cmbSublevel.Text = "Choose value" btnSearch.Enabled = True Case Else btnSearch.Enabled = True 'lblSublevel.Visible = False 'cmbSublevel.Visible = False End Select End If Catch ex As Exception Response.Write(ex.Message) End Try End Sub

Protected Sub cmbFilterVal_SelectedIndexChanged(ByVal sender As Object,ByVal e As System.EventArgs) Handles cmbFilterVal.SelectedIndexChanged Try txtFilterVal.Text = cmbFilterVal.Text Catch ex As Exception

End Try End Sub 49

Protected Sub cmbFilterColumn_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbFilterColumn.SelectedIndexChanged Dim DFval As String = "Select Distinct [" Try If cmbFilterColumn.Text <> "All(*)" Then DFval &= cmbFilterColumn.Text.Trim & "] from " & CType(Session("Sector"), String).Trim

myClassObj.FillLevelCombo(DFval, cmbFilterVal) cmbFilterVal.Items.Add("") cmbFilterVal.Text = "" Else cmbFilterVal.Items.Clear() txtfilterVal.Text = "" End If Catch ex As Exception

End Try End Sub

Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDownload.Click Try If dgCurrentData.Rows.Count > 0 Then 'myClassObj.GridviewToExcel(dgCurrentData) dgCurrentData.AllowPaging = False dgCurrentData.DataBind() exObj.Export("QueriedExport.xls", dgCurrentData) myClassObj.WriteLog("Saved") dgCurrentData.AllowPaging = True dgCurrentData.DataBind() Else MsgBox("There is no data to download") End If Catch ex As Exception myClassObj.WriteLog("Excel saving error: " & ex.Message) End Try End Sub

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click Dim currentVal As String = String.Empty 'lblDescription.Text = "" iSortDir.ImageUrl = "" Try dgCurrentData.SelectedIndex = -1 'Deselecting the selected row upon reload dgCurrentData.DataSource = Nothing If rbLevels.Items(0).Selected Then 'District level queries 'Select Case Session("selLevel").ToString.Trim ' Case "District" If Not cmbLevelValues.Text.Trim.Equals("Choose value") Then'if a district is chosen do this If Not cmbFilterColumn.Text.Equals("All(*)") Then ' if a filter column is chosen then do this If Not (cmbSublevel.Text.Trim.Equals("Choose value") Or cmbSublevel.Text.Trim.Equals("")) Then 'if sublevel value is chosen do this

50

If txtFilterVal.Text.Trim IsNot String.Empty Then 'if a value is provided for the filter value do this Session("curQuery") = "Exec spGetCommunityCodes '" & Session("Sector").ToString.Trim & "', 'Community','" & cmbSublevel.Text.Trim & "', '" & cmbFilterColumn.Text.Trim & "', '" & txtFilterVal.Text.Trim & "'" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.DataBind() Else MsgBox("No value provided for the selected column") End If currentVal = cmbLevelValues.Text & " DISTRICT " lblDescription.Text = currentVal & "--> " & cmbSublevel.Text.Trim Else 'if no sublevel is selected If txtFilterVal.Text.Trim IsNot String.Empty Then 'if a value is provided for the filter value do this Session("curQuery") = "Exec spGetCommunityCodes '" & Session("Sector").ToString.Trim & "', 'District', '" & cmbLevelValues.Text.Trim & "', '" & cmbFilterColumn.Text.Trim & "', '"& txtFilterVal.Text.Trim & "'" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.DataBind() Else MsgBox("No value provided for the selected column") End If currentVal = cmbLevelValues.Text & " DISTRICT " lblDescription.Text = currentVal End If Else 'if no filter column is selected If Not (cmbSublevel.Text.Trim.Equals("Choose value") Or cmbSublevel.Text.Trim.Equals("")) Then 'if sublevel value is chosen do this Session("curQuery") = "Exec spGetCommunityCodes'" & Session("Sector").ToString.Trim & "', 'Community', '" & cmbSublevel.Text.Trim & "', null,null" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0)

dgCurrentData.DataBind() currentVal = cmbLevelValues.Text & " DISTRICT " lblDescription.Text = currentVal & "--> " & cmbSublevel.Text.Trim Else 'if no sublevel is selected Session("curQuery") = "Exec spGetCommunityCodes'" & Session("Sector").ToString.Trim & "', 'District', '" & cmbLevelValues.Text.Trim & "', null,null" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource =

51

CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.DataBind() currentVal = cmbLevelValues.Text & " DISTRICT " lblDescription.Text = currentVal End If End If End If 'currentVal = cmbLevelValues.Text & " DISTRICT" ElseIf rbLevels.Items(1).Selected Then 'Case "Community" If Not cmbLevelValues.Text.Trim.Equals("Choose value") Then If Not cmbFilterColumn.Text.Equals("All(*)") Then If txtFilterVal.Text.Trim IsNot String.Empty Then Session("curQuery") = "Exec spGetCommunityCodes'" & Session("Sector").ToString.Trim & "', 'Community', '" & cmbLevelValues.Text.Trim & "', '" & cmbFilterColumn.Text.Trim & "', '" & txtFilterVal.Text.Trim & "'" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.DataBind() Else MsgBox("No value provided for the selected column") End If Else 'if no filter column is selected Session("curQuery") = "Exec spGetCommunityCodes '" & Session("Sector").ToString.Trim & "', 'Community', '" & cmbLevelValues.Text.Trim & "', null,null" Session("curDataset") = myClassObj.FillDataSet(CType(Session("curQuery"), String)) dgCurrentData.DataSource = CType(Session("curDataset"), DataSet).Tables(0) dgCurrentData.DataBind() End If End If currentVal = cmbLevelValues.Text & " COMMUNITY "

lblDescription.Text = currentVal 'End Select End If 'txtfilterVal.Text = String.Empty 'cmbFilterVal.Text = "" If Session("curDataset") IsNot Nothing Then lblQueryResult.Text = "NO OF " & CType(Session("curSectorText"), String).Trim.ToUpper & " FACILITIES " & ": " & CType(Session("curDataset"), DataSet).Tables(0).Rows.Count dgCurrentData.Visible = True 'currentVal.Trim & End If Catch ex As Exception 'lblErrorMsg.Text = "Filter Error: " + ex.Message MsgBox("Filter error: " & ex.Message) End Try End SubEnd Class

52

Map Form

Partial Class newMap Inherits System.Web.UI.Page

Protected Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged Dim myMap As String Try 'MsgBox("I've entered the radio button") Select Case RadioButtonList1.SelectedIndex Case 0 myMap = "Education" ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "Loadmap", "LoadMap('" & myMap & "');", True) '-- Not Working: ClientScript.RegisterStartupScript(Me.GetType(), "Loadmaps", "LoadMap(" & myMap & ");", True) Case 1 myMap = "Health" ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "Loadmap", "LoadMap('" & myMap & "');", True) Case 2 myMap = "WatSan" ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "Loadmap", "LoadMap('" & myMap & "');", True)

End Select Catch ex As Exception MsgBox("Error from the map options.....") End Try

End Sub Private Sub MsgBox(ByVal strMessage As String) 'Begin building the script Dim strScript As String = "<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf strScript += "alert(""" & strMessage & """)" & vbCrLf strScript += "</SCRIPT>" 'Register the script for the client side ClientScript.RegisterStartupScript(GetType(String), "messageBox", strScript) End SubEnd Class

Repository

Imports System.DataImports System.IOImports System.WebImports System.ConfigurationImports System.Web.UIImports System.Web.SecurityImports System.Web.UI.HtmlControlsImports System.Web.UI.WebControlsImports System.Web.UI.WebControls.WebParts

53

Partial Class frmRepository Inherits System.Web.UI.Page Dim myCls As New mySQLConnection.mySQLCon : Dim savedFile As String = String.Empty Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load lbldate.Text = Now.Date End Sub Private Sub MsgBox(ByVal strMessage As String) 'Begin building the script Dim strScript As String = "<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf strScript += "alert(""" & strMessage & """)" & vbCrLf strScript += "</SCRIPT>" 'Register the script for the client side ClientScript.RegisterStartupScript(GetType(String), "messageBox", strScript) End Sub

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim acclevel As Integer = 1 Try 'acclevel = CType(Session("Alevel"), Integer) If acclevel > 0 Then If DoUpload() Then If txtUploadBy.Text.Equals(String.Empty) Or FileUpload1.FileName.Equals(String.Empty) Then MsgBox("Fill all parameters before you upload...") File.Delete(savedFile) 'Delete uploaded file if unable to record in database Else myCls.SaveDetails(txtUploadBy.Text.Trim, Now.Date, FileUpload1.FileName, txtDescription.Text.Trim) MsgBox("Upload successful") txtUploadBy.Text = "" : txtDescription.Text = "" 'Clear all entries made after successful save End If Else MsgBox("Upload not successful. Check file and try again.") End If Else MsgBox("You don't have necessary privilege to upload. Contact Administrator") End If Catch ex As Exception myCls.WriteLog("Date: " & Now.Date & " Error: " & ex.Message) End Try End Sub Private Function DoUpload() As Boolean Try 'Receive the file uploaded from the web form and assign to the variable Dim f_Received As String = FileUpload1.PostedFile.FileName 'Get the file name of the received file Dim f_name As String = Path.GetFileName(f_Received) 'check if a directory has been opened today already Dim newFolder As String = Server.MapPath("~/UploadFiles/" &

54

lbldate.Text.Trim.Replace("/", "_") & "/") If Not (Directory.Exists(newFolder)) And Not (f_name.Equals(String.Empty)) Then 'creating a directory to save today's uploads Directory.CreateDirectory(newFolder) End If 'Defining path where the file will be uploaded to If Not newFolder.Equals(String.Empty) Then

savedFile = newFolder & f_name FileUpload1.PostedFile.SaveAs(savedFile) MsgBox("Files uploaded successfully...") 'If FileUpload1.PostedFile.ContentType = "application/ms-excel" Then

'Else

' Return False 'End If End If Catch ex As Exception MsgBox("Error while uploading....." + ex.Message) End Try Return True 'If codes are executed up to this point then upload wassuccessful hence return true End FunctionEnd Class

Home Page

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Homepage.aspx.vb" Inherits="Homepage" title="Home Page" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:Panel ID="Panel1" runat="server" Height="637px" Width="811px"> <div> <h1> About the project</h1> <asp:Image ID="Image1" runat="server" ImageUrl="~/images/map.gif" Width="802px" ImageAlign=Middle Height="377px" /> </div> <div>This facility database application, seeks to make available spatial data as well as attribute data on all identifiable and existing facilities

in the country. Images of existing facilities are attached to their

corresponding data and shall be updated as and when the facility changes<br /> It will form the basis for all facility based projects within

the district<br /> <br /> For how to use and find your way about the interface follow this<a href=frmHelp.aspx>help link</a></div>

55 <div> <h3>OVERVIEW OF THE CONTROLS</h3> <h6>DATA Button: This button leads you to the data attribute page where you can query and download the map data</h6> </div> </asp:Panel></asp:Content>

Master Page

Partial Class MasterPage Inherits System.Web.UI.MasterPage

Protected Sub btnData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnData.Click Server.Transfer("~/frmData.aspx", False) End Sub

'Protected Sub btnLogout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogout.Click ' Try ' Session("Login") = False ' 'DisablesButtons() ' Server.Transfer("~/login.aspx", False) ' Catch ex As Exception

' End Try 'End Sub Public Sub DisablesButtons() btnData.Enabled = False btnMaps.Enabled = False btnRepository.Enabled = False 'btnLogout.Enabled = False End Sub Public Sub EnablesButtons() btnData.Enabled = True btnMaps.Enabled = True btnRepository.Enabled = True 'btnLogout.Enabled = True End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load EnablesButtons() 'If CType(Session("Login"), Boolean) Then ' EnablesButtons() 'Else ' DisablesButtons() 'End If End Sub

Protected Sub btnMaps_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMaps.Click Server.Transfer("~/newMap.aspx", False) End Sub

Protected Sub btnRepository_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRepository.Click Server.Transfer("~/frmRepository.aspx", False) End Sub

56 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Server.Transfer("~/Homepage.aspx", False) End SubEnd Class

Download Utility

Imports SystemImports System.DataImports System.ConfigurationImports System.IOImports System.WebImports System.Web.SecurityImports System.Web.UIImports System.Web.UI.WebControlsImports System.Web.UI.WebControls.WebPartsImports System.Web.UI.HtmlControls

Public Class GridViewExportUtil

Public Sub Export(ByVal fileName As String, ByVal gv As GridView) HttpContext.Current.Response.Clear() HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName)) HttpContext.Current.Response.ContentType = "application/ms-excel" Dim sw As StringWriter = New StringWriter Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) ' Create a form to contain the grid Dim table As Table = New Table table.GridLines = gv.GridLines ' add the header row to the table If (Not (gv.HeaderRow) Is Nothing) Then GridViewExportUtil.PrepareControlForExport(gv.HeaderRow) table.Rows.Add(gv.HeaderRow) End If ' add each of the data rows to the table For Each row As GridViewRow In gv.Rows GridViewExportUtil.PrepareControlForExport(row) table.Rows.Add(row)

Next ' add the footer row to the table If (Not (gv.FooterRow) Is Nothing) Then GridViewExportUtil.PrepareControlForExport(gv.FooterRow) table.Rows.Add(gv.FooterRow) End If ' render the table into the htmlwriter table.RenderControl(htw) ' render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString) HttpContext.Current.Response.End() End Sub

' Replace any of the contained controls with literals Private Shared Sub PrepareControlForExport(ByVal control As Control) Dim i As Integer = 0 Do While (i < control.Controls.Count) Dim current As Control = control.Controls(i) If (TypeOf current Is LinkButton) Then 57 control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current,LinkButton).Text)) ElseIf (TypeOf current Is ImageButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current,ImageButton).AlternateText)) ElseIf (TypeOf current Is HyperLink) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current,HyperLink).Text)) ElseIf (TypeOf current Is DropDownList) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current,DropDownList).SelectedItem.Text)) ElseIf (TypeOf current Is CheckBox) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current,CheckBox).Checked)) 'TODO: Warning!!!, inline IF is not supported ? End If If current.HasControls Then GridViewExportUtil.PrepareControlForExport(current) End If i = (i + 1) Loop End SubEnd Class

---------------------------------------------------

MyWebClasses

Imports Microsoft.VisualBasicImports System.Data.SqlClientImports System.DataImports System.WebImports System.IOPublic Class mySQLConnection 'Opening a connection to access the SQL Server Friend Shared WebConSQL As SqlConnection : Friend Shared CurPixByte As Byte() Public Class mySQLCon

Public Function SQLConnector() As SqlConnection Dim str As String = String.Empty Try WebConSQL = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("AppSqlServer").ConnectionString) WebConSQL.Open() If WebConSQL.State = ConnectionState.Open Then WebConSQL.Close() End If Catch ex As Exception WriteLog("Date: " & Now.Date & " Error: " & ex.Message) End Try Return WebConSQL 58

End Function 'Module to fill administrative level associated drop downs. Public Sub FillLevelCombo(ByVal L As String, ByVal C As DropDownList) Dim qry As String = String.Empty : Dim sCmd As New SqlCommand(): Dim sRead As SqlDataReader Dim CanExecute As Boolean = False : Dim i As Integer = 0 : Dim WebCon As New SqlConnection Try WebCon = SQLConnector() sCmd.Connection = WebCon 'Pass web application's global sqlconnection object to the current command object If sCmd.Connection.State = Data.ConnectionState.Closed Then sCmd.Connection.Open() End If 'Determine which sql command to execute based on the level selected Select Case L Case "Regional"

qry = "Select RegionName from tblRegion order by RegionName Asc" CanExecute = True Case "District" qry = "Select DistrictName from tblDistrict order by DistrictName Asc" CanExecute = True Case "Community" qry = "Select distinct [CommunityName] from tblCommunity order by [CommunityName] Asc" CanExecute = True Case Else qry = L CanExecute = True End Select If CanExecute Then sCmd.CommandText = qry sCmd.CommandType = Data.CommandType.Text sRead = sCmd.ExecuteReader C.Items.Clear() While sRead.Read With C.Items .Add(sRead.Item(0).ToString.ToUpper.Trim) End With 'i += 1 End While End If Catch ex As Exception WriteLog("Date: " & Now.Date & " Error: " & ex.Message) If sCmd.Connection.State = Data.ConnectionState.Open Then sCmd.Connection.Close() End If End Try If sCmd.Connection.State = Data.ConnectionState.Open Then sCmd.Connection.Close() End If End Sub 'Create a dataset for the appropriate selection Public Function FillDataSet(ByVal q As String) As DataSet Dim Ds As New DataSet : Dim Da As SqlDataAdapter : Dim Cmd As

59

New SqlCommand : Dim mCnn As New SqlConnection() Try 'Ds = Nothing mCnn = SQLConnector() With Cmd .CommandText = q .CommandType = CommandType.Text .Connection = mCnn If .Connection.State = ConnectionState.Closed Then

.Connection.Open() End If Da = New SqlDataAdapter(Cmd) Da.Fill(Ds, "CurrentData") End With Catch ex As Exception WriteLog("My dataset filling error " + ex.Message + ex.ToString) If Cmd.Connection.State = ConnectionState.Open Then Cmd.Connection.Close() End If End Try If Cmd.Connection.State = ConnectionState.Open Then Cmd.Connection.Close() End If Return Ds End Function 'Storing errors in an errorlog file on the server Public Sub WriteLog(ByVal msg As String) If Not msg.ToString.Contains("Thread was being aborted") Then Dim context As HttpContext = HttpContext.Current Dim _path As String _path = "~/ErrorLog\ErrorLog.txt" Dim path As String = context.Server.MapPath(_path) Dim writer As New System.IO.StreamWriter(path, True) writer.WriteLine(msg + " " + DateTime.Now.ToString) writer.Close() End If End Sub 'Exporting the query results to an excel sheet Public Sub GridviewToExcel(ByVal gv As GridView) Try With HttpContext.Current .Response.Clear() .Response.AddHeader("content-disposition", "attachment;filename=offlinelist.xls") .Response.Charset = "" .Response.Cache.SetCacheability(HttpCacheability.NoCache) .Response.ContentType = "application/vnd.xls" Dim stringWrite As New System.IO.StringWriter() Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite) gv.RenderControl(htmlWrite) .Response.Write(stringWrite.ToString()) .Response.[End]() End With Catch ex As Exception WriteLog(ex.Message + ex.StackTrace) End Try

60

End Sub Public Function Checklogin(ByVal U As String, ByVal P As String) AsString Dim C As New SqlCommand : Dim cnt As Integer = 0 : Dim Alevel As String = String.Empty Try C.CommandText = "Select count(*) from tblLogins where [Username]='" & U.Trim & "' and [Password]='" & P.Trim & "'" 'return the count of all logins with same credentials as entered C.Connection = SQLConnector() If C.Connection.State = ConnectionState.Open Then cnt = C.ExecuteScalar Else C.Connection.Open() cnt = C.ExecuteScalar End If If cnt > 0 Then 'pass = True C.CommandText = "Select Accesslevel from tblLogins where [Username]='" & U.Trim & "' and [Password]='" & P.Trim & "'" 'return the accesslevel the user is operating with C.Connection = SQLConnector() If C.Connection.State = ConnectionState.Open Then Alevel = C.ExecuteScalar Else C.Connection.Open() Alevel = C.ExecuteScalar End If End If Catch ex As Exception WriteLog("Date: " & Now.Date & " Error: " & ex.Message) If C.Connection.State = ConnectionState.Open Then C.Connection.Close() End If End Try If C.Connection.State = ConnectionState.Open Then C.Connection.Close() End If Return Alevel End Function Public Function GetAllColumns(ByVal tbl As String) As Collection Dim q As String = "Exec spGetTableColumns '" & tbl & "'" Dim c As New SqlCommand() : Dim s As String = "" : Dim r As SqlDataReader : Dim cl As New Collection Try c.CommandType = CommandType.Text c.CommandText = q c.Connection = SQLConnector() If c.Connection.State = ConnectionState.Open Then r = c.ExecuteReader Else

c.Connection.Open() r = c.ExecuteReader End If 's = "" While r.Read If Not r.Item(0).ToString.Trim.Equals("Community") Then s &= tbl & ".[" & r.Item(0).ToString.Trim & "]," cl.Add(r.Item(0).ToString.Trim) End If 61 End While 's = s.Remove(s.Length - 1) 's = "Select tblCommunity.[CommunityName]," & s & " from " & tbl & ",tblCommunity where tblCommunity.CommunityCode=" & tbl & ".ComID " Catch ex As Exception WriteLog("Date: " & Now.Date & " Error: " & ex.Message) If c.Connection.State = ConnectionState.Open Then c.Connection.Close() End If End Try If c.Connection.State = ConnectionState.Open Then c.Connection.Close() End If Return cl End Function Private Function LoadPicture(ByVal PictureFile As String, ByVal w As String) As Byte() Dim sqlPictureBuffer As Byte() Try If PictureFile <> Nothing Then Dim picstream As New FileStream(PictureFile, FileMode.Open, FileAccess.Read) Dim info As New FileInfo(PictureFile) Dim Preader As New BinaryReader(picstream) sqlPictureBuffer = Preader.ReadBytes(CInt(info.Length)) Preader.Close() Else

End If Catch ex As Exception

End Try Return sqlPictureBuffer End Function ' Protected Sub download(ByVal dt As DataTable) ' Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte()) ' Response.Buffer = True ' Response.Charset = "" ' Response.Cache.SetCacheability(HttpCacheability.NoCache)

' Response.ContentType = dt.Rows(0)("ContentType").ToString() 'Response.AddHeader("content-disposition", "attachment;filename=" '& dt.Rows(0)("Name").ToString()) ' Response.BinaryWrite(bytes) ' Response.Flush() ' Response.End() ' End Sub Public Function ReturnData(ByVal Sector As String, ByVal AdminlevelAs String, ByVal levelValue As String, ByVal Col As String, ByVal colval AsString) As DataSet Dim c As New SqlConnection : Dim ds As New DataSet : Dim da As New SqlDataAdapter : Dim cmd As New SqlCommand Try c = SQLConnector() If c.State = ConnectionState.Open Then With cmd .CommandText = "Exec spGetCommunityCodes '" &

62

Sector & "', '" & Adminlevel & "', '" & levelValue & "', '" & Col & "', '" & colval & "'" .CommandType = CommandType.Text .Connection = c da = New SqlDataAdapter(cmd) da.Fill(ds, "CurrentData") End With Else c.Open() With cmd .CommandText = "Exec spGetCommunityCodes '" & Sector & "', '" & Adminlevel & "', '" & levelValue & "', '" & Col & "', '" & colval & "'" .CommandType = CommandType.Text .Connection = c da = New SqlDataAdapter(cmd) da.Fill(ds, "CurrentData") End With End If If c.State = ConnectionState.Open Then c.Close() End If Catch ex As Exception If c.State = ConnectionState.Open Then c.Close() End If End Try Return ds End Function

Public Sub SaveDetails(ByVal Uname As String, ByVal Udate As Date, ByVal fname As String, ByVal Udes As String) Dim C As New SqlCommand Try C.CommandText = "Exec spUploads '" & Uname.Trim & "','" & Udate & "','" & fname.Trim & "','" & Udes.Trim & "'" 'return the count of all logins with same credentials as entered C.CommandType = CommandType.Text C.Connection = SQLConnector() If C.Connection.State = ConnectionState.Open Then C.ExecuteNonQuery() Else C.Connection.Open() C.ExecuteNonQuery() End If Catch ex As Exception

End Try End Sub End Class

End Class

Web config (Connection String to database)

<appSettings/><connectionStrings>

<add name="AppSqlServer" connectionString="Data Source=CILVIA\SQLEXPRESS;Initial Catalog=EMMSDAGdb;Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings> 63

Stored Procedures (For the SQL database)

Codes1 (Selecting data from database approach 1)

USE [EMMSDAGdb]GO

/****** Object: StoredProcedure [dbo].[spGetCommunityCode2] Script Date: 06/01/2012 12:52:43 ******/SET ANSI_NULLS ONGO

SET QUOTED_IDENTIFIER ONGO

-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>

-- Description: <Description,,>-- =============================================CREATE PROCEDURE [dbo].[spGetCommunityCode2]

@Sector as varchar(50),@Level as varchar(50),@LevelValue as varchar(50)

ASBEGIN

Declare @sql as varchar(max)if @Level is not nullBegin

if @Level='National'begin

select @sql = 'select * from ['+ @Sector +']' exec(@sql)

endelse if @Level= 'Regional'begin

select @sql = 'SET QUOTED_IDENTIFIER OFF select * from ['+ @Sector +'] where Community in (' + dbo.fnRegionCommunityCode(@LevelValue)+ ')'

exec(@sql)endelse if @Level='District'begin

select @sql = 'SET QUOTED_IDENTIFIER OFF select * from ['+ @Sector +'] where Community in (' + dbo.fnDistrictCommunityCode(@LevelValue)+ ')'

exec(@sql)endelsebegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select * from ['+ @Sector +'] where Community in (' + dbo.fnReturnCommunityCode(@LevelValue)+ ')'

exec(@sql)end

EndEND GO

64

Codes 2 (Retrieving data from the database)

USE [EMMSDAGdb]GO

/****** Object: StoredProcedure [dbo].[spGetCommunityCodes] Script Date: 06/01/2012 12:54:25 ******/SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ONGO

CREATE PROCEDURE [dbo].[spGetCommunityCodes]@Sector as varchar(50),@Level as varchar(50),@LevelValue as varchar(50),@Column as varchar(50)=null,@ColVal as varchar(50)=null,@Orderby as varchar(50)=null

ASBEGIN

Declare @sql as varchar(max)if @Level is not nullBegin

if @Level='National'begin

if @Column is not null begin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and ('+ @Sector + '.[' + @Column + '] ="' + @ColVal + '") '

exec(@sql+@Orderby)end

elsebegin

select @sql = 'select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where tblCommunity.CommunityCode=' +quotename(@Sector) + '.Community '

exec(@sql+@Orderby)end

endelse if @Level= 'Regional'begin

if @Column is not nullbegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityCode in (select ComID from

65

tblCommunityDetails where District in (select DistrictID from tblDistrict where Region=(select RegionID from tblRegion where RegionName="'+ @LevelValue + '")))) and ('+ @Sector+ '.[' + @Column + '] = "' + @ColVal + '")) '

exec(@sql+@Orderby)end

elsebegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityCode in (select ComID from tblCommunityDetails where District in (select DistrictID from tblDistrict where Region=(select RegionID from tblRegion where RegionName="'+ @LevelValue + '"))))) '

exec(@sql+@Orderby)end

endelse if @Level='District'begin

if @Column is not nullbegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityCode in (select ComID from tblCommunityDetails where District in (select DistrictID from tblDistrict where DistrictName="' + @LevelValue + '"))) and ('+ @Sector + '.[' + @Column + '] = "' + @ColVal + '")) '

exec(@sql+@Orderby)end

elsebegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityCode in (select ComID from tblCommunityDetails where District in (select DistrictID from tblDistrict where DistrictName="' + @LevelValue + '")))) '

exec(@sql+@Orderby)end

endelsebegin

if @Column is not nullbegin

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from

tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityName ="' + @LevelValue + '") and ('+ @Sector+ '.[' + @Column + '] = "' + @ColVal + '")) '

exec(@sql+@Orderby)end

elsebegin 66

select @sql = 'SET QUOTED_IDENTIFIER OFF select tblCommunity.CommunityName,' + quotename(@Sector) + '.* from tblCommunity,'+ quotename(@Sector) + ' where (tblCommunity.CommunityCode=' + quotename(@Sector) + '.Community) and (Community in (select CommunityCodefrom tblCommunity where CommunityName ="' + @LevelValue + '")) '

exec(@sql+@Orderby)end

endEnd

END

--+ 'order by [' + @Orderby + ']'--exec spGetCommunityCodes1 'tblEducationFacilities','National',null,null,null,' order by EF_Name desc'--exec spGetCommunityCodes1 'tblEducationFacilities','National','order by EF_Name desc'GO

Codes 3 (Populating dropdowns)

USE [EMMSDAGdb]GO

/****** Object: StoredProcedure [dbo].[spGetTableColumns] Script Date: 06/01/2012 12:55:09 ******/SET ANSI_NULLS ONGO

SET QUOTED_IDENTIFIER ONGO

-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>-- Description: <Description,,>-- =============================================CREATE PROCEDURE [dbo].[spGetTableColumns]

@Table as varchar(50)ASBEGINdeclare @sql as varchar(max)

select @sql= 'SET QUOTED_IDENTIFIER OFF Select column_name from information_schema.columns where table_name = "' + @Table + '"'exec(@sql)END

GO

Codes 4 (uploading data)

USE [EMMSDAGdb]GO

/****** Object: StoredProcedure [dbo].[spUploads] Script Date: 06/01/2012 12:55:47 ******/SET ANSI_NULLS ONGO

SET QUOTED_IDENTIFIER ONGO

67-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>-- Description: <Description,,>-- =============================================CREATE PROCEDURE [dbo].[spUploads]

-- Add the parameters for the stored procedure here@Uname as varchar(max),@Udate as datetime,@Fname as varchar(max),@Description as varchar(max)

ASBEGIN

-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;

insert into tblUploads (UploadedBy,DateUploaded,[FileName],Description)values(@Uname,@Udate,@Fname,@Description)END

GO

68