A collaboration between

Università degli Studi di Padova

and Universidad de Murcia

Facoltà di Scienze MM. FF. NN. Laurea in Informatica

Management Software Refactoring .NET Programming

Graduate: Vaponi Samuel Professor: Filè Gilberto

Academic year 2010/2011 1 Index

1. Introduction...... 4 Consideration...... 4 Task...... 4 Activities...... 5

2. System Descriptions...... 6 Data downloading process...... 6 Components...... 8 • Management software...... 9 • ...... 11 • Automa...... 12 • Data loading application...... 12

3. Software Requirements...... 13 Security management...... 13 Data management...... 14 Client management...... 14 Order management...... 14 Maintenance request management...... 15 Warehouse management...... 16 Technician management...... 16 Account management...... 16

4. Software Development...... 17 Project structure...... 17 • Solutions...... 17 • Projects...... 18

2 • Modules...... 18

5. Relevant Classes...... 20 Data retrieval...... 21 • DataSet...... 21 • DataAdapter...... 22 • TableAdapter...... 23 • DataReader...... 24 • SqlCommand...... 25 GUI creation...... 26 • Form...... 26 • DataGridView...... 27 • BindingSource...... 27

6. Software Implementation...... 28 Security management ...... 28 Client management...... 34 Order management...... 41 Maintenance request management...... 47

7. Technology Used in Development Process...... 50 .NET Framework...... 51 C# programming language...... 54 Visual Studio 2008...... 55 SQL Server 2008...... 56 EMS SQL Manager 2008...... 58 WinAutomation...... 59

Appendixes...... 60 I. The Company...... 60 II. Database Schema...... 61

Conclusions...... 65

Bibliography...... 66

3 1. Introduction

Considerations During the training period the student participated in the refactoring of the internal management software currently in use at the Mencia Comunicaciones S.L., which is the company where the Stage took place. The management software was developed on Velneo™ platform (a Spanish platform that includes components for developing and deploying applications). This software has been used for more than ten years and it is now obsolete. Additionally, managerial needs have changed over the years, leading the administrator of the company to consider a full modernization of the system, exploiting the potential of new technologies available today on the market. New managerial needs of the company include a full mastery of business information and its fruition through user-friendly interfaces, charts and summary documents (possibly in popular formats like Microsoft Excel or PDF), all geared to facilitate the decision-making process and the planning of business activities. As the company works on behalf of a bigger one, there was another reason that led to the decision to develop a new management software: the need to automate the downloading of business information from the web portal of ONO, the leader company for whom Mencia Comunicaciones S.L. works for (more information about company's organization, see Appendix I: The Company). The automation of this procedure will result in a clear savings of time and money, although the possibility of integrating this process into the current software is not feasible since it would lead to conflicts over the management of data. The new system aims to meet the new managerial needs of the company also considering the automation of the downloading process. This way, the management of data and the planning of business activities are improved for the benefit of the company.

Task At the beginning of the training period the development of the system had already begun. All components involved with the automated downloading process of data were already developed, thus including the database that stores business information. Therefore, the company required the presence of a student with knowledge about object-oriented programming and Component Object Model (COM) , who could start the implementation of the management software itself. For the implementation it was decided to use technology already employed in the company: .NET Framework and Visual Studio 2008 (more information about technology and tools, see 7th Chapter: Technology Used in Development Process).

4 As mentioned the management software is just a part of the system, since it implements a reduced set of features, excluding everything related with the automated downloading process and data storing. The development of the management software identifies the mean task assigned to the student for the period of training.

Activities Once incorporated in the company, the student was completely devoted to the study of technology and development tools adopted in the company. It was necessary to study C# and to deepen its differences with C++ and Java, which were the programming languages already known. Much time was also used to get familiar with Visual Studio 2008 and the .NET platform. This step took almost a week, during which the student learnt how to develop basic GUI and controls using the visual editor designer provided by the IDE. Further the student worked with the support of the technical manager (the tutor) in understanding and planning the project. During this step the tutor explained how to access the database through the intranet, which functions to use for the database authentication and the methods to use to extract data. Later, when all the basics were acquired, started the design of software structure. It was necessary to identify the management areas, also according with the distinction adopted by the current software, and comprehend them. This step was rather long and interspersed with periods of implementation where the student worked alone. Better said, design and comprehension of each management area lasted throughout the entire implementation process, focusing on one area at a time.

The principal activities of the period of training were:

• Understanding the needs of the company. The student participated in a series of meetings aimed, firstly, to provide a general idea on the functionality of the software and further, during the implementation process, to specify what special requirements the software must comply.

• C# programming. This activity covered the development of software modules in C# (object-oriented programming language developed by Microsoft within the initiative .NET) using the integrated development environment Visual Studio 2008 and the suite of .NET Framework products.

• Database management. Along with software development was necessary to understand and interface a SQL Server database, which stores all business information. Although the Visual Studio offers a graphic tool to manage the SQL Server instance connected to the project, to facilitate this activity was available a database management software: EMS SQL Manager for SQL Server (see 7th Chapter: Technology Used in Development Process).

5 2. System Description

The new system is an improved version of the existing one. It performs all the functions provided by the management software currently in use in the company, plus the automation of data downloading from the leader company's web portal. The system currently in use is entirely composed by the management software and the database, while the new system is divided into more components with specific tasks. To deeply understand the choice of dividing the system into different components and to get to know why those components are needed to improve the productivity and efficiency of the company, first we will deepen the process of data downloading and how it is executed (or better, not executed) by the system currently in use.

Data downloading As the company works on behalf of a larger company, there is a need for a continuous exchange of information between the two companies, predominantly from Ono toward Mencia Comunicaciones. This information coming from the leader company is identified as external information, whose management results rather complicated since involves data with an imposed syntax and coming from an external source. The external information involves all data about services that are commissioned to the company, such as client data, order and maintenance request data, and related information. All this information is contained in XML files that ONO publishes on its web portal. Each associated company of ONO must access the web portal and download the files related to its area of expertise. According to that information each company will plan its business activities. This process is extremely simple and repetitive, and it can be summarized in the following steps:

• Access to the web portal at https://ono.toadirect.com with user-name and password (assigned by Ono to all associated companies). • Select a city and a date. • Export the XML file to a local directory. • Interpret data contained into the XML file and update the database. • Repeat the process for each city and date of interest.

6 All these steps are currently executed by hand, meaning that there are people employed to carry out this process, with an unjustified waste of time and labour. Further, to update the database, the employees need to fill out the appropriate forms provided by the current management software with data extracted from the XML files, whose syntax is rather complex. It is clear that this process would be easily executed by a computer, with obvious positive implications: less labour and faster results. In fact, the data downloading process employed in the new system is fully automated through the use of components designed on purpose.

7 Components

To integrate the automated downloading process the new system was divided into different components, which perform a limited set of functions. This choice was dictated by the different nature of the functions that the system had to do. That way each component could be developed independently and use the most appropriate and efficient technology for its task. The components that compose the system are: • Management Software. It is the mean component of the system and its task is to provide a basic and easy access to data through various media, to help the management of the company and the planning of business activities. • Database. It is a database managed by SQL Server database engine and its role is to collect all data needed for the management of the company. • Automa. It is a compiled job built with WinAutomation™ and its task is to automate the process of data downloading from the web portal of ONO. • Data Loading Application. It is a console application and its task is to interpret the information downloaded by the Automa and update the database with most recent data. It can be consider as a sub-routine of the Automa.

The Database and the components covering the automated downloading process are at the base of the system since the functions performed by these components are aimed to assist the Management Software and reside in the lower tiers of the application. Considering a three-tier architecture they implement respectively the Data Tier and the Logic Tier of the application, in order to keep the Database updated with the latest data. The Management Software is the tool of relevance of the system and the component with which the user interacts.

8 As mentioned the development of the Management Software identifies the task assigned to the student for the training period and it will be discussed throughout the whole document. The other components were not developed by the student hence they will be superficially discussed just to give the reader a complete idea of the system.

Management Software The Management Software is a windows application built to run on Windows operating systems and based on .NET Framework. It was developed with Visual Studio 2008 using C#. The Management Software is the mean component of the system and resides on top of the system's architecture. It is the only component that implements the Presentation Layer, thus also the only one with which the user interacts. The interaction with the user is done through a graphic interface, built with graphic components provided by the framework (more information about the components, see 5th Chapter: Relevant Classes – GUI Creation). These components belong to the Base Class Library which offers built-in solutions such as windows, controls and dialog boxes, up to more complex solutions like charts and data grid-views. The Logic Tier implemented by the software enclose all modules for accessing data source. Here there are all Component Object Model (COM) objects that belong to the ADO.NET library. These components are able to encompass external entities in order to use them in the paradigm of object-oriented programming. Specifically ADO.NET components are used to retrieve and manipulate data in (more information about components, see 5th Chapter: Relevant Classes – Data Retrieval).

While other components of the system ensure actuality, consistency and integrity of data, the Management Software is the application that works with that data, providing a tool for the fruition and the management of information.

9 The main purpose of the Management Software is to help the staff of the company manage information, in order to efficiently plan the business’ activities. Such information can be divided into two categories: internal or external of the company.

• Internal Information. It is that information of interest to the company, in regard to the aspects of internal management and administration. This category includes information on the yield of technicians, the technical material in stock and the economic-administrative information.

• External Information. It is that information directly coming from the leader company ONO, reachable through the appropriate web portal with self-possessed access. This category includes information about the services commissioned to the company, thus data about clients, orders and requests of maintenance.

Although the management of internal information proves relatively simple, since all of the data has an internal origin in the company, the management of the external information is rather complicated since involves data coming from an external source. This information is not always safe and may have inconsistencies; the software is in charge of managing those exceptions.

Management Areas To simplify the information management were identified some management areas. Each management area represents a subset of information and it also includes the tools provided to handle such information. This logical division was made on the basis of the nature of the information itself: from the initial classification that separates internal and external information were identified other areas that treat of particular elements or enclose groups of similar elements. When using the program, the user can easily select the set of information and tools of which he wants to access, thus having access to all features related. The nomenclature used in the classification is also used in the graphic user interface to identify different areas (referring to the names in brackets, see 6th Chapter: Software Implementation). The management areas are:

• Client management (Clientes). Includes all information needed to identify and contact the customers, such as name, social security number, address, email and several phone numbers to contact the customer at any time. Are also considered part of the management area the tools for managing data, such as data display interfaces, a form to modify details of client data and a search engine to find clients by user-selectable criteria. • Order management (Ordenes). Includes all the information regarding orders, such as the service to install, the client who requests the service, order status, the technician who has been assigned, the dates of request and activation, plus a series of data on the urban network, useful to the technicians during the installation. It includes also data display interfaces, a form to modify details of orders and two search engines: one provides a simple research by Id while the other assembles a group of orders with common elements, filtered by user-selectable criteria.

10 • Maintenance requests management (Averias). Includes the information regarding maintenance requests, which is essentially the same of orders plus some more elements to identify the damage, such as the date on which the damage occurs, type of maintenance and information about the repair in case of future problems. It includes also data display interfaces, a form to modify details of requests and two search engines: one provides a simple research by Id while the other assembles a group of maintenance requests with common elements, filtered by user-selectable criteria. • Warehouse management (Almacen). Includes all information about the material used by the technicians, such as type, code, price, seller, location in the warehouse and amount. It has not been implemented yet. • Technicians management (Empleados). Includes all information about the technicians, involving their personal data but also the services they installed and used cars. This allows to monitor their work in detail and calculate the appropriate salary. It has not been implemented yet. • Account management (Facturas). Includes all information about administrative accounting, involving information about order materials and banks. It has not been implemented yet.

In addition to management areas directly related with information was necessary to create some more. By their nature the followings do not belong to any of the categories above but they are useful to administer the software and to fully satisfy the needs of the company.

• Security management (Usuarios). Includes all information regarding users, essential to ensure a safe access to information. In addiction to collect user-names and password provides a log-in interface and a form to create new users and assign them privileges. • Statistics management (Estadisticas). Does not own information but uses data from other areas to create additional useful information for decision-making. Often the additional information is created by the union of two types of information (for example, the number of orders accomplished by a technician) which are then split by time intervals and plotted through charts and diagrams. This has not been implemented yet.

Database The Database is managed by SQL Server 2008 database engine and resides in a private server on the company's intranet. It is needed to collect business information for the management of the company. The Database was developed at the same time of the Data Loading Application, since they were strictly related. It was designed according to the database currently in use with little revision, to allow simultaneous use of both databases. Although its implementation was strongly influenced by the preceding requirements, the similitude allows to exploit the advantages brought by the automated downloading process by the software currently in

11 use. The main tables (regarding clients, orders and maintenance requests) are almost identical, allowing the copy of data from one database to the other by simple procedures. The database schema has been modified only marginally by the student, precisely just with the addition of tables designed to store data for internal management of software, like the table used by the security protocol (see Appendix II: Database Schema).

Automa The Automa is an autonomous windows application built with WinAutomation™ to run on Windows operating systems (more information about tools, see 7th Chapter: Technology Used in Development Process - WinAutomation). It is the core of the automated downloading process since it accomplishes all steps carried out by the employees assigned to data downloading. It fulfils actions such as launch the browser, type the address, log in the portal and so on, even calling the Data Loading Application as a sub-routine. The compiled job runs on the same machine that hosts the Database (a server) and it is constantly re-executed, overwriting local XML files with new downloaded version and re- calling the Data Loading Application. By this way each new service commissioned or exchange of data is readily assimilated by the system.

Data Loading Application The Data Loading Application is a console application built to run on Windows operating systems and based on .NET Framework. It was developed with Visual Studio 2008 using C# and its task is to transfer data from the XML files to the database. Once XML files reside on a local directory the DLA is called as a sub-routine of the Automa to update the Database. Since the Management Software do not have any form to insert external data, rather will be denied any manual insertion of external data, this application is the forced way to insert data about commissions into the system. Thanks to .NET library that provides methods to manage XML files, also using XPath, the elements of the XML document may be addressed and manipulated as objects within the syntax of the programming language in use. This way allows to reach data contained in the XML nodes, which is where resides the information of interest, and use it with Data Manipulation Language (DML) commands. Typically the algorithm checks if data already exists in the database and, eventually, adds to or updates it.

12 3. Software Requirements

Hereafter will be exposed the Software Requirement Specification (SRS), which is essentially a catalogue of requirements to be complied by the software. Since the requirements analysis was incorporated into the design phase there was no official document. The SRS has been indicted after the period of training, listing the implemented requirements and those that created the foundation for future implementation. The specification has been divided into some sub-requirement areas which broadly follows the classification of the management areas. Although most of the requirements are related to the management software, have been included for completeness some general requirements about data that are satisfied by other components of the system. In addiction, it has been established the priority of the requirements. There are three types of priority, with their relatives identifiers:

• [H] - High Priority: mandatory (essential for the software). • [M] - Medium priority: recommended (useful for the software). • [L] - Low priority: optional (not required for the software).

Security Management This sub-requirement area covers the users registration process and system information access (login).

• RS1. The access to information must be protected by a security protocol (H). • RS2. The software must accept more users (H). • RS3. Each user must have its own user-name and password (H). • RS4. Each user can access a set of features on its level of authority (H). • RS5. There must be at least a user in the system which can create other users and assign them a level of authority (M). • RS6. The level of authority of each user must be customizable (M).

13 Data Management This sub-requirement area covers the general requirements about data.

• RD1. The system must accede to data coming from the private ONO's web portal (H). • RD2. The management of data coming from the web portal must to be automated (H). • RD3. Data must be recognized, checked and stored to make it usable (H). This requirement implicates that data must not be redundant. • RD4. Data about clients, orders and maintenance requests can not be inserted or deleted by users (H). This requirement implicates that data about services only comes from the web portal of ONO. • RD5. All stored data can be modified by users (H). • RD6. All stored data can be used for statistics (M).

Client Management This sub-requirement area deals with everything related to clients and the management of their personal information.

• RC1. The system must enable the vision of all clients (list-like) (H). • RC2. The system must enable the vision of client data in detail (form-like) (H). • RC3. The detail window must enable to modify data (H). • RC4. The system must provide a client research function by various criteria (M). • RC5. The system should provide short-cuts to navigate windows (L).

Order Management This sub-requirement area deals with everything related to orders and all information involved.

• RO1. The system must enable the vision of all orders (order history, list-like) (H). • RO2. The system must enable the vision of orders data in detail (form-like) (H). • RO3. The system must enable the planning of activities (agenda) (H). • RO4. Data about agenda can be inserted or deleted by users (H). • RO5. The information of the agenda must be easily accessible and editable (H).

14 • RO6. The system must distinguish the status of orders (H): • Pending (Pendiente) • Started (Asignada) • Completed (Cumplimentada) • Cancelled (Devuelta) • Complete (Complete) • RO7. The system must enable the detection of orders according to their status, the date of activation and the customer who requested them (H). • RO8. The system must provide an order research function by various criteria (M). • RO9. The system should provide short-cuts to navigate windows (L).

Maintenance Request Management This sub-requirement area deals with everything related to maintenance requests and all information involved.

• RM1. The system must enable the vision of all maintenance requests (historical, list-like) (H). • RM2. The system must enable the vision of maintenance requests data in detail (form-like) (H). • RM3. The system must distinguish the type of the request (H): • Residencial: private customers (residential). • Pyme 24h: SME with low priority (24 hours to the intervention). • Pyme 6h: SME with high priority (6 hours to the intervention). • RM4. The system must distinguish the status of the request (H): • Pendientes: those which have to be done yet (highlight the expired requests). • Gestionadas: those already done • Repetidas: some other problem appears in a week from repair. • SLA: expired (after 24h or 6h). • Reabiertas: same problem appears in 48 hours from repair. • Early Life. • RM5. The system must allow the selective vision of maintenance requests by type and status (H). • RM6. The system must provide a maintenance request research function by various criteria (M). • RM7. The system should provide short-cuts to navigate windows (L).

15 Warehouse Management This sub-requirement area deals with everything related to material stock.

• RW1. The software must manage the warehouse of material of various kinds such as company cars, technical equipment (tools for electricians), instrumentation for use of services (modems, set-top box) (H). • RW2. The system must enable the vision of all data about materials (H).

Technician Management This sub-requirement area deals with everything related to technicians and their activities.

• RT1. The software must collect data on the activities of the technicians in order to assess their performance, since that will affect the calculation of remuneration (H). • RT2. The system must enable the vision of all data about the activities of the technicians (H).

Account Management This sub-requirement area deals with everything related to financial and administrative management.

• RA1. The software must manage and store invoice (H). • RA2. The software must provide tools to help the financial and administrative management of the company (H).

16 4. Software Development

In this chapter we enter the stage of actual development. Having identified the areas of management and their specific requirements it is time to begin the implementation. This phase consists mainly of creating software modules with a user-friendly graphical interface and the appropriate business code able to carry out the functions for which the module was created. Each management area is composed of a variable number of modules based on the requirements that must comply. Since the software implemented during the period of training is entirely focused on Visual Studio, this chapter focuses on the description of logical and physical structure of a project developed with the mentioned IDE.

Project Structure Visual Studio provides two containers that help to manage efficiently the items that are required by the development effort, such as references, data connections, folders, and all modules that compose the project. These containers are called solutions and projects.

Solutions. A solution includes one or more projects, plus files and metadata that help to define the solution as a whole. It is possible to use solutions to control build dependency issues and control the precise order in which contained projects are built. These information are contained in solution files with a .sln file extension.

17 Visual Studio automatically generates a solution when a new project is created. As needed, it is possible to add other projects to the solution if they are related. To develop the management software it was decided to create a single project solution, or stand- alone project, so it can be more subjective.

Projects. A project typically contains class files, resources and a set of related metadata such as component references and build instructions. Projects are used as containers for all of the build and configuration settings required to generate a .NET . These information are contained in project files with either a .csproj or .vbproj file extension, depending upon the project's language. There are many different project types although these can be divided broadly into two categories. The two categories of project types are: • Web projects. A Web project is one that is created with a Hypertext Transfer Protocol (HTTP) location. Web projects include ASP.NET Web Applications used to deliver content to Web browsers and ASP.NET Web Services used primarily for data integration over the Internet. • Non-Web or local projects. Non-Web or local projects are created with a file system location. The most common local project types are Windows applications and class libraries. The project developed during the period of training is essentially a local project, in particular a windows application. The choice of this type of solution was forced by the needs of the company. Since the company prefers not to make their servers accessible to third parties has been ruled out a web project as a reasonable solution. For this reason, to run the Management Software in a computer other than the intranet, it will be necessary to create a VPN (virtual private network). This choice may seem odd, but makes sense considering that the software will be used mostly inside of the intranet.

What is a Windows Application? A windows application is a software application that runs on a computer that is also running Microsoft Windows as an operating system. As usual a windows application will be run within a window, it may have more though. Just to make it clear, a window in the context of software is "the rectangular-shaped viewing area on screen that the user is working in and may or may not have options for controlling the position and size of the program area" (Computer Desktop Encyclopedia). What it typically has are controls to let the user interact with the application. These application follow the event-driven programming paradigm, which means that the flow of the program is determined by events, like sensor outputs or user actions (mouse clicks, key presses, etc..).

Modules. A module is typically a class file. In this project each module reflects the structure of the software by implementing both the Presentation Layer and the Logic Layer. Based on the requirements to be met, a module is designed to display data or collect data necessary for a particular transaction. The graphic interface is designed with the help of the visual editor designer provided by the IDE, which automatically generates the code to initialize graphic components, while the business code is written by the programmer.

18 When working with automatically generated source, Visual Studio uses partial classes to split the definition of a class over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. The code to initialize the graphic user interface is on a file with .designer.cs extension, while the business code is on a file with .cs extension. In this way the Presentation Layer and the Logic Layer are physically separated, so the programmer can easily write and manipulate his portion of code while the IDE takes care of initializing graphical components.

19 5. Relevant Classes

During the software implementation the choice of components and classes to use was dictated by several factors. Some choices were imposed by the requirements, while others were forced by the IDE and the structure of the Base Class Library. This means that the efficiency of the structure’s environment often results in a forced choice of high level components implemented on purpose, reducing the responsibility of the programmer. Some other cases the range of comparable components let the developer choose which component to use and the appropriate procedure to apply. Hereafter will be exposed the characteristics of the relevant components used by both the Presentation Layer and the Logic Layer. Some examples will clarify the use cases.

20 Data Retrieval

There are many ways to connect to a SQL Server database using .NET Framework. The Base Class Library includes a set of computer software components, called ADO.NET, that programmers can use to access data and data services. These components have been used in the project to access the data source. The following explanation will describe the most commonly used.

DataSet The DataSet is an in-memory cache of data retrieved from a data source, which includes tables where the data are contained. It is a major component of the ADO.NET architecture. Each table is stored DataTable object, referenced by the Tables property, while each record is represented by the DataRow, referenced by the Rows property of DataTable. It is also possible to enforce data integrity by using DataRelation objects, such as UniqueConstraint and ForeignKeyConstraint objects. The DataSet has some interesting features: • Works on the disconnected architecture. The connection doesn't need to be on for the DataSet to perform the manipulations and other actions and is required only at the time of updating records to the database table. • The connection does not need to be explicitly open. While using DataSet, the relative adapter automatically opens and closes the connection as and when required. In a typical multiple-tier implementation, to create and refresh a DataSet, are typically used two Dataset: • one as a buffer, to change the data in individual DataTable objects by adding, updating, or deleting DataRow objects; • the other will be directly bound to data source. In this way, once the changes are passed to the second Dataset, it is possible to simulate the Commit and Rollback commands invoking the methods AcceptChanges or RejectChanges. Although this procedure is accurate and effective, it was not considered important to simulate the behaviour of the Database Management System (DBMS) and therefore the temporary buffering of data. So it was chosen a more expeditious procedure, that was to apply in real-time changes on the database. Since a DataSet is not connected to any real data source, to implement the procedure it was imperative to use a System.Data.Common.DataAdapter or a TableAdapter (it resides in the hierarchy of the DataSet, e.g.

21 Mencia.masterDataSetTableAdapters.ClientesTableAdapter). • TableAdapters are suitable for working with datasets that have been created with the use of design-time tools. • DataAdapters work with both kind of database, but they are especially needed in datasets created without design-time tools. Hereafter will be shown an example of procedure using both objects.

DataAdapter The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. First, it is needed to set up a SqlConnection object with the connection string to tell the program where the database is, and a Dataset instance.

// Connect to the database SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";

// Set up the DataSet to hold all the data DataSet dsMain = new DataSet();

A Dataset is where all the data is held when it is pulled from the database table. It can be thought of like a grid on a spreadsheet. The columns in the grid are the columns from the database table. The rows represent a single entry in the table. The Dataset needs to be filled with data. However, because the Dataset and the SqlConnection can't see each other, it is needed a DataAdapter in the middle to help them out.

SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = new SqlCommand("Select * from Averias", conn); sqlDA.Fill(dsMain, "Averias");

The DataAdapter object will use the SqlCommand object to pull the records from the database, but it needs to know which connection object to use, that is why a "conn" variable is also passed to the constructor. Once connection to the database has been passed to DataAdapter, it will care to manage the connection, avoiding the programmer to open and close it. Once the query has been executed all records are pulled from the database to fill the DataSet with data. Later, the data can be access just with simple methods, even if there is no connection.

foreach (DataRow row in dsMain.Tables["Averias"].Rows) { for (int i = 0; i < row.ItemArray.Length; i++)

22 { Console.WriteLine(row.ItemArray[i].ToString()); } }

TableAdapter Whenever a new data source is visually added to the project, the IDE generates a TableAdapter class for every table that has been selected from the database. These designer-generated components are aimed to improve upon the functionality of DataAdapters. In addition to the standard functionality of a DataAdapter, TableAdapters provide a built-in connection object and the ability to contain multiple queries. Each query added to a TableAdapter is exposed as a public method that is simply called like any other method or function on an object. TableAdapters are automatically initialized by dragging the class symbol over the designer, that means it is not necessary to define any SqlConnection object either any connection string. Once the TableAdapter has been added to the class it is ready to be use with all the method that provides, such as: • TableAdapter.Fill. Populates the TableAdapter's associated DataTable with the results of the TableAdapter's "SELECT * FROM table" command. • TableAdapter.Update. Sends changes back to the database. • TableAdapter.GetData. Returns a new DataTable filled with data. • TableAdapter.Insert. Creates a new row in the data table. • TableAdapter.ClearBeforeFill. Determines whether a DataTable is emptied before you call one of the Fill methods. • TableAdapter.QueryName. Execute the query previously added that matches the query name. So, use TableAdapters to exploit the features of DataSets could be really straightforward. Hereafter is shown the code to fill a data viewer with data from a table.

this.clientesTableAdapter.Fill(this.masterDataSet.Clientes);

With an only line of code it is possible to access a database tables, pull out data and visualize it on an output control. Actually that semplicity is due to Visual Studio. When a data viewer (output control) is visually created, the IDE shoulders all the work of initializing the components and binding the viewer to a data source (binding process will be treat further on). All the code needed to do that resides in the portion of class hidden to the programmer, who actually does not need to manipulate it. As seen DataSets, combined with both DataAdapter or TableAdapter, provide a powerfull tool to manipulate database data. Further it has many features that are not been exposed here, for example DataSets provide a well-supported mechanism to serialize results, or pass the query results to another component. It is possible to serialize a DataSet to XML by calling the WriteXML method, or pass a DataSet in a SOAP method.

23 Even if the current requirements still do not always justify the use of Datasets in the project, their potential and versatility have been taken into account and considered important for the future development of the software. Moreover, especially combined with TableAdapters, DataSets drastically reduce the work of the programmer.

DataReader While Datasets are valued for their many in-built features, DataReaders (as low-level components) are appreciated for their simplicity to be adapted to any context. For the majority of queries employed in the project, where data is found, displayed, and then forgotten, the DataReader will increase the performance drastically, with only a little extra work. Considering the trivial example exposed to explain DataAdapters, the inspection of data (the foreach loop) do not actually start until the whole DataSet has been filled. There may be occasions where not all the results are needed, or other code might be executed while inspecting (like a progress bar). Using a DataSet, this can only take place after the complete results are fetched and passed into the various collections within the DataSet. Using DataReaders things change substantialy.

SqlConnection conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("select * from mytable", conn); command.Connection.Open(); SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { Console.WriteLine(reader.GetString(0)); } reader.Close();

In the portion of code above the inspection is made as soon as data is available by employing the while loop, where reader.Read() returns false if no more results are found. Therefore it is possible to inspect as soon as it goes on, since the DataReader only stores one result at a time. This results in a significant reduction in memory usage and system resources when compared to the use of DataSets, where the whole query result is stored. DataReaders are also useful when data in a row needs to be manipulated or shown separately. Hereafter an example.

SqlConnection sqlConn = new SqlConnection(strConnection); sqlConn.Open(); SqlCommand BuscarOrden = new SqlCommand("Select * from Clientes where idCliente ='" + idCliente + "'", sqlConn); SqlDataReader reader = BuscarOrden.ExecuteReader(CommandBehavior.CloseConnection); reader.Read();

24 if (reader.HasRows == true) { textBoxIDcliente.Text = reader["idCliente"].ToString(); textBoxNombre.Text = reader["Nombre"].ToString(); textBoxNIF.Text = reader["nif"].ToString(); textBoxDomicilio.Text = reader["Domicilio"].ToString(); textBoxPoblacion.Text = reader["Poblacion"].ToString(); textBoxProvincia.Text = reader["Provincia"].ToString(); textBoxCP.Text = reader["codigoPostal"].ToString(); textBoxTelResidencia.Text = reader["telefonoCasa"].ToString(); textBoxTelTrabajo.Text = reader["telefonoTrabajo"].ToString(); textBoxTelAdicional.Text = reader["telefonoAdicional"].ToString(); textBoxTelalternativo.Text = reader["telefonoAlternativo"].ToString(); comboBoxPYME.Text = reader["pyme"].ToString(); textBoxEmail.Text = reader["eMail"].ToString(); }

Here the reader is used as an associative array, with which it is possible to extract a column value at a time by entering the name of the column.

SqlCommand It is used to represent a Transact-SQL statement or to execute against a SQL Server database, like in the previous examples. SqlCommands feature the following methods for executing commands at a SQL Server database: • ExecuteReader. Executes commands that return rows contained in a SqlDataReader object. • ExecuteNonQuery. Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements. • ExecuteScalar. Retrieves a single value (for example, an aggregate value) from a database. • ExecuteXmlReader. Sends the CommandText to the Connection and builds an XmlReader object. Along the project there is a massive use of ExecuteNonQuery method, whenever an insert or update statement is executed, while the ExecuteReader method is always used whenever a DataReader object is employed.

25 GUI Creation

Regarding the development of the graphic user interface, procedural choices are quite limited since the implementation of certain features is constrained by the imposition of predetermined components. This imposition is actually performed by the IDE, which, however, reflects the directives imposed by the framework itself. In other words, classes like Form, DataGridView and BindingSource have been conceived and designed specifically to implement certain functions, and the only possible choice is to use them in combination.

Windows Forms Visual Studio use System.Windows.Forms.Form objects to build relatively straightforward C# windows applications. Window forms provide projects with components, such as dialog boxes, menus, buttons, and many other controls, that make up a standard windows application user interface (UI). Fundamentally, these controls are just classes from the .NET . Hereafter an empty form automatically created by the IDE.

The visual editor designer of Visual Studio enables to drag the controls onto the application's main form and adjust their size and position. Doing this, the IDE automatically adds the source code to create an instance of the appropriate class and initialize it.

26 DataGridView With System.Windows.Forms.DataGridView objects provide a customizable table for displaying data, with or without an underlying data source. Without specifying a data source, columns and rows that contain data will be created and added using the Rows and Columns properties. Alternatively, like it has been used in the project, it is possible to set the DataSource and DataMember properties to bind the DataGridView control to a data source and automatically populate it with data. In most circumstances, DataGridView control binds to a System.Windows.Forms.BindingSource component which manages the interaction with the data source. When a DataGridView is visually created by dragging it on the form, a wizard automatically appear to easily set up the binding source. By this way it is possible to select one of the data sources already in the project.

BindingSource The BindingSource component is considered by the other components as a data source. It can bind to a wide variety of data sources and can resolve many data binding issues automatically, hiding the complexity of the data source itself. Generally it binds to a Dataset. Hereafter will be shown part of the designer-generated code that treats of the binding process, involving all components explained before. This portion of code resides in the part of the class automatically managed by the IDE.

private System.Windows.Forms.DataGridView clientesDataGridView = new System.Windows.Forms.DataGridView();

private System.Windows.Forms.BindingSource clientesBindingSource = new System.Windows.Forms.BindingSource(this.components);

private masterDataSet masterDataSet = new Mencia.masterDataSet();

this.clientesBindingSource.DataSource = this.masterDataSet; this.clientesBindingSource.DataMember = "Clientes"; this.clientesDataGridView.DataSource = this.clientesBindingSource;

After declaring and initializing the objects, the DataSource and DataMember properties are setted to attach the BindingSource to the data source, which is the DataSet object representing the database. Further, the DataSource property of the DataGridView is setted to the BindingSource object.

27 6. Software Implementation

This session will explain in detail how the software was implemented and the procedural decisions taken. The explanation will follow the classification of the management areas adopted in the description of the Management Software and every satisfied requirement is identified by the code adopted in the Software Requirement Specification. Due to the limited duration of the training period, only the management areas regarding security, clients, orders and maintenance requests have been implemented.

Security Management - Access To implement the security protocol (RS1) it was chosen to create a table in the database containing all the necessary information for the authentication of the various users of the system (RS2). This table is called "AccesoMencia" and contains the following columns: • idUsuario (primary key) • Usuario (user) • Contraseña (password) • Permiso (authority) When a user connect to the system the following login window is displayed.

This window is the interface to collect necessary data to accede the software, which are user-name and password (RS3). Once data is inserted the "Aceptar" button will run the query on the database table that contains authentication data. According to user authority

28 will be initialized the main panel of the software, or an error message will appear. Hereafter the code executed when the "Aceptar" button is pressed:

private void buttonAceptar_Click(object sender, EventArgs e) { string strConnection = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; SqlConnection sqlConn = new SqlConnection(strConnection); sqlConn.Open();

SqlCommand BuscarUser = new SqlCommand("Select * from AccesoMencia where Usuario ='" + textBoxUser.Text + "' and Password = '" + textBoxPassword.Text + "'", sqlConn); SqlDataReader reader = BuscarUser.ExecuteReader(); reader.Read();

if (reader.HasRows == true) { int idUsuario = Convert.ToInt32(reader[0]); string Usuario = reader[1].ToString(); int permiso = Convert.ToInt32(reader[3]); reader.Close(); this.Close(); MenuPrincipalForm form = new MenuPrincipalForm(permiso, Usuario, idUsuario); form.MdiParent = Inicio.ActiveForm; form.Show(); } else { DialogResult result; string message = "Usuario o Contraseña Incorrecta"; string caption = "Error al Conectar"; MessageBoxButtons buttons = MessageBoxButtons.RetryCancel; MessageBoxIcon icon = MessageBoxIcon.Exclamation;

result = MessageBox.Show(message, caption, buttons, icon);

if (result == DialogResult.Retry) { reader.Close(); this.Show(); } else { this.Close(); reader.Close(); } } sqlConn.Close(); }

If authentication data correspond to those in the database will be created an instance of the main menu. The management areas reachable from the main menu will be enabled in

29 order to user's authority level. The different levels of authority make reachable or not the different management areas in the main menu, in other words the user will see on the menu on the left side only the buttons that access the areas of its competence (RS4). To differentiate between different levels of authority are used binary flags. Say we have a ten-digit binary number, each digit enables a management area. The binary number is then saved in base ten into the int field of "AccesoMencia" table, called "NivelPermisos". Hereafter the different authority levels:

• bit 0: Murcia = 1 • bit 1: Ciudad Real = 2 • bit 2: Ordenes = 4 • bit 3: Averias = 8 • bit 4: Clientes = 16 • bit 5: Estadisticas = 32 • bit 6: Almacen = 64 • bit 7: Empleados = 128 • bit 8: Facturas = 256 • bit 9: Crear User = 512 • bit 10: Parametros = 1024

For example an authority level of 5 let the user accede to the orders of Murcia; a level of 1023 generate an admin user, which can access all the areas but "Parametros" (this area will be accessible only by the programmer). After running the authentication process with the highest authority level, the main menu will allow to access the various management areas, such as:

• Ordenes (orders). • Averias (maintenance requests). • Clientes (clients). • Estadisticas (statistics). • Almacen (warehouse). • Empleados (technicians). • Facturas (account). • Crear User (users). • Parametros (parameters).

30 With the highest authority level the appearance of the main menu will be the following:

The different management areas are reachable through a series of buttons on the left side of the window. Each management area has been implemented on an System.Windows.Forms.Panel object, which is a container for other controls. It provides some interesting properties, such as: • Enabled property, which enable or disable the panel itself and all the controls contained within the Panel. • AutoScroll property, which allows to scroll panel area so any controls located within the Panel (but outside of its visible region) can be scrolled to with the scroll bars provided. These containers are enabled by pressing the buttons on the left side menu of the window. By this way the corresponding panel will appear on the central working area of the window where all its controls are shown. Thusly there are some management areas that do not use any panel. Client management accesses directly to a data viewer (or data container), implemented on a DataGridView object. This object is used whenever it is needed to display an entire table or a pre-added query, like exposed in the previous chapter (see 5th Chapter: Relevant Classes).

31 Security Management - Users User management area is aimed to create new users (RS5) and assign them a level of authority (RS6). Hereafter the appearance of the working area.

As seen there controls to insert user-name, password and the features that must be enabled. The process is quite simple: checked if there are any other users in the database with the same user-name, data about the new user will be inserted, in the other case a message of error is displayed. The process starts when "Crear" button is pressed.

private void buttonCrear_Click(object sender, EventArgs e) { string Usuario = textBoxUsuario.Text; string Password = textBoxPassword.Text; int Permisos = this.getPermisos();

string strConnection = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; SqlConnection sqlConn = new SqlConnection(strConnection); sqlConn.Open(); SqlCommand BuscarUser = new SqlCommand("Select * from AccesoMencia where Usuario ='" + Usuario + "'", sqlConn); SqlDataReader reader = BuscarUser.ExecuteReader(); reader.Read();

if (reader.HasRows == false)

32 { SqlCommand insertarNuevoUsuario = new SqlCommand("INSERT INTO [dbo].[AccesoMencia] ([Usuario], [Password], [NivelPermisos]) VALUES ('" + Usuario + "', '" + Password + "', '" + Permisos + "')", sqlConn); insertarNuevoUsuario.ExecuteNonQuery();

MessageBox.Show("Nuevo usuario creado"); reader.Close(); sqlConn.Close(); this.Close(); } else { MessageBox.Show("Usuario no valido"); reader.Close(); sqlConn.Close(); } }

The first query is executed with a data reader since the result is just needed to solve an if-else statement, and then discarded. As exposed in the previous chapter, in this case a SqlDataReader object is the preferred solution. Later, if there are no users with the same user-name, an insert sql statement is executed with SqlCommand.ExecuteNonQuery method.

33 Client Management The client management area has not many requirements, they monstly deal with displaying data. So, as said before, the button that opens the client management area accedes directly to a data viewer implemented on a DataGridView object, which will show a list of all clients (RC1). The DataGridView bind to the data source thought the BindingSource object like explained in the previous chapter. This way, and using the TableAdapter, load data from the table "Clientes" is rather simple. Hereafter is shown the code invoked when the client management area, or ClientesForm, is loaded.

private void ClientesForm_Load(object sender, EventArgs e) { this.clientesTableAdapter.Fill(this.masterDataSet.Clientes); }

Thanks to the Fill method it is possible to populate the data viewer with only a row of code. The following screenshot shows the appearance of the client management area.

The data viewer is basically empty cause I have no rights on showing information about company's clients. Throughout the document every other data viewer, which is aimed to show information about clients or other private information of the company, will be shown as empty.

Data sources that are bound to a BindingSource component can be navigated and managed with the BindingNavigator class, which provides a VCR-like user interface that appears on the top of tha window, right below the title. This navigator is automatically added by the IDE and represents a standardized way to navigate and manipulate data on a form. By default, the BindingNavigator control's user interface is composed of a series of ToolStripbuttons, text boxes, and static text elements for most common data-related actions, such as adding data, deleting data, and navigating through data. Each of these controls can be retrieved or set through an associated member of the BindingNavigator control. Although BindingNavigator offers coded solution for the most common data-related actions, it was necessary to implement other methods to extend the capabilities of data

34 management to fulfil the requirements. The requirements, in fact, say that every record shown in the ClientesForm window must be able to be expanded into another window that shows all client's data in detail (RC2). From the detail window it must be possible to modify the data of the client (RC3). This window was implemented with another form that appears by dobleclicking the record's row or when a research function returns a single element. Hereafter the code that handle the dobleclick event.

private void clientesDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { string idCliente = this.dataGridViewTextBoxColumn1.DataGridView[0, e.RowIndex].Value.ToString(); DatosClienteForm f1 = new DatosClienteForm(idCliente, null); f1.Owner = this; f1.Show(); } }

The event handler, which is the ClientesForm itself, implements the method above to handle the event sent from the sender, which is the DataGridView. That method is rather simply and consists in creating an instance of a DatoClientForm object and show it. As said DatoClientForm is opened even when a research returns a single element. ClientesForm provides two research features, they can be executed by pressing Ctrl+B or Ctrl+Alt+B (RC5). These two combination open two different research windows: BusquedaCliente and BusquedaClienteAvanzada, which provide different research functions (RC4). The key event is catched by ClientesForm implementing the following method.

private void ClientesForm_KeyUp(object sender, KeyEventArgs e) { if (e.Control == true && e.KeyValue == 66) // Ctrl + B { if (e.Alt == true) { BusquedaClienteAvanzado form = new BusquedaClienteAvanzada(); form.Show(); } else { BusquedaCliente form = new BusquedaCliente(); form.Show(); } } if (e.KeyValue == 27) this.Close(); }

35 The portion of code is quite simple: if the pressed keys correspond to one of the combinations, the relative form will be opened, or if the "Esc" button is pressed the ClientesForm closes itself (RC5). The short-cut navigation was a low priority requirement but it was developed to make the client management area complete. The BusquedaCliente form contains only a few controls, just to provide a simple research by Id.

The only thing this class has to do is to implement the click event for the "Buscar" button. Hereafter the code.

private void buttonBuscar_Click(object sender, EventArgs e) { string idCliente = this.textBox1.Text; string strConnection = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; SqlConnection sqlConn = new SqlConnection(strConnection); sqlConn.Open(); SqlCommand BuscarOrden = new SqlCommand("Select * from Clientes where idCliente ='" + idCliente + "'", sqlConn); SqlDataReader reader = BuscarOrden.ExecuteReader(); reader.Read(); if (reader.HasRows == true) { DatosClienteForm f1 = new DatosClienteForm(idCliente, null); f1.MdiParent = Inicio.ActiveForm; f1.Show(); this.Close(); reader.Close(); } else { string message = "No se encontró el cliente"; string caption = "Cliente Inexistente"; MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); } reader.Close(); }

36 Once the text box containing the client's Id has been read, a simple query is executed. Although the procedure to run the query may seem complicated, it is very simple and lower level compared to the use of TableAdapters. By this reason this procedure to access data is often use thruoghout the project, especially when the query is unusual or it has special values. In these cases the use of TableAdapter can be considered superfluous. However, using a TableAdapter it would be necessary to add a specific parametric query, with the risk that it will be little used. The procedure has some simple steps. First, a new connection with the database is created, using a System.Data.SqlClient.SqlConnection object that takes the connection string as a parameter (the connection string identifies the database instance). Once the connection has been created and opened it is possible to execute queries. A query is identified by an instance of the class System.Data.SqlClient.SqlCommand, which is created with two essential parameters: a string that expresses the sql query and the SqlConnection object. Its execution returns a SqlDataReader object, that can be used to navigate the results. If exists a client with that particular Id the DataReader will contain exactly one row, since there can be no more than one client with the same Id. So, BusquedaCliente opens the DatosClienteForm relative to client returned by the query.

The BusquedaClienteAvanzada is a little more complicated. This form provide an instantaneous research while typing in the appropriate text box. Hereafter the window.

This time the research is made by using the clientTableAdapter, which has a proper query for each criteria selectable in the combo box. Since all columns of the table are displayed the use of table adapters was preferred. Using a text changed event it is possible to update in real time the research results.

private void toolStripTextBoxBusqueda_TextChanged(object sender, EventArgs e) { string opcion = this.toolStripComboBox1.Text; string dato = "%" + this.toolStripTextBoxBusqueda.Text + "%"; switch (opcion) {

case "Nombre": this.clientesTableAdapter.FillByNombreCliente(this.masterD ataSet.Clientes, dato); break; case "Domicilio": this.clientesTableAdapter.FillByDomicilio(this.masterDataS et.Clientes, dato); break;

37 case "idCliente": this.clientesTableAdapter.FillByIdCliente(this.masterDataS et.Clientes, dato); break; case "nif": this.clientesTableAdapter.FillByNIF(this.masterDataSet.Cli entes, dato); break; case "Poblacion": this.clientesTableAdapter.FillByPoblacion(this.masterDataS et.Clientes, dato); break; case "codigoPostal": this.clientesTableAdapter.FillByCP(this.masterDataSet.Clie ntes, dato); break; case "Telefono": this.clientesTableAdapter.FillByTelefono(this.masterDataSe t.Clientes, dato); break; default: break; } }

The code is quite simple though. Every time the text in the text box on the top of the window changes a different research is executed, based on the criteria selected in the combo box. Like said before a table adapter is always bound to a data viewer, in this case a DataGridView. Once the results are shown in the data viewer it is possible to open the detail window (DatosClienteForm) by dobleclicking a record, like in ClienteForm. The DatosClienteForm will show the personal data, the orders and the maintenance requests of the client, each one in a different tab page. To contain tab pages is used a System.Windows.Forms.TabControl object. The first tab, which contains the personal data of the client, is called "General", from where it is possible to modify the data (RC3). It consists essentially in a groups of controls and dialogs, as shown hereafter.

38 The others two tabs contain a data viewer each one, to display respectively the orders and the maintenance requests of the client. The data viewers are implemented on a DataGridView using the same procedure explained before for the client data viewer. The only difference is that the table adapters for "Ordenes" and "Clientes" tables contain additional queries called both FillByCliente, which are also the names of the public methods that execute those queries. These methods accept an input parameter that represents the client's Id, which will be used in the queries to extract data only about the orders and the maintenance requests relative to the client concerned. Hereafter is shown the method called when the form is opened by dobleclicking the client's row in the DataGridView of the ClientesForm.

private void DatosClienteForm_Load(object sender, EventArgs e) { this.averiasTableAdapter.FillByCliente(this.masterDataSet.Averias, idCliente);

this.ordenesTableAdapter.FillByCliente(this.masterDataSet.Ordenes, idCliente);

39 string strConnection = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; SqlConnection sqlConn = new SqlConnection(strConnection); sqlConn.Open(); SqlCommand BuscarOrden = new SqlCommand("Select * from Clientes where idCliente ='" + idCliente + "'", sqlConn); SqlDataReader reader = BuscarOrden.ExecuteReader(CommandBehavior.CloseConnection); reader.Read();

if (reader.HasRows == true) { textBoxIDcliente.Text = reader["idCliente"].ToString(); textBoxNombre.Text = reader["Nombre"].ToString(); textBoxNIF.Text = reader["nif"].ToString(); textBoxDomicilio.Text = reader["Domicilio"].ToString(); textBoxPoblacion.Text = reader["Poblacion"].ToString(); textBoxProvincia.Text = reader["Provincia"].ToString(); textBoxCP.Text = reader["codigoPostal"].ToString(); textBoxTelResidencia.Text = reader["telefonoCasa"].ToString(); textBoxTelTrabajo.Text = reader["telefonoTrabajo"].ToString(); textBoxTelAdicional.Text = reader["telefonoAdicional"].ToString(); textBoxTelalternativo.Text = reader["telefonoAlternativo"].ToString(); comboBoxPYME.Text = reader["pyme"].ToString(); textBoxEmail.Text = reader["eMail"].ToString(); } reader.Close(); }

The method attends to filling the data viewers of orders and maintenance requests through their TableAdapters and load client data in the appropriate output controls.

40 Order Management The main page of the order management provides controls to access data through various criteria. Hereafter the appearance of the window.

Although the graphic interface is already designed, not all features are implemented. The controls on the working area should execute targeted researches against the database, but only a few are enabled. So far has been implemented only the most generic functions, such as the order history or list-like vision (Bolsa Ordenes), the detail window or form-like vision, the agenda (Planning) and the research functions (Busqueda Ordenes Cliente/Estado). Nevertheless other functions can be simulated through the research features, since they would be no more than parametric queries returning a list of orders. In anticipation of future implementations of other functions, the list-like vision form was equipped with a parameterized constructor. According to the parameters passed to the constructor, OrdenesForm will display orders filtered by different criteria, so a single class can be reused along the program. Basically the constructor accepts five strings: three strings identify a date interval and the geographic region, while the other two identify a column name (item) and its value (field). In this way OrdenesForm can be initialized to satisfy any filter criteria. Hereafter the method where the parameters are used. Actually this methos handles a load event, which is launched whenever a new instance of OrdenesForm is created.

private void OrdenesForm_Load(object sender, EventArgs e)

41 { if (Field == null && Item == null) this.ordenesTableAdapter.Fill(this.masterDataSet.Ordenes, Compania);

else { SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=SAMSPC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"; SqlDataAdapter sqlDA = new SqlDataAdapter();

if (F1 != null && F2 != null) sqlDA.SelectCommand = new SqlCommand("SELECT * FROM Ordenes WHERE " + Field + " ='" + Item + "' and Compania = '" + Compania + "' and FechaCita BETWEEN '" + F1 + "' and '" + F2 + "'", conn); else sqlDA.SelectCommand = new SqlCommand("SELECT * FROM Ordenes WHERE " + Field + " ='" + Item + "' and Compania = '" + Compania + "'", conn);

sqlDA.Fill(this.masterDataSet.Ordenes); } }

If there is no item and field passed to the constructor, ordenesTableAdapter will load every order in the database (the parameter "Compania" is always passed to distinguish the geographic region concerned). In the other case a DataAdapter will execute the query related to the item and the field passed, with or without a date interval. The order history or list-like vision is displayed by pressing the "Bolsa Orden" button on the main panel (RO1), which opens a OrdenesForm form without parameters (just "Compania", which is always present). This means that it will execute a simple query with no parameters, which will return all orders in the database. The returned data are displayed in the following form.

The buttons on the navigation bar under the title provide research functions, also accessible through short-cuts (RO9). By entering a date range in the text boxes and

42 pressing the “Buscar Fecha” button it will run the following code.

private void toolStripBuscarFecha_Click(object sender, EventArgs e) { this.ordenesTableAdapter.FillByFechas(this.masterDataSet.Orden es, Convert.ToDateTime(toolStripTextBox1.Text), Convert.ToDateTime(toolStripTextBox2.Text), Compania); }

Thanks to a parameterized query provided by the TableAdapter this method will return a subset of orders completed within the entered date range. The other function provides a research by criteria. Clicking the "Busqueda Avanzada" button appears a form that permits to select one of the constituent elements of the order and a data range. The data collected by this form are used to perform a research against all orders in the database that returns those which match the selected criteria.

Also in this case is used the OrdenesForm's constructor with parameters. By this way the new object is loaded at creation time with data that matches the selected criteria. The agenda allows to plan the activities listing the orders and the maintenance requests to be executed during the day. It is visible by clicking on "Planning" button (RO3), which will generate the following window.

43 Agenda also uses a DataGridView combined with the PlanningTOATabelAdapter, but this time the AllowUserToAddRows and AllowUserToDeleteRows properties of the data viewer are setted to true. This because the information stored in the "PlanningTOA" table can be inserted or deleted by the user (RO4), which takes care of planning activities. To make accessible and modifiable order data visualized in OrdenesForm and PlanningForm, it is possible to expand each order in a detailed data window (RO2) with a double click. This event will force the creation of a DatosOrdenForm object, which provides all the detailed information about the concerned order. Similarly to client's detail window the dobleclick event extract the order id from the first column of the table and open a DatosOrdenForm.

private void ordenesDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { string idOrden = this.dataGridViewTextBoxColumn1.DataGridView[0, e.RowIndex].Value.ToString(); DatosOrdenForm f1 = new DatosOrdenForm(idOrden); f1.MdiParent = Inicio.ActiveForm; f1.Show(); } }

DatosOrdenesForm contains controls to display all order data. The form looks like following.

44 Regarding the research functions have been implemented two options, accessible from the buttons "Buscar Cliente" and "Buscar Orden" (RO8). The first option opens a BusquedaClienteAvanzada form already implemented, which provide a research by client's criteria. Thereafter, when the client form is opened, expanding the detail window of the client it is possible to access all client's orders data. The second options provides a search by order status and, eventually, the time interval in which the service was activated (RO7). The form is the following.

Pressing the "Aceptar" button will be create an instance of OrdenesForm object with data collected in the form.

private void buttonAceptar_Click(object sender, EventArgs e) { string Dato = comboBox1.Text; string Campo = "Estado"; if (checkBox1.Checked == true) { DateTime f1 = this.dateTimePicker1.Value; string Fecha1 = f1.ToString().Substring(0, 10); DateTime f2 = this.dateTimePicker2.Value; string Fecha2 = f2.ToString().Substring(0, 10);

this.Close(); OrdenesForm f = new OrdenesForm(Dato, Campo, Fecha1, Fecha2, Compania); f.MdiParent = Inicio.ActiveForm; f.Show(); } else { this.Close(); OrdenesForm f2 = new OrdenesForm(Dato, Campo, null, null, Compania); f2.MdiParent = Inicio.ActiveForm;

45 f2.Show();

} }

The arguments passed to the constructor are "Dato" and "Campo". "Dato" is forced to "estado" while the "Campo" will contain the status value for which to execute the research. As seen, passing the search parameters to the constructor it is possible to reuse the same form in different contexts, saving time and code.

46 Maintenance Request Management The implementation of this management area follows the procedures and components used in the previous areas, the implementation of the main features will be exposed though. The main page of the maintenance request management provides controls to access data of the most common subsets of requests, divided by type and status (RM5). Hereafter the appearance of the main page.

Like in the order management main page, the controls on the working area execute targeted researches against the database, but here it is also possible to choose a date range.

47 After selecting a date range will be created an instance of AveriasForm, which provides a list-like vision of the maintenence requests that meet the search parameters selected (RM1).

To perform all different researches even this form was equipped with a parameterized constructor, using the same procedure used with OrdenesForm. According to the parameters passed to the constructor, AveriasForm will display maintenance requests filtered by different criteria, allowing to reuse the class along the program. Every request displayed on the list-like form can be expanded to a detailed form by a doubleclick (RM2), like in the other management areas. The detailed form allows to modify request data.

The creation of the form above is maintained by the doubleclick event handler.

48 There are also two search functions that can be performed from the list-like form. These research are used to further filter the displayed data or identify a specific maintenance request in accordance with its id. Both research functions are recallable through short-cuts (RM7).

A research by Id is rather simple to implement. After entering the id, the request will be localized by a simple query, or an error message appears. If the query returns at least one row means that the id is valid, then DatosAveriaForm will be opened with the details of the request. The other research function visualizes on the list-like form a group of maintenance requests with common elements, filtered by user selectable criteria (RM6).

From the picture it is possible to see the similarity to the advanced search form of orders, in fact even the procedure used for research are similar to those discussed above.

49 7. Technology Used In Development Process

Since several years Microsoft launched a new development technology platform called .NET Framework, which combines in a single environment different types of programming, from WUI programming (Windows User Interface) to Web programming and programming for mobile devices. This new environment encompassing different programming languages, like C#, VB.NET and others that have been adapted to the new environment, such as Cobol.NET and J#. The usefulness of this environment is that it allows easy and versatile interaction between different kinds of applications, such was not possible with the old Microsoft technologies like ASP and Visual Basic. Through .NET is possible to make communicate a stand-alone application with a web application, perhaps sharing the same database, providing information to special devices and vice versa. The most striking feature is that several pieces of the same application can be written using several languages supported by the platform, without causing compatibility problems. A class or a simple variable written in C# can be used in VB.NET, or other languages, and vice versa. In short, it is clear that versatility is the strength of this platform.

50 Microsoft .NET Framework

The Microsoft .NET Framework is a framework software that can be installed on computers running Microsoft Windows. It could be considered Microsoft's answer to compete with the Sun Microsystems Java platform and several web development framework based on PHP in the growing market of online business application.

The core of .NET framework is the Common Language Infrastructure (CLI), which is a specification developed by Microsoft. It describes a series of technical guidelines (especially regarding the executable code and execution environment) that provide a virtual execution environment which allows applications written in multiple high-level languages being executed in different system hardware platforms without the need to rewrite those applications to take into consideration the unique characteristics of those platforms. The .NET Framework is composed by an extensive library (Base Class Library) of pre- coded solution to solve the most common programming problems, and a virtual machine () that manages the execution of programs written specifically for the framework.

Base Class Library The Base Class Library (BLC) of the framework offers a wide range of objects and implemented components, including user interface, forms, data access, database connectivity, cryptography, web application development, numeric algorithms and supporting modules for the most common network communication standards. The aim of the library is to expedite and optimize the development process and provide access to system functionality. After that, a complex stack of libraries is built on top of the Base Class Library, including technologies like ADO.NET for database access, XML APIs to manipulate XML data, and to display rich user interfaces (Uis). Any programmer can easily combine any of these items within his code to facilitate the creation of complex applications.

51 Common Language Runtime The Common Language Runtime (CLR) is the virtual execution environment (sometimes called a virtual machine) that is responsible for executing . Managed code is any code written in a high-level language such as C#, which is compiled into the CLR's bytecode, called Common Intermediate Language (CIL), or more commonly just Intermediate Language (IL).

Managed programs and libraries are comprised of metadata whose job it is to describe the physical and logical CTS components and code abstractions. IL is an assembly-like language containing hooks into CLR services and Win32 into which all managed languages are compiled. The CLR understands metadata and IL, and uses the information contained within it to load and run the program's code.

52 Execution does not happen by interpreting the IL at runtime; rather, it occurs by compiling the managed code into executable native code on the fly and executing that instead. This happens through a process called just-in-time (JIT) compilation, which is performed along that the program invokes the methods, and the resulting executable code is stored in the cache memory. Under normal circumstances this code is not saved to a file, whenever the program is re-executed the CIL is just-in-time re-compiled.

Automatic Memory Management The most heralded productivity and correctness enhancing feature of the CLR is its automatic memory management. More specifically, the CLR manages memory entirely on user's behalf, using straightforward and performing allocation mechanisms, and using a Garbage Collection (GC) algorithm to eliminate all explicit deallocation of memory from your code. The GC understands when it is legal (and profitable) to reclaim an object's memory when there are no live references to it in the program. Furthermore, it does it intelligently to avoid unnecessary CPU cycles spent on reclaiming unused memory.

53 C# Programming Language

The C# is object-oriented programming language developed by Microsoft specifically for .NET Framework programming, and approved over the years as ECMA and ISO standards. The name of the language, C♯ , was obtained by drawing two positive signs on the two positive signs of C++, in order to give an image of evolutionary leap, just as happened with the transition from C to C++. In the other hand C# has not to be considered as a direct child of C++. Its syntax is inspired by C++, incorporating elements of the Java and Delphi (which has the same author, or Anders Hejlsberg). In addition, the variety of simple visual programming tools makes it very similar to another strength language of Microsoft, Visual Basic, but much more advanced than the latter according to all the features and concepts of the object oriented paradigm.

Language features As an object-oriented language, C# supports the concepts of data abstraction, encapsulation, modularity, polymorphism, and inheritance. All methods and variables are encapsulated inside the class definitions, including the Main method, which represents the entry point of the application. Unlike C++, a class can inherit directly from only one ancestor class (single inheritance avoids the problem of using a virtual base class when diamond inheritance is needed), but it can implement any number of interfaces. C# allows implicit conversions between homogeneous types and where there is no loss of data (ex. implicit conversion from boolean to integer is allowed, but not vice versa); it has specific constructs to define the properties of a class (getters and setters), it doesn't force the management of exceptions and it enables the management of pointers (even if only in special blocks of code marked "unsafe").

Visual C# and .NET Visual C # has been created specifically for .NET Framework programming, in fact it is considered the language that best describes the main guidelines on which every .NET program runs. His primitive data types have a unique match with the Common Type System (CTS) defined in the Common Language Infrastructure (CLI) which implement the core aspects of .NET framework. Further many of the abstractions of C#, such as classes, interfaces, delegates, and exceptions, have been suitably designed to manage the .NET framework. The term Visual keynotes the mainly purpose of this implementation which is support a rapid application development of Windows-based applications, hence the fact Visual C# is packaged with the graphical IDE Visual Studio.

54 2008

Visual Studio is an Integrated Development Environment (IDE) developed by Microsoft, which supports various types of language such as C++, C #, the J # (very similar to Java and compatible with the. NET Framework), Visual Basic.NET, ASP.NET, and facilitates the creation of desktop applications, web sites, web applications and web services. Working with an IDE like Visual Studio vastly extends the expressiveness of the programs created. It includes a code editor that supports syntax highlighting, refactoring and code completion using IntelliSense, which is not only for variables, functions and methods but also for programming language statement like loops and queries. Thanks to a series of graphical components (controls) Visual Studio facilitates data exchange between presentation layer and business layer of the program, hence development of graphical interface is very simple. Each control, might be an input or output, manages data with standard formats to increase usability. Furthermore, there are methods to convert .Net Framework standard formats to standard formats used by SqlServer (datetime, smalldatetime, etc..). These features underline as Microsoft aims to create a highly compatible set of development and administration tools, in order to encourage its users to keep choosing its products along the development process. For the same features, and since Mencia's infrastructure is based on Microsoft OS and SqlServer database, was chosen to use Visual Studio as development enviroment.

55 Microsoft SQL Server 2008

Microsoft SQL Server is a relational model database server (DBMS), better known as Relational Database Management System (RDBMS), produced by Microsoft. Its primary query languages are T-SQL and ANSI SQL. SQL Server is Microsoft's alternative to other management systems powerful databases such as Oracle, Sybase ASE, PostgreSQL, Interbase, Firebird or MySQL.

The SQL Server physical architecture explains how the database platform functions internally and how it manages data effectively. Hereafter are exposed their main features.

Protocol Layer. Protocol layer implements the external interface to SQL Server. All operations that can be invoked on SQL Server are communicated to it via Tabular Data Stream (TDS). TDS is an application layer protocol, that can be encased in other physical transport dependent protocols, including TCP/IP, Named pipes, and Shared memory. Consequently, access to SQL Server is available over these protocols.

Data storage. The main unit of data storage is a database, which is a collection of tables with typed columns. For physical storage of a table, its rows are divided into a series of partitions. The partition size is user defined; by default all rows are in a single partition. Rows in each partition are stored in either B-tree or heap structure. If the table has an associated index to allow fast retrieval of rows, the rows are stored in-order according to their index values, with a B-tree providing the index. A table without an index is stored in an unordered heap structure. Both heaps and B-trees can span multiple allocation units.

Buffering. SQL Server buffers pages in RAM to minimize disc I/O. Any 8 KB page can be buffered in-memory, and the set of all pages currently buffered is called the buffer cache. The amount of memory available to SQL Server decides how many pages will be cached in memory.

Transactions. SQL Server ensures that any change to the data is ACID-compliant, i.e., it uses transactions to ensure that any operation either totally completes or is undone if fails, but never leaves the database in an intermediate state.

Concurrency. SQL Server provides two modes of concurrency control: pessimistic concurrency and optimistic concurrency.

56 • Pessimistic concurrency controls concurrent access by using locks. Locks grant the user exclusive access to the data. The latter would have to wait for all locks to be released. • Optimistic concurrency control mechanism, instead of using locks, allows a new version of a row to be created whenever the row is updated, as opposed to overwriting the row. Both the old as well as the new versions of the row are stored and maintained. When a row is in the process of being updated, any other requests are not blocked (unlike locking) but are executed on the older version of the row. If the other request is an update statement, it will result in two different versions of the rows - both of them will be stored by the database, identified by their respective transaction Ids.

SQL CLR. (SQL Common Language Runtime) It is technology for hosting of the Microsoft .NET common language runtime engine within SQL Server. The SQL CLR allows managed code to be hosted by, and run in, the Microsoft SQL Server environment. That way memory, threading and resource management requirements of .NET Framework are satisfied by SQLOS itself, rather than the underlying Windows operating system.

XML Support. SQL Server 2008 includes native support for managing XML data, it defines an XML data type which supports the storage of XML documents. XML instances stored using the XML data type can be associated with an XML schema (XSD) that validates and types the instance which is verified against it. XML data can be queried using XQuery.

57 EMS SQL Manager

EMS SQL Manager for SQL Server is a tool for Microsoft SQL Server database development, management and administration. Its components focus on all the most common database tasks, but it also provides tools for database migration, extraction, data import, export and comparison. SQL Server Manager can also be used to visually observe and analyse query plans and optimize the database performance.

EMS SQL Manager includes the following tools:

• The SQL Manager simplifies and automates the database development process. Includes features to design, explore and maintain existing databases; it allows to view, print and manipulate data and to define user privileges on database objects visually. • The Data Generator is a wizard application that allows to define tables and fields for generating data. • The Data Export & Import tools allow to import data from and export data to the most popular data formats, including MS Access, MS Excel, MS Word, PDF, HTML, PDF, TXT, CSV, DBF, XML, ODF and more. • The Data Pump tool allows converting database structure and data from any ADO- compatible source to an SQL Server databases. • The DB Extract allows to Create database backups in the form of SQL scripts, saving the database structure and table data as a whole or partially. • The DB Comparer is a tool to compare and synchronize the structure of multiple databases. It allows to view all differences of compared database objects and execute an automatically generated script to eliminate all or selected differences. • The Data Comparer is similar to the DB Comparer but it works with the contents of multiple databases. It allows to view all differences of compared tables and execute an automatically generated script to eliminate these differences.

Thanks to all these features, SQL Manager provides permits multiple host/database connections, database and server properties management, managing views, procedures and user-defined functions, managing user-defined types, synonyms, DDL triggers, assemblies, aggregates, XML schema collections, defaults and rules, managing partition functions and schemes, full-text catalogs and indices, symmetric and asymmetric keys, certificates, creating diagram of existing database using Reverse engineering tool.

58 WinAutomation

WinAutomation is a program that provides task managers to automate routine tasks. The program builds compiled jobs that use combinations of simulated keystrokes, mouse movement and window-control manipulation in order to automate tasks in a way not possible or reliable with other languages. A compiled job runs on Windows operating systems with .Net Framework installed on the machine. The features of WinAutomation met perfectly the project needs and made it the right tool to automate the data downloading process. Moreover, cost reduction due to labor savings automating the process quickly cover the cost of acquiring the software license.

59 Appendix I The Company

The Mencia Comunicaciones S.L. is the company where took place the period of training. It is the associated company of ONO for the region of Murcia and the province of Ciudad Real, providing technical services for installation and maintenance on behalf of the leader company for customers of a limited geographic area.

Expertise areas of Mencia Comunicaciones S.L.: Murcia and Ciudad Real

The ONO is the leader communications and broadband entertainment company in Spain, delivering integrated telephone, television and internet services to its residential customers, as well as telecommunications services of high added value to SMEs, large companies and institutions. The operator owns a fiber optic network deployed throughout Spain, through which nearly seven million users and companies have exploited for years of the high-speed and stability provided by that network.

60 Appendix II Database Schema

The chart below shows the current state of the database. Although only a few tables have been used in the project developed during the training period the whole database schema has been reported. As mentioned the Database was designed according to the database currently in use to allow simultaneous use of both databases. This means that in addition to the tables needed to store the information about the commissioned services additional tables were created to host the company's internal information. These tables were developed based on the previous schema to facilitate the transition of information into the new system, but they are not used since the respective areas of management have not been implemented yet.

61 62 As seen in the schema there are fields that appear in more tables; this choice was not by chance but rather due to the unreliability of data coming from ONO. Every order or maintenance request is stored with client information, to prevent that an erroneous data included in the request by the operators will affect the information of clients in the database.

63 64 Conclusions

The main purpose of the period of training is to give the trainee the opportunity to apply the knowledge gained during his degree course, and to give him a way to acquire new knowledge that the university is not able to provide. This actually happened in my case. The experience at Mencia Comunicaciones S.L. offered me the possibility of using tools with proprietary licenses, whose use is quite rare in academia. The use of advanced tools gave me a broad understanding of which technologies are nowadays available on the market, and how those can work at high levels of efficiency, saving time and obtaining highly complex products, but stable at the same time. Besides the knowledge acquired during the studies provided the ideal background to understand those instruments. The high level of abstraction provided by the modern development platforms on one hand reduces the conceptual distance between analysis and implementation, while on the other hand brought me to face a new class of problems, especially arising from components interaction and event management. By these reasons I reckon that a period of training in a business company can be evaluated and enjoyed more positively than a research project inside the university because it puts the student in direct contact with the world and the market of labour, which is the exact environment that the majority of students will have to integrate into soon thereafter.

65 Bibliography

Books

• Professional .NET Framework 2.0. by Joe Duffy - Wiley Publishing, Inc.

• Inside C#, Second Edition by Tom Archer and Andrew Whitechapel - Microsoft Press

• INTERNATIONAL STANDARD ISO/IEC 23271, Common Language Infrastructure (CLI)

• Microsoft SQL Server 2008 Internals (Pro – Developer) by Kalen Delaney, Paul S. Randal, Kimberly L. Tripp, and Conor Cunningham - Paperback

Online

• http://articles.sitepoint.com • http://msdn.microsoft.com • http://www.csharpkey.com • http://www.csharphelp.com • http://www.csharp-station.com • http://www.ecma-international.org • http://www.microsoft.com • http://www.sqlmag.com • http://www.sqlmanager.net • http://www.w3schools.com • http://www.wikipedia.org

66 Es la unica razon para levantarse por la manana, la unica razon por la que aguantas a tu jefe, la sangre el sudor y las lagrimas. Lo haces porque quieres que la gente sepas lo bueno, atractivo, generoso, selvagemente divertido e inteligente que eres. Temedme o veneradme! Pero porfavor pensad que soy especial. Compartimos una adiccion: somos junkies de la aprobacion ajena. Todos aguantamos por la palmadita en la espalda y el reloy de oro, el jodido hip-hip hurra. Ficate en el cicho listo con le insigne sacandole brillo al su trofeo, sigue brillando diamante loco. Porque no somos mas que trajeados suplicando la aporobacion de los demas. Si supieramos eso no hariamos esto, alguien nos lo esta ocultando. Y si tuvieras una segunda oportunidad preguntarias: porque?

67