Table of Contents
Advanced Business Programming with C# 2005 byDonald L. Voils Electronic & Database Publishing, Inc. 2007 (1675 pages) ISBN:9780979359101
With particular emphasis placed upon the creation of GUI business programs, this introductory guide covers the writing of business programs using C# from Microsoft Visual Studio .NET 2005.
Table of Contents Advanced Business Programming with C# 2005 Preface Lecture 1 - Introduction to Business Programming Lecture 2 - C# Language Fundamentals Lecture 3
- Methods in C#, Text File I/O and Structures
Lecture 4
- Classes in C#
Lecture 5
- Class Extensions and Polymorphism
Lecture 6
- Operator Overloading
Lecture 7
- Interfaces
Lecture 8
- Arrays and Collections
Lecture 9 - String, String Builder, Char and Regex Classes Lecture 10 - Handling Exceptions Lecture 11 - Generics in C# Lecture 12 - Delegates and Events Lecture 13 - Building Windows Applications and Event Driven Programming Lecture 14 - File Input/Output and Object Serialization Lecture 15 - Accessing Data with ADO.NET List of Tables
file:///D|/1/final/toc.html [01.12.2007 04:47:30]
Back Cover
Back Cover Lecture Objectives: This electronic book presents lectures that may be used in a college or university semester class dealing with the writing of business programs using C# from Microsoft Visual Studio . NET 2005. The major programming emphasis is upon the creation of GUI business programs. Prerequisite requirements: These lectures assume that the student already has taken business courses including accounting. Since this is an advanced business programming course, it is assumed that the student has experience in programming business applications using the C++ programming language.
file:///D|/1/final/backcover.html [01.12.2007 04:47:31]
Advanced Business Programming with C# 2005
Advanced Business Programming with C# 2005 By Donald L. Voils Business revolves around the world and computers make it happen. Copyright © 2007 Don Voils ISBN-13 978-0-9793591-0-1 ISBN-10 0-9793591-0-4 Published by: White Feather Publishing 12524 Shoreline Line Drive Suite 301 Wellington, Florida USA 33414 There are examples included in each lecture. However if you would like separate copies of the examples, the graphics, the Excel spreadsheets or the Access databases used in some of the exercises, email: dvoils@adelphia. net for shipping and handling costs. Dedication These lectures are dedicated to the many students from all over the world who have studied these lectures and the many other lectures that I have written. These lectures are also dedicated to my wife Connie without whose unending support none of this would have been possible. Finally I would like to dedicate these lectures to those of my ancestors who were here in the USA prior to the immigration of the many peoples from all over the world. May the Great Spirit watch over you as long as the grass grows and the river flows. Pawnee Proverb
file:///D|/1/final/BBL0001.html [01.12.2007 04:47:31]
Preface
Preface Lecture Objectives: This electronic book presents lectures that may be used in a college or university semester class dealing with the writing of business programs using C# from Microsoft Visual Studio .NET 2005. The major programming emphasis is upon the creation of GUI business programs. Prerequisite requirements: These lectures assume that the student already has taken business courses including accounting. Since this is an advanced business programming course, it is assumed that the student has experience in programming business applications using the C++ programming language. In addition the student should be familiar with the following programming concepts: ●
●
Structure programming: ❍
Sequence,
❍
Selection
❍
Repetition
❍
Modularization.
Object oriented programming ❍
Encapsulation
❍
Polymorphism
❍
Inheritance
Software requirements: Since these lectures are based upon Visual Studio .NET 2005, it is assumed that the student has access to this software. In addition UML charts will be used and therefore it is assumed that the student has access to Microsoft Visio 2003 Professional or a similar program. The lecture notes: When using these lecture notes, you must have access to an Internet browser that in addition has access to Adobe Acrobat 7.0 or higher. The lecture notes contain links to the C# examples. When viewing the notes, you should have open Visual Studio .NET 2005 in addition to the browser. Visual Studio .NET should be set up and ready to compile and run a C# program. (How to do this will be illustrated later in the lecture notes.) Look at each example very closely to ensure that you understand what the example is attempting to show. Using Select in Adobe Acrobat, copy the program to the Clipboard. After the code has been copied to memory, click on Visual Studio .NET into the current project. Next, click on Ctrl-A followed by Ctrl-V (which pastes the copied code into Visual Studio .NET). When using a console example, the project must be set up to be a console project. When using a Windows example, the project must be set up to be a Windows project. Note: In Visual Studio .NET 2003 Windows projects were only one file. However in Visual Studio .NET 2005, Windows project are three or more files so steps must be taken to take advantage of this fact especially when using the examples listed in each lecture. Some of the examples that are included in the book are one file Windows programs written in Visual Studio .NET 2003. If a console project is created, then the Windows sample can be copied into the project. Note: Some of the examples use Excel spreadsheets, some use graphics while others use Access databases. These samples are not included in this book. If you would like these samples, email:
[email protected]. Note: These lectures are menu driven using Adobe Acrobat bookmarks. It is therefore possible to link from the Table of Contents below to a particular lecture and back. Then within each lecture, it is possible to link to a subsection of that lecture and to the many examples that are added to the end of each lecture. Further, it is possible to link from one lecture to the next lecture.
file:///D|/1/final/BBL0002.html (1 von 2) [01.12.2007 04:47:32]
Preface
file:///D|/1/final/BBL0002.html (2 von 2) [01.12.2007 04:47:32]
Lecture 1: Introduction to Business Programming
Lecture 1: Introduction to Business Programming The Study of the Use of Computers The study of the use of computers has changed significantly over the last twenty five years while I have been working in this field. At first this field of study was mainly devoted to the use of computers to solve business problems. Most of the books and research papers published in the early years were written to serve that use of computers. However during the last ten years, there has been an increased use of computers to solve non business problems. For example a larger and larger amount of time is being devoted to the study of the Internet not only for business but for non business purposes as well. There is becoming an increased use of cell phones and devices like PDAs and electronic devices embedded in machinery like cars which require programming as well. There has been an increased use of computers in the area of graphics, gaming, music, video and for other personal entertainment devices. The field of computer science at some colleges and universities has therefore split into several different approaches to the study of computers specifically: business and non business. The study of the business use of computers can now frequently be found in the School or College of Business. This area of computer science is sometimes called Management Information Systems (MIS) or Computer Information Systems (CIS). Other names are sometimes used to describe this field of study. The study of the non business use of computers can now frequently be found in a separate Department of Computer Science. This CS department is sometimes in the College of Engineering or is sometimes included in the Mathematics Department. The topics studied under this arrangement might include: communications, multimedia, data bases, computer security, software quality assurance, programming languages, operating systems, computer networking and many other topics. The languages used for these courses have varied from machine language to COBOL, Fortran, Pascal, C, C++, Java and now C#. The language C supports structured programming. C++ extended C and the concepts of structured programming to include object oriented programming (OOP). C# extends beyond these styles by adding component oriented and event driven programming using a graphic user interface (GUI). In addition C# adds the ability to easily access database data and to create Internet programs. This course will begin with an introduction to the structured programming and the component oriented side of C#. Next the OOP side will be introduced. This will be followed with the event driven program and then database access. These lectures will not consider C# programming for the Internet. This course is not meant to be an extensive study of program design and development. This course is only an introduction to the subject. If you continue your formal study of business programming, you should take additional courses on this subject. What should be done after taking this class is to take a courses in SRS (Software Requirements Specification), OOA (Object Oriented Analysis), OOD (Object Oriented Design), OOP (Object Oriented Programming), Software Testing, SQA (Software Quality Assurance), Software Security, programming for a network environment and to study Java and C# more in depth. These online course notes are meant to complement any other required texts and to hopefully add materials that will be helpful to the MIS major. The design discussed in the online notes will include more of a discussion of UML (Unified Modeling Language) than you will find in some texts. Since the field of MIS changes so rapidly, you will need throughout your career to continue your education in the field yearly in order to keep up and in order to keep your job. For example, the previous edition of this text dealt with C# 2003. These lectures deal with C# 2005. It is expected that Microsoft will introduce another version shortly: C# 2007.
file:///D|/1/final/BBL0003.html [01.12.2007 04:47:32]
What is Programming?
What is Programming? As a new programmer, it is important for you to: ●
Know that programming is an art which training can improve upon but that you can not become a programmer unless programming is an art that you were given as a human being.
●
Know the company you work for and the internal politics which is as important as the computer concept that you will use.
●
Know and to be able to converse with the business clients, the users and other stakeholders for whom the program is being developed.
●
Know the field for which the program is going to be developed.
●
Know that software is: ❍
a computer program (i.e. code)
❍
the procedures for using the code
❍
❍
the documentation which describes the reasons for creating it, describes the code, and describes how to use it. data to run the code on to test all possibilities
But what is most important for you is the need to: "Know thyself" and you need to ask yourself ●
How do I approach problems?
●
How do I work with others?
●
Which of the 5 phases of software life cycle that will be discussed below do I enjoy most and which do I do well in?
file:///D|/1/final/BBL0004.html [01.12.2007 04:47:33]
The 5 Phases of Software Life Cycle (SLC)
The 5 Phases of Software Life Cycle (SLC) 1. Problem Analysis and Specification Phase (Software Requirements Specifications) 2. Design Phase (Software Design) 3. Coding Phase (Implementation of Design) 4. Testing, Execution and Debugging Phase (Software Testing) 5. Maintenance Phase (Software Maintenance) Note: The approach to software life cycle listed above is sometimes referred to as the "waterfall" approach where one phase follows immediately after the other. Note: Each of these phases produces documents. As the project progresses, these documents will have to be written and then rewritten. Some believe that documentation is so important that when discussing the 5-phases a sixth phase should be added: the documentation phase. Note: Errors in the software system can be created in any one of the 5-phases. Some of the causes of these errors are: ●
faulty system's analysis
●
communication errors between the stakeholders and the developers
●
feature "fluff" where the stakeholders request features that are not needed
●
deliberate deviation from the specifications by the computer system's staff
●
logical design errors
●
coding errors
●
non-compliance with the specifications
●
incomplete and inaccurate testing
●
procedure errors
●
documentation errors
●
errors caused by insufficient time and money devoted to each phase
Note: In a large corporation's information technology dealing with a large project, the specification phase could take 2 months, the design phase could take 4 months, the coding phase could take 3 months and the testing phase could take 3 months. This would be followed with user training that might take 1 month. The maintenance phase starts this process all over so you can see that software development can take a long time and in fact never end. Some projects can take years to complete. In fact some projects can take so long that the reason to begin the project is no longer important and the project is canceled. Note: Although not discussed during this course, a user's manual should be created. Its construction should begin during the first phase and should continue until after the project is completed. Note: Although not discussed in this course, part of the phases should be a training phase both of those who are to create the program as well as those who will use it. In addition some testing should be conducted in each phase
file:///D|/1/final/BBL0005.html (1 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
with the major testing taking place during the Testing Phase. The quality assurance should continue throughout the project. Note: In a software development and maintenance organization, the different types of positions available can be: ●
Software or Systems Quality Assurance Engineer
●
Software or Systems Analysts
●
Software or Systems Designer
●
Programmer
●
Software Tester
●
Software Maintenance Technician
●
Systems Security Engineer
●
and team leaders for each of these groups.
Try to determine which of these positions best meets your qualifications and professional goals. Note: Some new terms have been added that better describe how the SLC is implemented. These terms are: White Box SLC, Grey Box SLC and Black Box SLC. By these terms the following is meant: ●
White Box SLC means that all of the phases of the SLC are done by the IT employees of the company for whom the system is being developed.
●
By Grey Box SLC is meant that some of the phases or parts of a phase are done internally by the IT employees of the company for whom the system is being developed while other phases or parts of these phases are out sourced to other companies like the Coding Phase or the Testing Phase.
●
By Black Box SLC is meant that most if not all of the phases are performed by one or more outside IT companies. While almost the entire project is out sourced, the company's employees may participate somewhat by providing necessary information for the out sourced contractors.
Problem Analysis and Specification Phase In this phase the analyst, the security and the quality assurance engineers attempt to do each of the following and to create software requirements specification documents that address these issues: ●
Obtain a formal statement of the software requirements.
●
Obtain copies of the major reference documents.
●
Determine what platform the final project will run on and what computer language as well as what version of the language the project must be written in.
●
Determine who the users and other stakeholders will be, what type of User Interface (UI) will be required and how often the program will be used.
●
Determine what level of fault tolerance and security will be required and whether the final project will be open to judification in a court of law.
●
Develop benchmarks that will be used to evaluate the final system.
●
Collect sufficient data to be used for testing through the entire project during each of the phases as well as in the Testing Phase.
●
Ask questions of the users, those in management and other stakeholders who will monitor the project to ensure
file:///D|/1/final/BBL0005.html (2 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
that what is truly being requested is understood. ●
Determine whether the specifications must be written in the design phase using one of the formal methods like: Z, VDM, Larch, UML or some other design methodology and if so then the specifications must be written to support that methodology.
●
Write descriptions of the input and output and then show it to the client, the users and other stakeholders for their verification.
●
Write and then rewrite the system specifications as they become better known.
●
Ask the client, the users and other stakeholders after each rewrite whether the newly written specifications are closer to what the real needs are.
●
Ask the clients, the users and other stakeholders whether their stated specifications are a real requirement or whether some of it is "fluff" i.e. something that would just be nice to have.
To be a good analyst you need to have: ●
analytical skills
●
technical skills
●
managerial skills
●
interpersonal and communications skills as the most important skills that are needed
At the end of this course, you need to ask yourself: ●
Do I want to do Problem Analysis and Specification? If you do, then you need to study OOA in more depth and seek to become certified as a Business Analyst.
●
Do I have the necessary skills to be successful doing this phase?
Note: During this course you will prepare a specification document for each programming homework but you will not be required to act as a systems analyst. Note: This phase is sometimes referred to as the System Requirements Specification (SRS) phase. Part of this phase can include an analysis process called: Object Oriented Analysis (OOA) and System Security Specification. Note: As part of the SRS should be a determination and documentation of the training needs of the system users in order to increase the possibility of a successful project. Note: It is recommended that you read the following book: Wiegers, Karl; Software Requirements 2nd Edition; Microsoft Press; Redmond, WA 2003; ISBN 0-7356-1879-8
Design Phase In this phase sometimes be called Object Oriented Design (OOD), the programmer attempts to: ●
Identify the objects in the problem's specification and their data types to identify the data structures and then to create graphics and charts that describe these data structures.
●
Identify the multiple modules needed to solve the problem and then to create a graphical representation that describes the relationships between these modules.
●
Identify the User Interface components (there may be more than one i.e. a customer UI v.s. an employee UI) and design how each of these UIs will appear.
file:///D|/1/final/BBL0005.html (3 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
●
Identify the security components that will be required.
●
Create for each module an algorithm (that is a sequence of steps), that when applied in the programming language, will solve a particular part of the problem.
●
Develop the algorithms so that they are:
●
❍
Definite and unambiguous
❍
Simple
❍
Finite
But most importantly understand that the design should create a program that is well structured and where: ❍
●
program = algorithms + data structures
Develop the design using the Design Tools
At the end of this course, ask yourself: ●
Do I want to do Design? If so, then you should take additional courses in OOD.
●
Do I like to analyze things in their smallest details? If so, then you should study OOA.
●
Do I like to write descriptions of these minute details, to draw pictures of these tiny details and then to describe what I see to others?
●
Do I have the people skills to do the design phase?
Note: The need to off shore programming may decrease in the future because several companies are offering tools that take the designs that are created in UML 2.0+ and converting these design documents into C++ or C# programs as will be demonstrated later when UML charts in Visual Studio .NET 2005 will be used to write the definitions of classes. It is also possible with tools like these to convert C++ or C# program into UML design documents as will be seen later when Visual Studio .NET 2005 is used to convert class definitions into UML documents.
Design Tools Some of the design tools: ●
Abstract Data Type Description (a collection of standardized symbols like UML that illustrate the overall relationships between the major pieces of the program including the data)
●
Human Interface (a collection of sample or potential screens and reports that shows what the user will see.)
●
System Flowcharts (a collection of standardized symbols that illustrate the relationships between all of the programs in the system)
●
Structure Chart (a collection of standardized symbols that illustrate the overall relationships between the major pieces of the program to include the movement of data between the individual modules if any)
●
Flowchart (a collection of standardized symbols that express the logic flow of a program.)
●
Pseudo Code (a mixture of natural language (not necessarily English), terms, symbols and other features commonly used in one or more high-level languages that express the logic flow of a program.
Abstract Data Type Description These descriptions could include data type descriptions using UML data charts like the following: file:///D|/1/final/BBL0005.html (4 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
CustomerRecord -firstName -lastName -accountNumber -currentBalance +addCustomer( ) +modifyCustomer () +changeBalance( ) …
TransactionRecord -accountNumber -transactionAmount -accountType +addTransaction( ) +modifyTransaction () …
Human Interface This may include reports like the following: Southern Warehousing Monthly Accounts Open table as spreadsheet Customer Name
Account Number
Starting Balance
Customer One
1111111
XXXX.XX
XXX.XX
Customer Two
2222222
XXXX.XX
XXXX.XX
Customer Three
3333333
XXXX.XX
XXXX.XX
....
....
....
Totals
Ending Balance
.... $XXXXX.XX
$XXXXX.XX
System Flowchart System flowcharts show the interrelationship between different parts of the total system and the program being written:
file:///D|/1/final/BBL0005.html (5 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Structure Chart A structure chart shows the modules of the program being written and their relationships and in some cases the movement of data between the modules:
Flowchart Flowcharts show the modules and their interrelationships, the program's logic and the variable names.
file:///D|/1/final/BBL0005.html (6 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Pseudo-Code Pseudo code show the modules their interrelationships, the programs logic and the variable names but it does this using words: START PROCESS Initialization PROCESS Report Heading Read fname, lname, accout_no, start_balance, transaction_type DOWHILE(More Records) PROCESS Detail Record Read fname, lname, accout_no, start_balance, transaction_type ENDDO PROCESS Report Totals END Initialization total_previous = 0.00 total_current = 0.00 Return
file:///D|/1/final/BBL0005.html (7 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Report Heading Display Company Name, Report Name, Column Headers Return Detail Line Display name, account_no, start_balance, end_balance Return Case 'D' total_previous = total_previous + start_balance end_balance = start_balance + transaction total_current = total_current + end_balance Return Case 'W' total_previous = total_previous + start_balance end_balance = start_balance - transaction total_current = total_current + end_balance Return Invalid Case Display Error Message Return Detail Record CASEENTRY Opcode CASE 'D' PROCESS Case 'D' CASE 'W' PROCESS Case 'W' Case other PROCESS Invalid Case ENDCASE PROCESS Detail Line Return Report Totals Display total_previous, total_current Return
Coding Phase (Implementation of the Design) In this phase the programmer: ●
Encodes the program modules into the previously selected language and version that was selected in the Specification Phase using the data types, the logic, the modular design, the security issues and the variable names selected in the Design Phase.
●
While creating the modules, writes the code in a: Well structured, documented and stylistic manner
●
Combines the program modules into a complete software system.
●
Ensures the program quality and that the code is correct, readable and understandable by reading the code in each module and in the combined program.
●
Hand verifies the logical correctness and the integration of the various parts of the program by using the sample data generated in the Specification Phase.
file:///D|/1/final/BBL0005.html (8 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC) ●
Translates the program from the source code into machine code using the selected language's compiler to determine if there are any syntax or warning errors.
At the end of the course, ask yourself: ●
Do I want to do Implementation of the Design phase (i.e. do you want to do the Coding Phase? If you do, then you should study OOP.
Well-Structured, Documented and Stylistic Programs The code needs to satisfy the following criteria (This list is sometimes referred to as the developer's requirements to distinguish it from the program requirements): ●
The program should have opening comments.
●
Each module should be documented like the program with opening comments.
●
There should be internal comments that explain each key section of the program and each module.
●
Each module and each variable should use meaningful names. If the name is one word, then it should be in lower case. If a name contains more than one word, then the first word should be in lower case and the first letter of the remaining words should be in upper case while the other letters in these words should be in lower case.
●
The documentation of the program and of each module should be formatted in a style that enhances its readability by meeting the following criteria: ❍
Each program statement should be on a separate line.
❍
Upper and lower case should be used in a way that enhances readability.
❍
❍
❍
The placement of each { symbol and its corresponding } should be listed on separate lines from the other code and listed in the program so that they are vertically aligned. There should be an indentation of the lines that are enclosed within a { and its corresponding } The indentation of statements that are more than one line should be written so that after the first line they are indented more with respect to the first line.
❍
There should be vertical alignment of the names of the variables when they are defined.
❍
There should be blank lines inserted between definitions, declarations, statements, and blocks of code.
❍
❍
❍
The placement of the definitions and declarations of variables should be near the top of the section where they are first used. There should be a separation of the operators from their operands by spaces. The output should be labeled so that the user understands what they are being asked or what they are viewing
Testing, Execution and Debugging Phase This phase is sometimes referred to as the Software Quality Assurance (SQA) phase. By Software Quality Assurance is meant: ●
A systematic, planned set of actions necessary to provide adequate confidence that the software development process or the maintenance process of a software system product conforms to established functional technical requirements as well as with the managerial requirements of keeping the schedule and operating within the budgetary confines.
file:///D|/1/final/BBL0005.html (9 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
In this phase the programmer or the Software Quality Assurance (SQA) staff checks each of the following: ●
Checks for Validation. That is the SQA staff tries to answer the question: "Are we building the correct product?" To do this the QA staff needs to check that the documents, the program modules, etc. to see if they match the requirements of the users and other stakeholders.
●
Checks for Verification. That is SQA staff tries to answer the question: "Are we building the product correctly?" To do this SQA staff needs to check that the product is correct and complete as well as whether the parts are consistent with each other and whether they are consistent with the documents of the preceding phases.
In addition to testing during the Testing Phase, the SQA staff is aware that errors may occur in any of the phases and therefore they test each phase. The SQA staff is aware that errors may occur for various reasons to include: ●
Software Requirements Specifications don't accurately reflect given information or the user's and other stakeholder's needs/requests
●
Logic errors in algorithms
●
Incorrect coding or integration
●
Failure to handle boundary data or test values
The SQA staff knows that there are different kinds of testing types which are required and uses them where appropriate. The SQA staff knows that no matter how much they test the program, there will still be bugs and they strive to keep the number of errors within acceptable limits At the end of the course, ask yourself: ●
Do I want to do Testing, Execution and Debugging? If so, then you may become a member of the Software Quality Assurance or Software Testing group.
●
Do I have the skills to be successful in this area? If so, then you may want to take additional courses in software testing and software quality assurance. In addition you might want to consider becoming a Certified Software Quality Assurance Engineer.
Note: The quality assurance staff might want to consider the purchase of one of the many testing software programs to support the testing process. Note: Testing done by the coding team may not yield quality testing because of their involvement in creating the code. In addition there may also be problems when the testing is conducted by members of the same company as the coding team. Sometimes it is necessary to contract with an outside testing company in order to gain quality testing. Note: One of the major causes of programs not passing the testing process is that the project had difficulty meeting SRS deadlines and staying within budget. Note: One of the problems may be that the program passes the testing phase yet did not meet the SRS. In fact testing may determine that there is a need for recoding of the program and maybe even determine that there needs to be a completely new SRS. Note: This discussion of SQA may seem to imply that software quality assurance does not begin until after the coding has been completed. What should be noted is that, the testing may need to begin as soon as the SRS has been accomplished or even as part of the SRS. Note: The SQA budget may be as much as 20% – 30% of the total cost of the program. It may be determined when considering the costs that the SQA should be handled by an outside SQA firm.
file:///D|/1/final/BBL0005.html (10 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
Note: I recommend that you read the following book: Galin, Daniel; Software Quality Assurance; Pearson Education; London, England; 2004; ISBN 0-201-70945-7
Testing Types Testing consists of many different types of tests to include: ●
Unit tests that include: ❍
●
●
❍
Testing the program components in isolation
❍
Verification that each individual program unit works as designed
❍
Testing for errors to include: syntax errors
■
warning errors
■
linking errors
■
run-time errors
■
logical errors
■
system and data security leaks
❍
Testing that determines if the units combine correctly
❍
Testing the component interfaces and information flow
❍
Testing that determines whether the data moves correctly from one unit to another
System tests that include: Testing that determines whether the overall system is working correctly
Black box (or functional) tests that include: ❍
❍
❍
●
■
Integration tests that include:
❍
●
The most rigorous and time intensive part of the testing and is the most fundamental and the most important
Testing that determines whether the set of test data works. Testing of the output produced for various inputs for correctness without considering the structure of the program component itself. Testing a program unit as if it is a black box that accepts inputs and produces outputs, but ignores the inner workings of the box.
White box (or structural also called glass-box because the tester looks inside of the program components) tests include: ❍
Testing of specific sections of the program to determine if each section is working correctly
file:///D|/1/final/BBL0005.html (11 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC) ❍
Testing the performance by examining the code's internal structure.
❍
Selecting test data carefully so that specific parts of the program units are exercised.
❍
❍
Testing that may include the following of the values from one variable to the next by using the debugger and its jump points. This testing is more expensive that Black Box because the tester looks at the interior workings of each individual part of the program.
Testing is frequently subdivided into two general types: ●
Alpha Testing that is done in-house by staff members (This group is frequently called the Software Quality Assurance or Testing staff.)
●
Beta Testing that is done outside of the company and is done by "real people" where the system developers try to determine: ❍
❍
Is it possible for "real people" to interact with the program as it is designed and meet the system requirements specification? Do "real people" get the correct outputs for specific inputs?
Note: I recommend that you read the following book: Craig, Rick et al; Systematic Software Testing; Artech House Publishers; Boston, MA; 2002; ISBN 1-58053-508-9
Maintenance Phase (Adding Enhancements) As a future programmer, it is important for you to know some of the reasons for the need of the maintenance phase. These reasons can be: ●
that some of the previous phases were done incorrectly.
●
that the original program specifications or the business plan has changed.
●
that because of poor program structure, poor program documentation or poor program style you are required to redo some of the program or all of the program.
●
that the testing did not catch all of the bugs before the release so that some or all of the program needs to be redone‥
●
that marketing or management was trying to hurry the development of the program before it was completed so that they could deliver the product.
It is important for you to know: ●
that the fixing of bugs is difficult, time consuming and never ending.
●
that the process of removing bugs impedes implementation of program enhancements.
●
that some of the reasons that maintenance may fail are: ❍
❍
the code does not agree with the documentation. changes were made to the program but there is no documentation to indicate what or why the changes were made.
It is also important for you to know that this phase can be the:
file:///D|/1/final/BBL0005.html (12 von 13) [01.12.2007 04:47:35]
The 5 Phases of Software Life Cycle (SLC)
●
Largest % of computer center's budget
●
Largest % of programmer's time
●
Largest % of software development costs
●
Only type of IT positions open at some companies
At the end of the course, you need to ask yourself: ●
Do I want to do maintenance?
●
Do I have the skills necessary to do this type of work?
file:///D|/1/final/BBL0005.html (13 von 13) [01.12.2007 04:47:35]
The "Real" 5-Phases
The "Real" 5-Phases Software development should not follow the "waterfall" approach as seems to be implied by the previous section of this lecture. What is really needed is interplay between each of the phases. A reinterpretation of the five phases of software development is shown in the graphic below where each phase is connected to every other phase. This approach is sometimes referred to as "spiral" software development. In addition to having each phase connected to every other phase, Security and Quality Assurance should be connected to every phase as well. The most important feature of this approach is to notice that the Users (and other stakeholders) are central to the phases and that they need to be involved throughout the entire project.
In addition to not following a linear approach to software development, another modification of the five phases utilizing a component library approach is recommended. In this approach components from the company's software library are used if they exist and if not, then new components are created and utilized. This approach is referred to as "component" software development. The following graphic shows the five phases slightly modified to represent this approach:
file:///D|/1/final/BBL0006.html (1 von 2) [01.12.2007 04:47:35]
The "Real" 5-Phases
While using components in the company library is the approach to take, extra care must be taken not to modify these components and therefore to make them unusable to future as well as previously written programs. Again you should consider that security and quality assurance are involved throughout this process. As you progress through these lectures, you should try to develop components that could be used in your future programming. These components could be stored in a dynamic linked library a .dll file like: tools.dll. While the code in this course is in C#, it is possible that some tools developed for this course could be used in C, in C++ or even in Java programs.
file:///D|/1/final/BBL0006.html (2 von 2) [01.12.2007 04:47:35]
CASE Tools
CASE Tools Today, to aid in the development of the 5-phases, CASE tools (i.e. Computer-aided Software Engineering tools) are used. In researching for these lectures, I found the following definition of CASE tools. Definition of CASE tools: CASE tools are computerized software development tools that support the developer when performing one or more of the phases of the software life cycle and/or support software maintenance. In these lecture notes two different CASE tools will be used: Microsoft Visio 2003 © and Microsoft Visual Studio . NET 2005 ©. CASE tools are subdivided into several categories. Two of the categories are: "classic" and "real". Computer compilers are examples of "classic" CASE tools. CASE tools that can be used in several of the phases are called "real". Both Visio and Visual Studio .NET can be considered "real" CASE tools using this definition. Some of the new testing tools on the market can be considered "real" as well because they can be involved in several of the 5phases. Another categorization of CASE tools are "upper" and "lower". By the term: "upper" CASE tools is meant those tools that support the first two phases while the "lower" CASE tools support the last three phases. In terms of these categories, Visio is considered an "upper" CASE tool while Visual Studio .NET is considered to be a "lower" CASE tool. Both Visio and Visual Studio .NET have a greater capacity as CASE tools than will be studied in this course. It is recommended that you try to go beyond their minimal introduction and study both of these CASE tools more in depth. Many students do not like to use the power of these tools until they are forced to. However you will find that in general, once you learn how to use them, they will save considerable amounts of time. For example in the Galin book listed below, he provided data on a programming job that required 110 days for the 5-phases to develop the software using traditional non-CASE tool methods. When the same program was created using CASE tools, only 61 days were required. He claimed that if advanced CASE tools had been used then there would have been an even greater reduction in time spent on development of the program. The following graphic attempts to illustrate how traditional programming compares to using CASE tools. This graphic is from the Galin book p 301.
file:///D|/1/final/BBL0007.html (1 von 2) [01.12.2007 04:47:36]
CASE Tools
Note: In the graphic above, Repository means the collection of the documentation from all phases of the software development. Note: In the graphic above, notice the different categories of the development team. Your goal as a future member of a software development team is to determine which of these jobs you are the best at and which you want to work on. The above discussion is a modification of the topic from the following book which I highly recommend that you read: Galin, Daniel; Software Quality Assurance: From theory to implementation; Addison Wesley, 2004. p 298 – 304.
file:///D|/1/final/BBL0007.html (2 von 2) [01.12.2007 04:47:36]
The Team
The Team The project team consists of many different groups of individuals to include: ●
Upper Management
●
Middle Management
●
Team Manager
●
Users ("Real People" or "Stakeholder")
●
Program Analysts
●
Program Designers
●
Program Coders
●
Test Center Staff (Quality Assurance)
●
Program Maintenance Staff
●
System's Deployment Staff
●
System's Security Staff
●
Help Center Staff
Which of the above positions you will be assigned will depend on the project, your talents, your client and your company. Note: In today's world the groups listed above may not be in the same part of the world or even within the same company. Some companies do the analysis and the design internally and sub job out the coding. The testing may be done internally but it could also be sub jobbed out as well. Since the maintenance can link back to the top of this list, these staff members may be a part of the company. The deployment and the security may also be internal as well as sub jobbed. Ask yourself after this course: ●
Where do I want to work?
●
In which of these areas do I have the skills necessary to be successful?
file:///D|/1/final/BBL0008.html [01.12.2007 04:47:36]
An Example of the 5 Phases
An Example of the 5 Phases The following is a look at a "real world" example (only parts of the phases are included): ●
Phase 1 Problem Analysis and Specification
●
Phase 2 Design
●
Phase 3 Implementation of the Design (Coding)
●
Phase 4 Testing, Execution and Debugging
●
Phase 5 Maintenance
Phase 1: Problem Analysis and Specification Make a small business accounting system for an accounting service that meets the following specifications: 1. Statement of the problem. 2. Sample Data and Print Outs ❍
Profit and Loss Statement
❍
Expense Ledger
❍
Sales Ledger
3. Program Conditions 4. Sample screens ❍
Main Menu
❍
Sales Menu
Case Study #1: A Single Entry General Ledger for Multiple Clients of an Accountant This program was encountered in the early 1980's. An accountant needed some accounting programs written. He had purchased a PC with 64 KB of RAM and a dual floppy 5 1/4" drives. In addition he had a dot-matrix printer. Prior to this project, the company's staff members were using this system to only do word processing. A franchised computerized accounting service had come to town. They were offering a service similar to what he provided for his clients. They were offering their services at a lower price than he was charging. Their service used the paid out records and the sales records to develop a monthly profit and loss statement. Their service did not include check writing or consultation on the status of the business or what future actions might improve the business performance. The accountant wanted to computerize his business so that he could compete with the computerized accounting service. He hoped that if he computerized, he could serve more clients in the same amount of time and thereby be able to lower his prices to that of the computerized accounting service. The accountant had surveyed the computer accounting field and could not find an accounting package which met his needs. His clients were small cash businesses. They had no accounts receivable, no accounts payable and no inventory control needs. He only used a simple single entry general ledger rather than a double entry general ledger for his clients. Most of the software packages he found were double entry ledgers and had far more features than were needed by his clients. Therefore, he wanted a single entry general ledger program created that was easy to use, would run on his computer, and would duplicate the forms he was currently using (sample forms are included on the next few pages.) He wanted to be able to have several different clients on each floppy. Because he did not want an extensive library and he wanted to be able to call up their past records using their client number. He had two different forms for different types of clients and he wanted two different programs to serve the two types of clients or one program that could be used for all of his customers. Profit or Loss Statement Name:_____________________________ DBA:______________________________ Street: ______________________________ file:///D|/1/final/BBL0009.html (1 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
City/State: ___________________________ Month of ________ Year: _______________ ============================================================== SALES
CURRENT MONTH
YEAR TO DATE
3.__________________ $______________ 4.__________________ $______________ 5.__________________ $______________ 6.__________________ $______________ 7.__________________ $______________ 1. TOTAL SALES
$________________
$________________
2. OTHER INCOME
$________________
$________________
1&2 GRAND TOTAL
$________________
$________________
$________________
$________________
$________________
$________________
=============================== PURCHASES\ Cost of Sales 8. __________________ $______________ 9. __________________ $______________ 10._________________ $______________ 11._________________ $______________ 12. TOTAL PURCHASES\ Cost of Sales =============================== GROSS PROFIT =============================== DEDUCT EXPENSES 13._________________________________
$________________
$________________
14._________________________________
$________________
$________________
15._________________________________
$________________
$________________
16._________________________________
$________________
$________________
17._________________________________
$________________
$________________
18._________________________________
$________________
$________________
19._________________________________
$________________
$________________
20._________________________________
$________________
$________________
21._________________________________
$________________
$________________
22._________________________________
$________________
$________________
23._________________________________
$________________
$________________
24._________________________________
$________________
$________________
25._________________________________
$________________
$________________
___________________________________
$________________
$________________
___________________________________
$________________
$________________
___________________________________
$________________
$________________
TOTAL EXPENSES ==================================
$________________
$________________
NET PROFIT
$________________
$________________
==================================
Expense Ledger Open table as spreadsheet Sam's Computer Store
Jill & John Pilgry
544 W. 5th St. Mayville, WI file:///D|/1/final/BBL0009.html (2 von 23) [01.12.2007 04:47:42]
Expenses
An Example of the 5 Phases
May-00 12
14
Check Amt
$
11,348.00
7-MayBill Wagner
15492 $
280.00
$
280.00
7-MayTom Jason
15493 $
350.00
$
350.00
10-MayRace Office Supply
15494 $
146.31
10-MayIRS
15495 $
1,146.81
10MayHowie's Service
15496 $
19.00
11MayThomas Electronics
15497 $
7,948.00
11-MayWPS
15498 $
450.00
11MayWisconsin Tele
15499 $
179.40
12-MayWNAM
15500 $
491.00
12-MaySun Inc.
15501 $
1,346.57
14-MayTom Jason
15502 $
350.00
$
350.00
14-MayBill Wagner
15503 $
280.00
$
280.00
14-MayPost Crescent
15504 $
752.76
14-MayBenic Computers
15505 $
6,349.00
17MayService Master
15506 $
192.00
17-MayPolice Ball
15507 $
45.00
18MayThomas Electronics
15508 $
4,689.00
19-MayWYTL/ WOSH
15509 $
540.00
19MayHomarc Inc
15510 $
795.00
21-MayTom Jason
15511 $
350.00
$
350.00
21-MayBill Wagner
15512 $
280.00
$
280.00
22MayHowie's Service
15513 $
45.00
23MayOshkosh Northwestern
15514 $
350.00
24-MayBenic Computers
15515 $
3,568.00
Date
Name
YTD Totals
Cost of Sales
13
Check #
$
file:///D|/1/final/BBL0009.html (3 von 23) [01.12.2007 04:47:42]
92,499.32
Office Sup. $
$
495.75
15
Wages
16 Rent
$
3,180.00
17
Telephone $
720.00
18
Utilities $
1,549.96
19
Advertizing $
7,990.60
$
$
$
7,157.80
$
1,146.81
$
258.75
$
450.00
22
23
Maintenance $
1,728.97
$
192.00
Misc Expenses $
1,556.38
$
45.00
19.00
179.40
$
491.00
$
752.76
1,346.57
6,349.00
4,689.00
$ $
540.00
795.00
$
$
$
$
Insurance
7,948.00
$
$
576.50
21
Taxes
146.31
$
$
20
Vehicle
3,568.00
350.00
45.00
An Example of the 5 Phases
24-MayINA
15516 $
175.00
25-MayWis. Public Service Corp
15517 $
374.32
26-MayUnited Fund
15518 $
150.00
26-MaySun Inc.
15519 $
592.56
27MayChamber Com. (Dues)
15520 $
230.00
28-MayTom Jason
15521 $
350.00
$
350.00
28-MayBill Wagner
15522 $
280.00
$
280.00
28MayHowie's Service
15523 $
37.50
28MayService Master
15524 $
211.00
31-MayWis. Dept. Revenue
15525 $
697.41
31-MayRace Office Supply
15526 $
28.56
●
MTD Totals
●
YTD Totals
$34,069.20
$ $
$
374.32
$
$
28.56
230.00
37.50
$
697.41
$
211.00
$
174.87
$
2,520.00
$
795.00
$
179.40
$
374.32
$
2,133.76
$
101.50
$
1,844.22
$
625.00
$
403.00
$
425.00
$
116,992.45
$
670.62
$
13,868.00
$
3,975.00
$
899.40
$
1,924.28
$
10,124.36
$
678.00
$
9,002.02
$
883.75
$
2,131.97
$
1,981.38
Jill & John Pilgry
Mayville, WI May-00
SALES 3
4
Computer
5
Software $
26,096.44
6
Books $
2,741.72
7
Peripherals $
23,937.48
8
Training $
750.56
Misc $
Daily Totals
Weekly Totals
28.00
Date 2-May
$
567.52
$
156.99
$
36.42
$
399.95
$
80.00
$
-
$
1,240.88
3-May
$
764.98
$
210.87
$
15.75
$
196.50
$
-
$
5.00
$
1,193.10
4-May
$
871.32
$
184.63
$
75.30
$
245.30
$
10.00
$
-
$
1,386.55
5-May
$
671.36
$
220.42
$
53.20
$
288.40
$
30.00
$
-
$
1,263.38
6-May
$
794.53
$
350.72
$
21.10
$
149.36
$
-
$
-
$
1,315.71
7-May
$
943.31
$
424.65
$
-
$
836.75
$
-
$
-
$
2,204.71
9-May
$
475.41
$
198.64
$
26.00
$
330.40
$
40.00
$
-
$
1,070.45
10-May
$
631.25
$
75.00
$
-
$
-
$
-
$
10.00
$
716.25
11-May
$
241.63
$
156.38
$
33.40
$
440.00
$
-
$
-
$
871.41
12-May
$
714.62
$
348.62
$
25.00
$
75.36
$
20.00
$
-
$
1,183.60
13-May
$
691.75
$
75.84
$
19.50
$
590.00
$
-
$
-
$
1,377.09
14-May
$
541.28
$
140.50
$
-
$
-
$
-
$
4.00
$
685.78
16-May
$
364.18
$
230.75
$
41.90
$
-
$
-
$
-
$
636.83
17-May
$
894.36
$
246.40
$
36.52
$
-
$
-
$
-
$
1,177.28
18-May
$
1,643.80
$
643.74
$
147.80
$
876.51
$
-
$
6.00
$
3,317.85
19-May
$
284.67
$
-
$
-
$
321.54
$
-
$
-
$
606.21
file:///D|/1/final/BBL0009.html (4 von 23) [01.12.2007 04:47:42]
$
24,493.13
Sam's Computer Store
78,329.68
150.00
$
544 W. 5th St.
$
$ 592.56
Sales Ledger Open table as spreadsheet
YTD Totals
175.00
$
8,604.33
$
5,904.58
An Example of the 5 Phases
20-May
$
591.84
$
280.30
$
17.50
$
543.41
$
30.00
$
-
$
1,463.05
21-May
$
756.31
$
150.30
$
42.30
$
678.95
$
20.00
$
4.00
$
1,651.86
23-May
$
594.51
$
250.90
$
56.75
$
136.50
$
-
$
-
$
1,038.66
24-May
$
964.35
$
442.53
$
31.42
$
-
$
-
$
2.00
$
1,440.30
25-May
$
736.49
$
211.34
$
25.97
$
71.00
$
-
$
3.00
$
1,047.80 5,009.25
26-May
$
3,497.86
$
1,468.39
$
43.00
$
-
$
-
$
-
$
27-May
$
284.69
$
-
$
15.00
$
245.00
$
-
$
-
$
544.69
28-May
$
1,384.76
$
546.97
$
13.00
$
-
$
-
$
-
$
1,944.73
30-May
$
796.58
$
231.42
$
-
$
438.41
$
40.00
$
-
$
1,506.41
31-May
$
384.60
$
119.75
$
30.00
$
120.70
$
10.00
$
-
$
========= ●
MTD Totals
$
21,087.96
========= $
========= ●
YTD Totals
$
99,417.64
7,366.05
========= $
========= $
33,462.49
806.83
========= $
========= $
3,548.55
6,984.04
========= $
========= $
30,921.52
280.00 =========
$
1,030.56
========= $
34.00
$
========= $
62.00
665.05 ========= 36,558.88 =========
$
Program Conditions The accountant requested that the program include the following features: 1. That all of the calculations should be carried out by his computer. 2. That the sums for each client should be stored to be used from month to month but that the program would have a way to modify these sums if it became necessary later. 3. That a column for percentages be added to the general ledger so that he could compare sales, purchases (cost of sales), and that the program would calculate each expense category as a percentage of gross sales for MTD and YTD. 4. That he would be able to enter in the expenses and sales into the program as he read from the client's checkbook and the cash register slips, he would be able to edit errors or delete records which were incorrect, he would be able to get a print out of the expenses and sales for MTD, and that these could be cleared after each month. (The monthly values would be cleared only on demand by him and not automatically done by the computer.) 5. That the computer would sort the expenses and sales into their respective categories and print their sums in the P&L statement. 6. That he could override the Total Sales and the Total Purchases if he wished. He claimed that this was necessary to adjust the monthly profit/ loss statements to reflect the "true business" when sales or purchases would require carrying over several months. 7. That all of his thirteen expense categories could be used and in addition four others could be entered for special clients. Further he wanted room for three expense categories to be listed in the remarks area which were not figured into the Total Expenses.
Program Main Menu The Main Menu of the program was to look like the following:
Sales Ledger The Sales Ledger menu was to look like the following: file:///D|/1/final/BBL0009.html (5 von 23) [01.12.2007 04:47:42]
168,442.76
$
8,853.08
$
11,025.43
$
2,171.46
An Example of the 5 Phases
Phase 2: Design The following steps were part of the Design Phase: 1. Abstract Data Types for Accounting 2. Human Interface for Accounting 3. Structure Chart for Accounting 4. Flow Chart for Accounting 5. Pseudo Code for Accounting The above examples of the design phase's documents are incomplete and are listed here to only give you a brief illustration of where you will be by the end of this course.
Abstract Data Types (ADT) for Accounting System 1. Company: What types of data are needed for Company? ❍
name - string
❍
owner - string
❍
address - string
❍
city - string
❍
state - string
❍
zip - string
What types of functions/methods are needed for Company? ❍
input name, owner, address, city, state and zip
❍
output company information
UML data type description:
Company -companyName:string -companyOwner:string -companyAddress :string -companyCity:string -companyState:string -companyZip:string
file:///D|/1/final/BBL0009.html (6 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
+inputName(name: string ) +inputOwner(owner: string ) +inputAddress(address: string ) +inputCity(city: string ) +inputState(state: string ) +inputZip(zip: string ) +outputCompanyInfo( )
2. Date: What types of data for Date? ❍
month - int
❍
day - int
❍
year - int
What types of functions/methods for Date? ❍
input month,
❍
input day
❍
input year
❍
output month
❍
output day
❍
output year
❍
output date
UML data type description:
Date -month:integer -day:integer -year:integer +inputMonth(theMonth: int ) +inputDay(theDay: int ) +inputYear(theYear: int) +outputMonth( ):integer +outputDay( ):integer +outputYear( ):integer +outputDate( )
3. Sales: What types of data for Sales? ❍
day - date
❍
daily_sales[5] - array of floats
file:///D|/1/final/BBL0009.html (7 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
What types of functions for Sales? ❍
input date (month, day and year)
❍
input sales
❍
modify sales
❍
output sales date
❍
output sales amount for a particular account
❍
output sales for the date
UML data type description:
Sales:Date -dailySales[5]:float +inputSalesAmounts(dayNumber: int, amount: float ) +modifySalesAmount(dayNumber: int, amount: float ) +showSalesAmount(number:integer):float +showSalesAmounts( )
The above listing is not a complete analysis, so ask yourself: What other ADTs would be needed?
Human Interface for Accounting The Design Phase as well as the Specification Phase should contain samples of the Human Interface. For example there should be samples of the menus. The menus of the system should look something like the following:
Main Menu 1. Start New Client 2. Expense Ledger Menu 3. Sales Ledger Menu 4. Profit and Loss Menu 5. End of Year Processing 6. Quit Which?
Sales Ledger Menu 1. Enter Daily Sales 2. Edit Daily Sales 3. Print Daily Sales 4. Process End of Month Sales 5. Return to Main Menu
file:///D|/1/final/BBL0009.html (8 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
Which?
Expense Ledger Menu 1. Enter Expense 2. Edit Expense 3. Print Expense Report 4. Process End of Month Expenses 5. Return to Main Menu Which?
In addition to the menus as shown above, there should also be samples of any additional input screens to provide the programmer with information about how they are to appear. For example input screens need to provide information as to how the sales and expenses would be entered and what the screens will look like when the user wants to edit the sales or the expenses. But not only should there be examples of the input screens, there needs to be examples of output screens as well. For example there needs to be examples of what each report will look like. The samples for both the input and the output will be similar to yet different from the samples created for the Specification Phase. The documents of the Specification Phase should be samples of what the user is currently viewing and how it will be different. The Design Phase samples should show the programmer how to represent the screens that the user will view in the finished program.
Structure Chart for Accounting As discussed previously, a program needs to be subdivided into pieces that are called modules. Subdividing the program in this way provides a better design, one which is easier to manage and in general one that is less expensive to create and to maintain. The structure chart of the accounting program should look similar to the following:
Notice at the top of this structure chart is the main module called accounting. This module is then subdivided into the several additional modules that appeared in the main menu seen previously to include the options: Start Client, Sales Ledger, Expense Ledger, Profit and Loss and End of Year Processing. The Sales Ledger and the Expense Ledger menus each had several options. For example in the Sales Ledger menu, there were Enter Sales, Edit Sales, Print Sales and Process End of Month options. Notice in this structure chart that each of these options has a module that is to carry out these objectives. What this sample of a structure chart does not show is the movement of data between the different modules. The reason for this is that this program was created in the early 80's and the movement of data was not directly between the different modules but instead the data was handled globally. Later in the notes will be samples of structure charts that show how to handle the movement of data directly between modules rather than moving data globally.
Flow Chart for Accounting The Design Phase should provide documentation that shows the programmer the logic of the program and the names of the modules as well as file:///D|/1/final/BBL0009.html (9 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
the names of the data that are to be used in the program. There are several different tools that can be used to do this. One tool is a flowchart and another is pseudo code. A flowchart is a graphic representation of this logic. It shows the program flow. The following is a flowchart for the Accounting module and it shows the logic of the main menu. Notice as the program begins, the user decides which process to select and depending on the choice will go to one of the modules for that menu option. After each module is completed, the program flow returns to the main menu.
This flowchart is not a complete flowchart of the total system and its individual parts/modules. The final documentation should contain a separate flowchart for each module.
Pseudo Code for Accounting The Design Phase should contain documents that represent the logic of the program. This can be done with a flowchart or with pseudo code. The pseudo code is "false" code. That is, it does not show exactly the instructions in a particular language. In fact pseudo code should be written so that it could be used in one of several different languages depending on what language is available for the program. What the pseudo code should do is to show the logic of the program but do it in words rather than graphically as is done with a flowchart. This example could represent the pseudo code of the accounting program: Accounting do Display the Main Menu Choices 1. Start New Client 2. Expense Ledger Menu 3. Sales Ledger Menu 4. Profit and Loss Menu 5. End of Year Processing 6. Quit Request and Receive Choice Case: 1: Process strt_clnt 2: Process expens_ldgr 3: Process sales_ldgr 4: Process pandl 5: Process eoy 6: End Program EndCase file:///D|/1/final/BBL0009.html (10 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
dowhile(continue) End strt_clnt ..... Return expens_ldge ..... Return sales_ldgr .... Return pandl ...... Return
Notice that the main module processes or calls each of the sub modules depending on the user's choice. When creating pseudo code, each module has its own separate part of the total. When each module completes its instructions, the program will return to the calling module. That is the reason for the word Return in each of the sub modules of the pseudo code. In this example, the dots above represent statements that are being left out. The real pseudo code would provide these statements.
Phase 3: Implementation of the Design (Coding Phase) The Coding Phase converts the documents of the previous phases into the instructions of a particular version of a particular language. In this course we will look at using the version of C# in Visual Studio .NET 2005. Note: The original accounting program was written in the early 80's in BASIC before C# was invented. The coding listed here is actually a maintenance of the original program that has been rewritten in C++. Link to each of the following to get a general feel of how the design would be converted to C++. ●
Header file: accounting.h
●
Program file: accounting.cpp
This implementation of the program is in two pieces one of which is called a header file and the other is called a program file. A later lecture will discuss how to combine these two files into a program using the Visual Studio .NET C# CASE tools. // // // // // // // // // // //
This is the header: accounting.h This header is required for the program accounting.cpp It does not include all of the class information required by the program.
Some of the classes that are needed in this program.
class company { private: string companyName, companyOwner, companyAddress, companyCity, companyState, companyZip; public: void inputName() { cout > companyName; file:///D|/1/final/BBL0009.html (11 von 23) [01.12.2007 04:47:42]
An Example of the 5 Phases
cout > companyCity; cout /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> file:///D|/1/final/BBL0025.html (2 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.theAmount = new System.Windows.Forms.TextBox(); this.theBalance = new System.Windows.Forms.TextBox(); this.thePayment = new System.Windows.Forms.Button(); this.theCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(50, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(185, 23); this.label1.TabIndex = 0; this.label1.Text = "Accounts Receivable"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(44, 84); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 23); this.label2.TabIndex = 1; this.label2.Text = "Amount"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(44, 125); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(77, 23); this.label3.TabIndex = 2; this.label3.Text = "Balance"; // // theAmount // this.theAmount.Location = new System.Drawing.Point(167, 84); this.theAmount.Name = "theAmount"; this.theAmount.Size = new System.Drawing.Size(100, 22); this.theAmount.TabIndex = 1; // // theBalance // this.theBalance.Location = new System.Drawing.Point(167, 125); this.theBalance.Name = "theBalance"; this.theBalance.ReadOnly = true; this.theBalance.Size = new System.Drawing.Size(100, 22); this.theBalance.TabIndex = 4; this.theBalance.TabStop = false; // // thePayment // this.thePayment.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.thePayment.Location = new System.Drawing.Point(46, 205); this.thePayment.Name = "thePayment"; this.thePayment.Size = new System.Drawing.Size(97, 34); this.thePayment.TabIndex = 2; this.thePayment.Text = "Payment"; this.thePayment.UseVisualStyleBackColor = true; this.thePayment.Click += new System.EventHandler(this.thePayment_Click); // file:///D|/1/final/BBL0025.html (3 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// theCharge // this.theCharge.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.theCharge.Location = new System.Drawing.Point(179, 205); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(88, 34); this.theCharge.TabIndex = 3; this.theCharge.Text = "Charge"; this.theCharge.UseVisualStyleBackColor = true; this.theCharge.Click += new System.EventHandler(this.theCharge_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.theCharge); this.Controls.Add(this.thePayment); this.Controls.Add(this.theBalance); this.Controls.Add(this.theAmount); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox theAmount; private System.Windows.Forms.TextBox theBalance; private System.Windows.Forms.Button thePayment; private System.Windows.Forms.Button theCharge; } }
// program_id Form1.cs // written_by don voils // date_written 4/2/2006 // description This file is part of a program which simulates a Windows accounts // receivable program. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace accountsReceivable { public partial class Form1 : Form { public Form1() { InitializeComponent(); theAmount.Text = " "; theBalance.Text = "0.00"; } private void thePayment_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance -= amount; theBalance.Text = String.Format("{0:n}", balance);
file:///D|/1/final/BBL0025.html (4 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theAmount.Text = ""; } private void theCharge_Click(object sender, EventArgs e) { decimal amount = Convert.ToDecimal(theAmount.Text); decimal balance = Convert.ToDecimal(theBalance.Text); balance += amount; theBalance.Text = String.Format("{0:n}", balance); theAmount.Text = ""; } } }
// program_id Program1.cs // written_by don voils // date_written 4/2/2006 // description This file is part of a program which simulates a Windows accounts // receivable program. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsReceivable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
//program_id booleanOperators.cs //written_by don voils //date_written 6/28/2006 //description This program demonstrates some of the uses of // the boolean operators: &, | and ^. // using System; namespace Conversion { class theProgram { static void Main() { bool a = true; bool b = true; Console.WriteLine("a = {0}, b = {1}, a&b = {2}\n", a, b, a & b); Console.WriteLine("a = {0}, b = {1}, a|b = {2}\n", a, b, a | b); Console.WriteLine("a = {0}, b = {1}, a^b = {2}\n\n", a, b, a ^ b); } } }
// program_id color1.cs // written?_by don voils // date_written 7/9/2006 // description This program demonstrates how // use colors in Console output. file:///D|/1/final/BBL0025.html (5 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// using System; class theProgram { static void Main() { int a = 5; int b = a; Console.Title = "This is a test of Console colors"; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine("a stored {0} and b stored {1}\n", a, b); Console.ReadKey(); } }
//program_id Conversion.cs //written_by don voils //date_written 1/28/2006 //description This program demonstrates some of the uses of // the methods of the class System.Convert. // using System; namespace Conversion { class theProgram { static void Main() { int theInt = Convert.ToInt32("32",10); Console.WriteLine("In example 1 theInt = {0} when converted from the string " + "\"32\".\n",theInt); theInt = Convert.ToInt16("32",16); Console.WriteLine("In example 2 theInt = {0} when converted from 32 base 16.\n", theInt); theInt = Convert.ToInt16("10101",2); Console.WriteLine("In example 3 theInt = {0} when converted from 10101 base 2.\n", theInt); decimal theDecimal = Convert.ToDecimal(23.45); Console.WriteLine("In example 4 theDecimal = {0} when converted from the " + "double 23.45.\n",theDecimal); theDecimal = Convert.ToDecimal("45.67"); Console.WriteLine("In example 5 theDecimal = {0} when converted from the string " + "\"45.67\".\n",theDecimal); string theString = Convert.ToString(34,2); Console.WriteLine("In example 6 theString = {0} when converted from the int 234 to " + "base 2.",theString); Console.WriteLine("\n\n"); } } }
// program_id datetime1.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. //
file:///D|/1/final/BBL0025.html (6 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
using System; class theProgram { static void Main() { DateTime theDate = new DateTime(2005,12,27); Console.WriteLine("This program was written on:\n{0} {1}\n" + "which was the {2} day of the year {3}", theDate.DayOfWeek,theDate.Date, theDate.DayOfYear,theDate.Year); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime2.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. // using System; class theProgram { static void Main() { int month; int day; int year; Console.Write("What is the month of the invoice? "); month = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the day of the month of the invoice? "); day = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the year of the invoice? "); year = Int32.Parse(Console.ReadLine()); DateTime theDate = new DateTime(year,month,day); Console.WriteLine("\n\nThe invoice was issued on: {0}", theDate.ToLongDateString()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime3.cs // written_by don voils // date_written 12/27/2006 // description This program demonstrates some of the // properties of the class: DateTime. // // Run this program several times to see // what effect this will have on the number // of ticks. // using System; class theProgram { static void Main() { DateTime theDate = new DateTime(); file:///D|/1/final/BBL0025.html (7 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
theDate = DateTime.Now; Console.WriteLine("\n\nThe invoice was issued on: {0}",theDate.ToShortDateString()); Console.WriteLine("and the number of ticks today were: {0:n0}",theDate.Ticks); theDate = DateTime.Today; Console.WriteLine("\n\nor was the invoice issued on: {0}",theDate.ToLongDateString()); Console.WriteLine("and the number of ticks up to today were: {0:n0}",theDate.Ticks); DateTime newDate = new DateTime(2005,12,27,14,31,0); Console.WriteLine("\n\nThis program was written on: {0}",newDate.ToString()); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id datetime4.cs // written_by don voils // date_written 8/5/2006 // description This program demonstrates some of the // formatting properties for the class DateTime. // using System; class theProgram { static void Main() { DateTime theDay = DateTime.Now; Console.WriteLine(theDay.ToString()); Console.WriteLine(theDay.ToString("\n\ndddd MMMM dd, yyyy g")); Console.WriteLine("\n\n{0:MM/dd/yy hh:mm tt}",theDay); Console.WriteLine("\n\n{0:hh:mm:ss tt G\\M zz}",theDay); Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id DefiniteAssignmentRule.cs // written_by don voils // date_written 5/6/2006 // description This program demonstrates the Definite Assinment Rule. // It will not compile because an defined variable is // being used prior to assigning it a value. // using System; using System.Collections.Generic; using System.Text; namespace testingCsharp { class Program { static void Main(string[] args) { // The following lines will not compile. // int theNumber; Console.WriteLine(theNumber); // If the following statements were uncommented // and the statements above were commented out // the program would compile. // //int theNumber = 0; //Console.WriteLine(theNumber); }
file:///D|/1/final/BBL0025.html (8 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
} }
// program_id dowhile.cs // written?_by don voils // date_written 12/12/2006 // description This program demonstrates how to // use the do/while loop. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double totalPayroll = 0; // This char used to control the loop // char toContinue = 'y';
// this int keeps track of the number of employees // int numberEmployees = 0; // Receives and adds the value of each emplyee's payroll // until the user requests to stop.. // do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); totalPayroll += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); // Clears the screen. // Console.Clear();
// Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",totalPayroll); // Improves the vertical spacing. Console.WriteLine("\n\n"); Console.ReadKey(); } }
// program_id enum1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use enumerated data types: file:///D|/1/final/BBL0025.html (9 von 35) [01.12.2007 04:48:02]
Lecture 2 Examples
// i) with type conversion // ii) with relational operators // iii) with arithmetic operators // iv) with a for() loop and a switch. // v) In addition it shows // that an enumerated data type may be // used as an argument and as an output // data type. // using System;
class theProgram { enum Colors:int { BLACK, RED, YELLOW, GREEN, BLUE } static void Main() { string theColor; Colors yourCar = Colors.YELLOW; theColor = yourCar.ToString(); Console.WriteLine("The color of your car is {0}",theColor); int theNumber = (int)yourCar; Console.WriteLine("\nThe number of your car is {0}",theNumber); Colors hisCar = Colors.GREEN; if(yourCar < hisCar) Console.WriteLine("\nYour car's color is less than his car's color.\n"); else Console.WriteLine("\nHis car's color is less than your car's color.\n"); Colors myCar; // Notice that type casting is not required in the control // statement // for(myCar = Colors.BLACK ;myCar b?a:b); } static long MAX(long a, long b) { return (a>b?a:b); } static float MAX(float a, float b) { return (a>b?a:b); } static double MAX(double a, double b) { return (a>b?a:b); }
are methods that overload the name MAX. See overload.cs The C# compiler will not return a compiler error when the definitions for the above methods MAX are compiled in the same program since the signatures are all different. Overloading may help the programmer who wants a method to operate on new arguments. Rather than rewriting all previous code to include the new argument, the programmer only needs to overload the name with a new definition. The compiler will then determine from context which name to use. What overloading has done is to reduce the complexity of programming by reducing the number of different method names for the programmer has to remember. Q: When should methods be overloaded? A: When there exists a group of methods with similar results but different signatures. However, the real answer to this question will only come with experience. There will be times in which another technique may be a better choice.
file:///D|/1/final/BBL0029.html (2 von 2) [01.12.2007 04:48:06]
Text File Output
Text File Output Now that the lectures have considered keyboard input and screen output, it is time to consider text file input and output. This can be done using the console or using the Windows GUI environment. Only the console approach will be considered in this part of the lecture. Suppose that a program was to store the customer ID, the name of a customer and the balance due. Suppose that some of the data was to include: 1, George Washington, $1.25. Each of the symbols in this data would be a character. Each of the items: customer ID, first name, last name and balance due would be what are called a field. All of the information about each customer would be called a record. Lastly the data would all be stored into a file in persistent storage. For example the data to be stored could be that which is included in the following table:
Open table as spreadsheet Field 1 Customer ID
Field 2 First Name
Field 3 Last Name
Field 4 Balance Due $1.25
Record 1
1
George
Washington
Record 2
93
Thomas
Doolittle
$32.33
Record 3
134
Jon
Le Moire
$421.33
Record 4
245
Juan
Sanchez
$532.64
Record 5
356
Heinrich
Schmitz
$1,343.23
Record 6
567
Wen
Wu
$4,632.33
Text File Output Classes The classes needed for file I/O are in the namespace: System.IO and therefore each program that will handle file I/ O must contain the following: using System.IO;
Inside of the program's class definition, the text file could be named with a statement like the following: static string fileName = @"C:\temp\datafile.txt";
Note: The @ reduces the need for special characters in strings. The file may be located in any storage location including the temp folder on the C: drive as indicated in the above statement. The text file: datafile.txt is the storage file that will contain the data (there is nothing about this particular name or extension that is required).
file:///D|/1/final/BBL0030.html (1 von 5) [01.12.2007 04:48:07]
Text File Output
Another statement that is needed is one like the following: static FileStream writeFileStream;
This statement defines a reference writeFileStream (this could be any name) to an object of the class FileStream that permits output of data. The class FileStream deals with the access to the environment outside of the program. A statement like the following should also be included in the code: static StreamWriter fileWriter;
The statement above defines a reference fileWriter (this could be any name) to an object of the class StreamWriter that is required for file output of text data. The class StreamWriter handles the data within the program before sending it out. The conditionals below are required to close the objects if they are already open to avoid an exception and thereby a crashing of the program. if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close();
These objects for the classes FileStream and StreamWriter will need to be instantiated with statements similar to the following: writeFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream);
These two statements instantiate the objects referred to by writeFileSream and fileWriter respectively. They are calling constructors for these respective classes. These objects will now provide for the connecting of the program to the data file represented by fileName.
FileMode and FileAccess The FileStream() constructor has several forms with different options to regulate how the file is accessed. FileMode is an enumerated data type whose enumerators regulate how the file will access the data. The FileMode enumerators are: Append, CreateNew, Create, Open, OpenCreate and Truncate
Be careful about using OpenCreate because if the file already exists, the data that is to be written to the file will be placed at the start of the current file data and the data that is there will be ignored and overwritten. FileAccess is also an enumerated data type whose enumerators are:
file:///D|/1/final/BBL0030.html (2 von 5) [01.12.2007 04:48:07]
Text File Output
Read, Write and ReadWrite
WriteLine() for File Output In the code where theData is used for output, there should be a line like the following: fileWriter.WriteLine(theData);
This line of code will send what ever is stored in theData variable to the file buffer associated with fileWriter and from there to the file. Notice the use of the method WriteLine() above. This is similar to the WriteLine() used with the class: Console. The major difference is that the WriteLine() for Console is a static method while the method WriteLine() for StreamWriter is a non-static method and it must therefore be dotted with an object like fileWriter.
Clearing Output Buffers After all of the data for a record has been written to the output buffer fileWriter, the buffer should be cleared to ensure that the data has all been written to the data file. This can be done by using the StreamWriter method Flush () as in the following statement: fileWriter.Flush();
But if the program is no longer going to use fileWriter and the associated file, then the following statement would achieve this same goal: fileWriter.Close();
For an example of output to a text file, view the following: writeToTextFiles.cs. The program: writeToTextFiles.cs implements the customer data specifications listed in the table above. Create a C# Console project. Paste this sample program file into this Visual Studio .NET 2005 project, compile and run the program. After you have stored the records to the disk, open the file: datafile.txt in NotePad and examine its contents. Note: The C: drive was not used in this program. The program will store the data to the drive and folder where the project is located. Open up Windows Explorer and view the location of the data file.) In what folder is the data file located? In C++ it would be in the folder where the source file is located. In the C# program, the data file is located in the folder where the executable file is located, i.e. in the bin\Debug subfolder of the program's folder.
Appending Data to the End of the File If you ran this program more than once, each time the program was run the previous data would be overwritten. To avoid this, the program could have the FileMode enumerator be Append rather than OpenCreate. Modify this program by changing the FileMode to Append. Compile and run it several times. After you have run the program several times, examine the contents of the text file to notice that the data was appended one record after another for each of the program runs.
Checking File Existence The program above provided the name of the file to be processed in the code. However, suppose that the name of the file needs to come from the keyboard or somewhere else in the code. The question would then arise as to
file:///D|/1/final/BBL0030.html (3 von 5) [01.12.2007 04:48:07]
Text File Output
whether the file existed. If the file's name was stored into the string variable: fileName from the keyboard or somewhere else in the program, then the following would test whether the file existed or not by using the static method Exists() of the class: File. This method returns true if the file argument is accessible and false otherwise. For example the keyboard entry into the string fileName could be tested with this method as in the following: if(File.Exists(fileName)) { /// processes this code if the file exists. }
Note: The class File as well as other classes used for working with file I/O will be discussed in more detail in a later lecture.
Keyboard Enter of Output File Name The following code modifies the program above to permit the user to enter the file name. Notice that the user would enter the name and then the program would add the extension: ".txt" so that the user would not need to know the extension and therefore would not need to type it in. static string fileName; // additional code goes here //...... // char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(File.Exists(fileName)) { Console.WriteLine("\nThat file already exists."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now " + "end. \n\nContinue? "); Console.ReadLine(); } else { ..... }
file:///D|/1/final/BBL0030.html (4 von 5) [01.12.2007 04:48:07]
Text File Output
Notice that if the file already exists then the program will either end or permit the user to enter in a name that does not already exist. See testingwriteToTextfiles.cs
file:///D|/1/final/BBL0030.html (5 von 5) [01.12.2007 04:48:07]
Text File Input
Text File Input File Input Classes To read the text data in from storage, the code of the program is similar to that used for writing to the data file. The major difference is that instead of using an object of the class StreamWriter, an object of the class StreamReader is used instead. The following three sections of code for reading data are similar to the three sections of code in the previous part of the lecture where output was discussed. For example the following would define the objects needed for input in this program: static string fileName = @"c:\temp\datafile.txt"; static FileStream readFileStream; static StreamReader fileReader;
and in addition the following statements are needed to check to see if the objects have been instantiated: if(readFileStream!=null) readFileStream.Close(); if( fileReader!=null) fileReader.Close();
The objects for the classes FileStream and StreamReader need to be instantiated with statements similar to the following: readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream);
ReadLine() for File Input To bring the text data in from the file, a statement like the following method call is needed. fileReader.ReadLine(theData);
Notice the use of method: ReadLine() above. As with WriteLine(), this ReadLine() is a non-static method of the class StreamReader and therefore it must be dotted with the object: fileReader.
Loop to Input Data The program must determine whether all of the data in the text file has been read. To do this a while() loop could be coded to determine whether there is more data to read or not. A statement like the following could be used to determine when the end of the data is reached. The ..... below indicates that there is additional code. while(theData != null) { ..... } file:///D|/1/final/BBL0031.html (1 von 3) [01.12.2007 04:48:08]
Text File Input
For an example of input of the same text file: datafile.txt, view the following: readFromTextFiles.cs. Open this file and paste it into the same console project that was used with writeToTextFiles.cs and then compile and run the program as you did in that example. Notice how the program reads in the data that was stored into the file: datafile. txt on the drive where the program writeToTextFiles.cs stored it as discussed above. (An alternate approach would be to use an entirely new console project and to copy the datafile.txt to the folder for the new project.)
Variable File Names The program above provided the name of the file to be processed in the code. However, suppose that the name of the file needs to come from the keyboard or somewhere else in the code. The question would then arise as to whether the file existed. If the file's name was stored into the string variable: fileName from the keyboard or somewhere else in the program, then the following would test whether the file existed or not by using the static method Exists() of the class: File. This method returns true if the file argument is accessible and false otherwise. For example the keyboard entry into the string fileName could be tested with this method as in the following: if(File.Exists(fileName)) { /// processes this code if the file exists. }
Note: The class File as well as other classes used for working with file I/O will be discussed in more detail in a later lecture. The following code modifies the program above to permit the user to enter the file name. Notice that the user would enter the name and then the program would add the extension: ".txt" so that the user would not need to know the extension and therefore would not need to type it in. static string fileName; // additional code goes here //...... // char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(!File.Exists(fileName)) { Console.WriteLine("\nThat file does not exist."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) {
file:///D|/1/final/BBL0031.html (2 von 3) [01.12.2007 04:48:08]
Text File Input
Console.WriteLine( "\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { // // continue with the file processing. // }
Observe the above code at the top of the program: testingInFileName.cs. Copy this file to the same project that you did for the program: readFromTextFiles.cs that you used above. When the program: testingInFilename.exe begins, enter different file names. For example use: testing and datafile. Notice that when testing is entered, the program catches the problem and permits reenter of the correct name: datafile. When datafile is entered, the program operates correctly. In addition if the user wished to terminate the program, this is also permitted.
file:///D|/1/final/BBL0031.html (3 von 3) [01.12.2007 04:48:08]
Windows Forms and Text File I/O
Windows Forms and Text File I/O Windows Forms and Text File Output Specifications: Suppose that you were requested to write an accounts payable program that would receive data entered from the keyboard and store it to a text file using the C# GUI interface. Suppose further that the data to be entered is: company name and amount due. The GUI should include a button labeled: Post that would append the data to the file: accountsPayable.txt. The form should look like the following:
where the top two blanks are the text boxes and the bottom one is a button. The following is some sample data (however the dollar signs and the commas should not be entered into the program since this would be character data rather than numeric data):
Company Name Amount Due
The Big One
Another One
Again One
Still More
$10,000.00
$1,422.33
$23,320.21
$235.34
Design: Form1 Set companyName = "" Set amountDue = "0.00" Open for writing to the data file End Posting Open file accountsPayable.txt Write companyName to file Write amountDue to file Set companyName = ""; Set amountDue = "0.00"; End
Coding: To begin, create a Windows form using the project name: accountsPayable. Click on the form and using the Properties change the Text of the form to Accounts Payable. From the Toolbox drag two labels, two textboxes and a button to the form. ●
properties of the labels
file:///D|/1/final/BBL0032.html (1 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
●
●
❍
label 1 properties: Font: Bold, Text: Company Name Location: 12, 43, Size: 120, 17
❍
label 2 properties: font: Bold, text: Amount Due, location: 12, 96, size: 96, 17
properties of the textboxes ❍
textbox 1 properties: font: Bold, name: companyName, location: 138, 43, size: 142, 22, TabIndex: 1
❍
textbox 2 properties: font: Bold, name: amountDue, location: 138, 96, size: 142, 22 , TabIndex: 2
properties of button ❍
button 1 properties: font: Bold, text: Post, name: postPayables, location: 12, 171, size: 75, 23, TabIndex: 3 When you have made the above modifications, the form should look like the following:
To complete the coding, click on the form and select: View Code. Place the following at the top of Form1.cs with the other using statements: using System.IO;
In the class: Form1 define the following data members: static string fileName = @"accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter;
By making the above as static data members, they will be accessible inside of any of the Form1 methods without the need to define an object of the class Form1 nor will it be necessary to dot it with the name of the class when they are used. In the Form1() constructor do the following:
file:///D|/1/final/BBL0032.html (2 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); }
Next double click the Post button and change its event handler to the following: private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text); fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); }
As indicated previously when text file I/O was discussed, the first two statements would write out the data from the textboxes to the text file: accountsPayable.txt. The third statement would flush out the output buffer to send the data to the file. The fourth and fifth statement would clear the data in the textboxes and the sixth statement would return the cursor to the text box: companyName. Note: While the program is running, use a mouse to attempt to change the size of the form. Was it possible? Would this be a good idea to have the form resizable? In this particular program, allowing the user to resize the form is not a good idea. To prevent this from happening, set the Maximum Size and the Minimum Size to the same values as the Size for Form1. To see the program link to: Form1.cs, Form1.Designer.cs and its corresponding Program.cs. To use these three files, create a Windows project: accountsPayable. Copy each of these three files into their corresponding files in the project. Compile and run the program. After you have run the program on several records, observe the data file and its contents. Close and run the program again. Open the data file once again and notice that the data from the second run is appended to the data in the file.
Programming C# Windows Program to Output Data for Excel If the fields had commas between them and the output data file had an extension of .csv, then the file could be imported into Excel. To see how this could be done, modify the Form1.cs above to contain the following: public partial class Form1 : Form { static string fileName = @"accountsPayable.csv"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName,
file:///D|/1/final/BBL0032.html (3 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.Write(companyName.Text); fileWriter.Write(","); fileWriter.WriteLine(amountDue.Text); fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } }
Run at least ten companies through the program modification above. Then download APTotals.xls and open it into Excel. When the file is opened, it should appear similar to the following:
Notice that in the file APtotals.xls, there is text: Total AP in A20 and in B20 is the Sum of B1–B19. Further the cells B1–B20 are formatted into US currency. Click on the cell: A1. Next, click on Data on the menu bar. Follow this by clicking on: Import External Data and then on Import Data. Making these selections, Excel should appear as in the following graphic:
file:///D|/1/final/BBL0032.html (4 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Using these selections, open the file: accountsPayable.csv. The following dialog should then appear:
Click on the Next button and the following dialog should appear:
file:///D|/1/final/BBL0032.html (5 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
In the Delimiters uncheck Tab and check Comma. Next click the Finish button at the bottom. A dialog like the following should appear (Notice that the data will be placed beginning at A1):
Now click the OK button and in the spreadsheet should appear data like the following:
file:///D|/1/final/BBL0032.html (6 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Notice how the data appears formatted as would be needed. A C# student: Geoff asked how a C# Windows program could be used to interact with Excel. The example above illustrates his request. Note: It is also possible to create an Excel spreadsheet populated with data and to import the data into a C# program. This topic will be discussed later in the lectures.
Windows Forms and Text File Input Specifications: Suppose that you were requested to create a Windows GUI program that can read the data created by the program above one record at a time and display the data read into textboxes. In addition the program should total the account payable amount as it is read. The total accounts payable amounts should then be posted to the Total AP Due text box. The form should look like the following where the top three are text boxes and the bottom is a button:
file:///D|/1/final/BBL0032.html (7 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
Design: The following is the pseudo code for the program Form Set companyName = "" Set amountDue = "0.00" Set totalAPDue = "0.00" Open File Set totalDue = 0.00 End Next IF(file not at end of file)THEN { Read from file into companyName; Read from file into theAmount totalDue += theAmount; Set amountDue = String.Format(theAmount); Set totalAPDue = String.Format(totalDue); } ELSE Display "There is no more data to read." ENDIF End
Coding: To begin, create a Window's project using the project name: viewAccountsPayable. Click on the form and using the Properties change the Text of the form to View Accounts Payable. Set the Maximum Size and the Minimum Size to the same values as the Size. From the Toolbox drag three labels, three textboxes and a button to the form. Change their properties to the following: ●
●
properties of the labels ❍
label 1 properties: Font: Bold, Text: Company Name Location: 40, 27, Size: 120, 17
❍
label 2 properties: font: Bold, text: Amount Due, location: 43, 70 ,size: 96, 17
❍
label3 properties font: Bold, text: Total Amount Due: location: 43, 120, size: 104, 17
properties of the textboxes
file:///D|/1/final/BBL0032.html (8 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O ❍
textbox 1 properties: font: Bold, name: companyName, location: 174, 27, size: 100, 22, ReadOnly: True
❍
textbox 2 properties: font: Bold, name: amountDue, location: 174, 70, size: 100, 22, ReadOnly: True
❍
●
textbox 3 properties: font: Bold, name: totalAmountDue, location: 174, 120, size: 100, 22, ReadOnly: True
properties of button ❍
button 1 properties: font: Bold, text: Next, name: viewPayables, location: 12, 171, size: 75, 23, TabIndex: 1
After completing the above steps, the form should look like the following:
Add the following to the top of Form1.cs: using System.IO;
Add the following definitions to the class: Form1: static string fileName = @"accountsPayable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalDue;
Modify the Form1 constructor to the following: public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = String.Format("{0:c}", 0.00); totalAPDue.Text = String.Format("{0:c}", 0.00); readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream); file:///D|/1/final/BBL0032.html (9 von 10) [01.12.2007 04:48:09]
Windows Forms and Text File I/O
totalDue = 0.00; }
The purpose of the second, third and fourth statements above are to initialize the three textboxes. The next two lines make a connection to the file for the purpose of reading in the data. The last line sets the variable: totalDue to 0.00 for the purpose of adding the values as they are read in. Next double click on the button: Next and change its event handler to the following: private void nextAP_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { companyName.Text = fileReader.ReadLine(); double theAmount = double.Parse(fileReader.ReadLine()); totalDue += theAmount; amountDue.Text = String.Format("{0:c}", theAmount); totalAPDue.Text = String.Format("{0:c}", totalDue); } else MessageBox.Show("There is no more data to read."); }
Notice the use of the StreamReader data member: EndOfStream to control access to fileReader.ReadLine(). The Console program viewed above used a while() loop and theData != Null to stop data entry. However that approach would not work here. Notice that a selection is set up to determine if all of the data in the file has been read. Inside of the then part of the selection are five statements to implement the reading of the data, the adding up of the amounts due and the displaying the dollar amounts of the amount due the current record and the total amount due. The else part of the selection contains a call to a MessageBox to inform the user when all of the data has been read. (More will be discussed about the MessageBox later in the lectures.) To complete the implementation and to test the program the data file: accountsPayable.txt that was created in the program: accountsPayable.cs needs to be copied to the bin\Debug folder of the current project. To View the code see: Form1.cs, Form1.Designer.cs and Program.cs. Comment: Above it was discussed how to output to a file that could then be used by Excel. It is also possible to create a file in Excel, save it as comma separated data: i.e. a .csv file and then using a C# Windows program input the data into a program like the one above. To do this would require the separation of the data into two strings: one for the company name and one for the amount owed. This would require the use of a string method to find the comma and then to separate the data into the company name up to the comma and the amount owed after the comma. This topic will be discussed later when strings and string builders are discussed. Note: One of the important issues that has not been considered in the discussion of Windows programs so far has been what happens if the user does not enter a value in a field. Or what if the value to be entered into a textbox is to be a numeric value and the user enters characters instead. This topic will be discussed later in a lecture on data validation.
file:///D|/1/final/BBL0032.html (10 von 10) [01.12.2007 04:48:09]
UML Charts and Class Diagram for Structures
UML Charts and Class Diagram for Structures Example 1: In a previous lecture it was demonstrated how to use Visio to create a UML chart of an enumerated data type and how to use the Visual Studio .NET 2005 IDE to not only create an enumerated data type in the program but to also create a graphic that would depict the enumerated data type. In this example it will be demonstrated how to use Visio and the Visual Studio .NET 2005 IDE to create the code for the structure Customer and how to create a graphic of the structure as well. The structure Customer is defined in the following code: public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public string getName() { return name; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public decimal getOwes() { return owes; } }
Open Visio to create UML charts. Select the Class icon and drag it onto the graphic. Double click the Class icon. Change the Name: to Customer and change and the Stereotype: option to struct which should appear as in the following:
file:///D|/1/final/BBL0033.html (1 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Next click the OK button and the UML chart should now appear like the following:
The next step is to add the fields and the methods to the UML chart. Begin by double clicking the graphic and the following appears:
Notice that in Visio the fields are called: Attributes and the methods are called: Operations. First click on the Attributes from the Categories options. What should appear should be like the following:
file:///D|/1/final/BBL0033.html (2 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Click in the Attribute column and add each of the field names, their data type and their visibility as private (i.e. a will appear in the UML chart) as indicated in the example code above. After making these changes, click the OK button. What should appear would be like the following:
The next step is to enter the structure's methods. Again double click the structure icon and then select Operations from the Categories: options. What you should see will be like the following:
file:///D|/1/final/BBL0033.html (3 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Clicking in the Operation column, enter the name of each method and in the Return Type column enter the method's return type. What you should see is something like the following:
The next step is to enter the signature of setName(). To do this, click on the Properties button on the right side. Something like the following will appear:
Clicking in the Parameter column enter aName and click into the Type column and enter C#::string. After the signature for setName() is entered, do the same for setOwes(). Clicking the OK button the UML chart should look like the following:
file:///D|/1/final/BBL0033.html (4 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Begin by creating a console project called: AccountsReceivable. As soon as the project opens, click on Project on the menu bar. When you do, what appears should be like the following:
Next click on the option: Add New Item. When the Add New Item options appear, select Class Diagram.
file:///D|/1/final/BBL0033.html (5 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Next should appear the following and when it does select Struct by draging the icon onto the Class Diagram form:
When the New Struct form appears enter Customer as the name. Rather than creating an new file, the structure will be placed into the file: Program.cs by clicking the Add to existing file option and then typing in the name of file:///D|/1/final/BBL0033.html (6 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
the file: Program.cs.(In a Windows program you might place the structure's code into Form1.cs) Follow this by clicking the OK button.
An icon like the following should now appear on the screen:
The structure is to have the following fields: private string name; private decimal owes;
and the following methods: public void setName(string aName) { name = aName; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName() {
file:///D|/1/final/BBL0033.html (7 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
return name; } public decimal getOwes() { return owes; }
To include these features, right click on the Customer icon to make the following options appear:
First select the Field option and type in the word: name for the field. After this, click the right mouse button to display the following options and then select Properties:
file:///D|/1/final/BBL0033.html (8 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
The Properties menu will appear like the following:
In the Type property, change from the default int to string. Leave the Access as private. Following these same steps, create the field: owes and make its Type: decimal and Access as private. After completing the fields, the next step is to add the methods. Right click on the name of the structure and select Add and then Method.
file:///D|/1/final/BBL0033.html (9 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Enter the name of the first method: setName. After typing in the name, right click on the name of the method and select Properties and the following should appear:
file:///D|/1/final/BBL0033.html (10 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
Notice that it is possible to change the output type from the default void to any option needed. In addition one of the Properties options is Method Signature. In addition the Access is by default public. The Properties options do not seem to permit the entry of the signature so this will be handled later when viewing the code. Next follow the steps used for the method setName() and add the public methods: ●
void setOwes()
●
string getName()
●
decimal getOwes()
After making these additions to the structure: Customer, the icon should appear as the following:
file:///D|/1/final/BBL0033.html (11 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
To complete the next step, do a right mouse button and select View Code. When you do, the following code should appear in Program.cs: public struct Customer { private string name; private decimal owes; public void setName() { throw new System.NotImplementedException(); } public string getName() { throw new System.NotImplementedException(); } public void setOwes() { throw new System.NotImplementedException(); } public decimal getOwes() { throw new System.NotImplementedException(); } }
Next the signatures of setName() and setOwes() have to be completed and the body of each method needs to be
file:///D|/1/final/BBL0033.html (12 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
rewritten removing the throw statements. When this is completed, the code should now appear like the following: public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public string getName() { return name; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public decimal getOwes() { return owes; } }
For the program documentation, the graphic should also be saved. Example 2: In the example above, the access member methods were used. In addtion to access member methods, C# can also implement properties for the fields of a structure as was discussed in a previous example in this section. In that discussion the structure Customer was this time written with properties as in the following: public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } }
file:///D|/1/final/BBL0033.html (13 von 17) [01.12.2007 04:48:10]
UML Charts and Class Diagram for Structures
The next step will be to create a UML chart that implements structure properties. Using the same technique as in the above example, the fields are entered in as before. The problem with Visio is that it does not appear that there are any features to implement, properties. Therefore what I did was to create methods whose names were the following: Name get{} set{}
and Owes get{} set{}
When the UML chart was completed, it appeared as in the following:
Notice that the parenthesis appears above even though they should not. I was unable to find a way to eliminate them. Create a console project called: NEWAR. Once it appears, click on Project on the Menu Bar. From the choices, again select, Add New Item. The item to be added is again, Class Diagram. This again will create a Class Diagram document on to which drag a structure. Name the structure Customer. Recall that this structure may be placed into any file. To simulate a case where the structure may be placed into the component library, this time permit the structure to be placed into the default file which is Customer.cs. As before, create the two fields: name and owes. Instead of creating the methods as in the previous example, select Property from the menu selection as in the following:
file:///D|/1/final/BBL0033.html (14 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
When creating the Property Name change its data type to string and when creating Owes change its data type to decimal. This should create a graphic like the following:
Do a right click on the graphic and select View Code. The structure's definition should appear like the following: public struct Customer { private string name; private decimal owes;
file:///D|/1/final/BBL0033.html (15 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
public string Name { get { throw new System.NotImplementedException(); } set { } } public decimal Owes { get { throw new System.NotImplementedException(); } set { } } }
What now needs to be done is to remove the throw statements from each get{} and to enter the correct code into each get{} and each set{} as in the following: public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } } }
file:///D|/1/final/BBL0033.html (16 von 17) [01.12.2007 04:48:11]
UML Charts and Class Diagram for Structures
This would complete the coding of the structure Customer. What should of course be done now would be to save the graphics for each of these two charts.
file:///D|/1/final/BBL0033.html (17 von 17) [01.12.2007 04:48:11]
Lecture 3 Examples
Lecture 3 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
Accounts Payable (output)
Demonstrates a Windows program which outputs data to a text file.
●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Accounts Payable (input) ●
Form1.cs
●
Form1.Designer.cs
●
Program.cs
Demonstrates a Windows program which inputs data from a text file.
APTotals.xls
An Excel spreadsheet that demonstrates inputting data into the spreadsheet which would output into a text file.
function1.cs
Demonstrates how to use functions in C#.
function2.cs
Demonstrates how to use functions with arguments. One of the arguments is passed by value and the other is passed by reference ref.
function3.cs
Demonstrates how to use functions with arguments. One of the arguments is passed by value and the other is passed by the reference out.
function4.cs
Demonstrates how it is possible that the function: Main() calls another function that does all of the work.
newfact.cs
demonstrates how to use recursive functions in C#
newgcd.cs
Demonstrates how to use recursive functions in C#.
overload.cs
Demonstrates how to overload functions in C#.
readFromTextFiles.cs
Demonstrates text file input.
struct0.cs
Illustrates a struct where the definition of an instance initializes the data members.
struct1.cs
Illustrates a struct definition, struct variable definition, struct assignment, and the manipulation of struct members‥
struct2.cs
Illustrates a struct definition, struct variable definition, struct assignment, and the manipulation of struct members.
struct3.cs
Illustrates a struct with methods including a constructor.
struct4.cs
Illustrates a struct where the definition of a non-default constructor is included.
struct5.cs
Illustrates a struct where the definition of an instance uses the new operator and the definition of the structure does not have a constructor.
struct6.cs
Illustrates a struct where the definition of default constructor is included. However it will not compile.
struct10.cs
Illustrates a struct with private data members and public methods.
struct11.cs
Illustrates that the assignment operator is overloading on structures.
structToString.cs
Illustrates how a struct can override the ToString() method.
structureProperties.cs
Illustrates a structure with public properties of the data members instead of using public methods.
testingInFileName.cs
Demonstrates the testing of the name of the text file to see if it exits before input.
testingwriteToTextfiles.cs
Demonstrates how to test to determine if a text file exists before output. It only permits continuation if the file did not exist.
writeToTextfiles.cs
Demonstrates text file output.
// program_id Form1.Designer.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // namespace accountsPayable { partial class Form1
file:///D|/1/final/BBL0034.html (1 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
{ /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.thePosting = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 96); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // companyName // this.companyName.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0))); this.companyName.Location = new System.Drawing.Point(138, 43); this.companyName.Name = "companyName"; this.companyName.Size = new System.Drawing.Size(142, 22); this.companyName.TabIndex = 1; // // amountDue // this.amountDue.Location = new System.Drawing.Point(138, 96); this.amountDue.Name = "amountDue"; this.amountDue.Size = new System.Drawing.Size(142, 22); this.amountDue.TabIndex = 2; // // thePosting // this.thePosting.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit. Point, ((byte)(0)));
file:///D|/1/final/BBL0034.html (2 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
this.thePosting.Location = new System.Drawing.Point(12, 171); this.thePosting.Name = "thePosting"; this.thePosting.Size = new System.Drawing.Size(75, 23); this.thePosting.TabIndex = 3; this.thePosting.Text = "Post"; this.thePosting.UseVisualStyleBackColor = true; this.thePosting.Click += new System.EventHandler(this.thePosting_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 267); this.Controls.Add(this.thePosting); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.MaximumSize = new System.Drawing.Size(300, 300); this.MinimumSize = new System.Drawing.Size(300, 300); this.Name = "Form1"; this.Text = "Accounts Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.Button thePosting; } }
// program_id Form1.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace accountsPayable { public partial class Form1 : Form { static string fileName = @"accountsPayable.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = "0.00"; writeFileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } private void thePosting_Click(object sender, EventArgs e) { fileWriter.WriteLine(companyName.Text); fileWriter.WriteLine(amountDue.Text);
file:///D|/1/final/BBL0034.html (3 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
fileWriter.Flush(); companyName.Text = ""; amountDue.Text = "0.00"; companyName.Focus(); } } }
// program_id Program.cs // written_by don voils // date_written 6/28/2006 // description This program provides for the output of data from a Windows form // to a text file. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace accountsPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id function1.cs // written?_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions in C# // using System;
class theProgram { static void Main() { // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(); // Causes the running of the program to stop // and waits for the pressing of the enter key. // This is needed most when executing the program // using Debug. // Console.ReadKey(); } static void calculatePayroll() { // This char used to control the loop // char toContinue = 'y'; // this int keeps track of the number of employees //
file:///D|/1/final/BBL0034.html (4 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
int numberEmployees = 0; // The doubles required for the calculations // double totalPayroll = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear();
// Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); totalPayroll += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",totalPayroll); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. //
Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id function2.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions with arguments. // One of the arguments is passed by // value and the other is passed by // reference ref. // using System;
class theProgram { static void Main() {
file:///D|/1/final/BBL0034.html (5 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// The doubles required for the calculations // double totalPayroll = 0.00; // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(ref totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } // Notice the use of the keyword ref both in the call above // and in the definition below. // static void calculatePayroll(ref double theTotal) { // This char used to control the loop // char toContinue = 'y'; // this int keeps track of the number of employees // int numberEmployees = 0;
do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); } // Notice that the argument theTotal does not need to be passed by reference // so the modifier ref is no included in the definition below or the call above. // static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y'));
file:///D|/1/final/BBL0034.html (6 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} }
// program_id function3.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use functions with arguments. // One of the arguments is passed by // value and the other is passed by // the reference out. // using System;
class theProgram { static void Main() { // The doubles required for the calculations // double totalPayroll; // Receives and adds the value of each emplyee's payroll // until the user requests the process to stop. // calculatePayroll(out totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } static void calculatePayroll(out double theTotal) { // This char used to control the loop // char toContinue = 'y'; // Since the variable theTotal is passed in with no value // using the modifier out, it must be initialized. // theTotal = 0.00; // this int keeps track of the number of employees // int numberEmployees = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ",numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); }while((toContinue == 'y') || (toContinue == 'Y')); } // Even though the argument theTotal was passed into the method // calculatePayroll() by reference, this feature is not needed // in the following method so it is passed in by value. //
file:///D|/1/final/BBL0034.html (7 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}",theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); }while((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id function4.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how it // is possible that the function: Main() // calls another function that does all // of the work. // using System;
class theProgram { static void Main() { StaringProgram(); } static void StaringProgram() { // The doubles required for the calculations // double totalPayroll; // Receives and adds the value of each emplyee's payroll // until the user requests to stop. // calculatePayroll(out totalPayroll); showTotalPayroll(totalPayroll); Console.ReadKey(); } static void calculatePayroll(out double theTotal) { // This char used to control the loop // char toContinue = 'y'; // Since the variable theTotal comes in with no value // using the modifier out, it must be initialized. //
file:///D|/1/final/BBL0034.html (8 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
theTotal = 0; // this int keeps track of the number of employees // int numberEmployees = 0; do { ++numberEmployees; // Clears the screen. // Console.Clear(); // Request and receive the individual payroll. // Console.Write("\nWhat was the salary of employee {0}? ", numberEmployees); theTotal += Double.Parse(Console.ReadLine()); // Request and receive whether to continue. // Console.Write("\n\nDo you want to continue? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); } while ((toContinue == 'y') || (toContinue == 'Y')); } static void showTotalPayroll(double theTotal) { char toContinue; do { // Clears the screen. // Console.Clear(); // Displays the total payroll. // Console.WriteLine("The total payroll was {0:c}", theTotal); // Improves the vertical spacing. Console.WriteLine("\n\n"); // Request and receive whether to continue. // Console.Write("\n\nDo you want to end program? (Y/N) "); toContinue = Char.Parse(Console.ReadLine()); // Clears the screen. // Console.Clear(); } while ((toContinue != 'y') && (toContinue != 'Y')); } }
// program_id newfact.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use recursive functions in C# // using System;
class theProgram { static void Main() { int number1; Console.Write("What is the number? "); number1 = Int32.Parse(Console.ReadLine());
file:///D|/1/final/BBL0034.html (9 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
Console.WriteLine("\n{0} factorial is {1}\n\n",number1,factorial(number1)); Console.ReadKey(); } static long factorial(int numb) { return (numb==0)?(1):(numb * factorial(numb-1)); } }
// program_id newgcd.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use recursive functions in C# // using System;
class theProgram {
static void Main() { int int1, int2; Console.Write("What is the first number? "); int1 = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat is the second number? "); int2 = Int32.Parse(Console.ReadLine()); Console.WriteLine("\nThe GCD of {0} and {1} is {2}\n",int1,int2,newGCD(int1,int2)); Console.ReadKey(); } static int newGCD(int numb1, int numb2) { return (numb1b?a:b); } static long MAX(long a, long b) { return (a>b?a:b); } static float MAX(float a, float b) { return (a>b?a:b); } static double MAX (double a, double b) { return (a>b?a:b); } }
// program_id readFromTextFiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file input. // using System; using System.IO; namespace readFromTextFiles { class InPutData { static string fileName = "datafile.txt"; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerFirstName = fileReader.ReadLine(); while(customerFirstName != null) { customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" " +customerLastName); customerID = fileReader.ReadLine(); Console.WriteLine("Customer's ID: "+customerID); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("Balance due: {0:c}\n",customerBalanceDue)); customerFirstName = fileReader.ReadLine(); } CloseDataFiles(); Console.ReadKey();
file:///D|/1/final/BBL0034.html (11 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close(); if( fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream ); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id scope1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use local variables in C# functions. // using System;
class theProgram { static void Main() { int x = 5; overThere(x); Console.WriteLine("\nAfter the function, the outside x = {0}\n",x); }
static void overThere(int a) { int x = 7; Console.WriteLine("\nIn the function, the inside x = {0}",x); Console.WriteLine(" & the outside x = {0}",a); } }
// program_id static1.cs // written_by don voils // date_written 12/14/2006 // description This program demonstrates how to // use static variables in C# // using System;
class theProgram { static int x = 7; static void Main() { // Notice there there is no automatic variable x inside of Main() // The static variable will be called in each of the folowing statements. // overThere(x); Console.WriteLine("Static variable from outside of Main() where x = {0}\n", x); overThere(x); Console.WriteLine("Static variable from outside of Main() where x = {0}\n", x);
file:///D|/1/final/BBL0034.html (12 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
} static void overThere(int a) { // Notice there there is no automatic variable x inside of overThere() // The static variable will be called in each of the folowing statements. // Console.WriteLine("Static variable x = {0}" + " inside of overThere()\n & passed by value x = {1}\n",x,a); ++x; Console.WriteLine("Incremented static variable inside of overThere().\n"); } }
//program_id struct0.cs //author don voils //date written 6/10/2006 //Description This program illustrates a struct // where the definition of an instance // initializes the data members. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne = new Customer(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name, theOne.owes); Console.ReadKey(); } }
//program_id struct1.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struct // definition, struct variable definition, // struc assignment, and the manipulation // of struc members. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne; Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n",theOne.name,theOne.owes); Console.ReadKey(); }
file:///D|/1/final/BBL0034.html (13 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
}
//program_id struct2.cs // //author don voils //date written 12/22/2006 // //Description This program illustrates a struc // definition, struc variable definition, // struc assignment, and the manipulation // of struc members. // using System; public enum WorkType {SALARIED, HOURLY}; public struct Date { public int theMonth, theDay, theYear; } public struct Employee { public Date hireDate; public WorkType salaryType; public string employeeLastName, employeeFirstName; public decimal unitPay; }
class theProgram { static void Main() { Employee newStaff; Console.Write("\nWhat is the new employee's first name? "); newStaff.employeeFirstName = Console.ReadLine(); Console.Write("\nWhat is the new employee's last name? "); newStaff.employeeLastName = Console.ReadLine(); Console.Write("\nWhat is {0} {1}'s pay per unit of work? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.unitPay = Decimal.Parse(Console.ReadLine()); Console.Write("\nWhat month was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theMonth = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat day was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theDay = Int32.Parse(Console.ReadLine()); Console.Write("\nWhat year was {0} {1} hired? ", newStaff.employeeFirstName,newStaff.employeeLastName); newStaff.hireDate.theYear = Int32.Parse(Console.ReadLine()); int salaryType; Console.Write("\nIs the employee salaried (0) or hourly {1)? "); salaryType = Int32.Parse(Console.ReadLine()); newStaff.salaryType= (WorkType)salaryType; Console.Clear(); Console.WriteLine("\n\nDid you say that the name of the new employee is {0} {1}", newStaff.employeeFirstName,newStaff.employeeLastName); Console.WriteLine("who was hired on {0}/{1}/{2}" ,newStaff.hireDate.theMonth ,newStaff.hireDate.theDay ,newStaff.hireDate.theYear);
file:///D|/1/final/BBL0034.html (14 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
if (newStaff.salaryType==WorkType.SALARIED) Console.WriteLine("and is salaried at {0:c}?" ,newStaff.unitPay); else Console.WriteLine("and is hourly at {0:c}?" ,newStaff.unitPay); Console.ReadKey(); } }
//program_id struct3.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struc // with methods including a constructor. // using System;
public struct Circle { private double theRadius; public Circle(double Radius) { theRadius = Radius; } public void setRadius(double Radius) { theRadius = Radius; } public double getRadius() { return theRadius; } public double getArea() { double PI = 3.14159; return (theRadius * theRadius * PI); } public double getCircumference() { double PI = 3.14159; return (2 * theRadius * PI); } } class theProgram { static void Main() { Circle theCircle = new Circle(); Console.Write("What is the radius of the circle? "); theCircle.setRadius(Double.Parse(Console.ReadLine())); Console.Clear(); Console.WriteLine("\n\nThe area of the circle is {0}",theCircle.getArea()); Console.WriteLine("\nThe circumference of the circle is {0}\n\n",theCircle.getCircumference()); Console.ReadKey(); } }
//program_id struct4.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struc // where the definition of a non-default
file:///D|/1/final/BBL0034.html (15 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// constructor is included. // using System; public struct Customer { public string name; public decimal owes; public Customer(string aName,decimal TheyOwe) { name = aName; owes = TheyOwe; } } class theProgram { static void Main() { Console.Write("\nWhat is the customer's name? "); string aName = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",aName); decimal TheyOwe = Decimal.Parse(Console.ReadLine()); Customer theOne = new Customer(aName,TheyOwe); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name,theOne.owes); Console.ReadKey(); } }
//program_id struct5.cs //author don voils //date written 12/22/2006 //Description This program illustrates a struct // where the definition of an instance // uses the new operator and the // definition of the structure // does not have a constructor. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne = new Customer(); Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n",theOne.name,theOne.owes); Console.ReadKey(); } }
//program_id struct6.cs //author don voils
file:///D|/1/final/BBL0034.html (16 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
//date written 12/22/2006 //Description This program illustrates a struc // where the definition of default // constructor is included. However // it will not ocmpile. // using System; public struct Customer { public string name; public decimal owes; public Customer() { name = ""; owes = 0.0; } } class theProgram { static void Main() { Customer theOne = new Customer(); Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.name,theOne.owes); } }
//program_id struct10.cs //author don voils //date written 6/10/2006 //Description This program illustrates a struct // with private data members and // public methods. // using System; public struct Customer { private string name; private decimal owes; public void setName(string aName) { name = aName; } public void setOwes(decimal customerOwes) { owes = customerOwes; } public string getName() { return name; } public decimal getOwes() { return owes; } } class theProgram { static void Main() { Customer theOne = new Customer(); theOne.setName("George Washington");
file:///D|/1/final/BBL0034.html (17 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
theOne.setOwes(100000.00m); Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.getName(), theOne.getOwes()); Console.ReadKey(); } }
//program_id struct11.cs //author don voils //date written 12/22/2006 // //Description This program illustrates that // the assignment operator is // overloading on structures. // using System; public struct Customer { public string name; public decimal owes; } class theProgram { static void Main() { Customer theOne; Customer theOtherOne; Console.Write("\nWhat is the customer's name? "); theOne.name = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ", theOne.name); theOne.owes = Decimal.Parse(Console.ReadLine()); theOtherOne = theOne; Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOtherOne.name, theOtherOne.owes); Console.ReadKey(); } }
//program_id structToString.cs // //author don voils //date written 12/22/2006 // //Description This program illustrates how a struc // can override the ToString() method // using System; public struct Customer { public string name; public decimal owes; public Customer(string aName,decimal theyOwe) { name = aName; owes = theyOwe; } public override string ToString() { string output = String.Format("\nCustomer: {0}\nOwes: {1:c}",name,owes); return output; } }
file:///D|/1/final/BBL0034.html (18 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
class theProgram { static void Main() { Console.Write("\nWhat is the customer's name? "); string aName = Console.ReadLine(); Console.Write("\n\nEnter the amount that {0} owes? ",aName); decimal theyOwe = Decimal.Parse(Console.ReadLine()); Customer theOne = new Customer(aName,theyOwe); Console.Clear(); Console.WriteLine(theOne.ToString()); Console.ReadKey(); } }
//program_id structureProperties.cs //author don voils //date written 8/28/2006 //Description This program illustrates a struct // with public properties of the data members // instead of using public methods. using System; public struct Customer { private string name; private decimal owes; public string Name { get { return name; } set { name = value; } } public decimal Owes { get { return owes; } set { owes = value; } } } class theProgram { static void Main() { Customer theOne = new Customer(); theOne.Name = "George Washington"; theOne.Owes = 100000.00m; Console.Clear(); Console.WriteLine("\nDid you say that the customer {0} owes {1:c}\n", theOne.Name, theOne.Owes); Console.ReadKey(); } }
file:///D|/1/final/BBL0034.html (19 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
// program_id testingInFileName.cs // written_by don voils // date_written 1/9/2006 // description This program demonstrates the testing of the name // of the text file to see if it exits before input. // using System; using System.IO; namespace readFromTextFiles { class InPutData { static string fileName; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(!File.Exists(fileName)) { Console.WriteLine("\nThat file does not exist."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerFirstName = fileReader.ReadLine(); while(customerFirstName != null) { customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" " +customerLastName); customerID = fileReader.ReadLine(); Console.WriteLine("Customer's ID: "+customerID); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("Balance due: {0:c}\n",customerBalanceDue)); customerFirstName = fileReader.ReadLine(); } CloseDataFiles(); Console.ReadKey(); } } static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close();
file:///D|/1/final/BBL0034.html (20 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
if( fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream ); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id testingwriteToTextfiles.cs // written_by don voils // date_written 2/10/2006 // description This program demonstrates how to test to // determine if a text file exists before // output. It only permits continuation if // the file did not exist. // using System; using System.IO; namespace writeToTextfiles { class OutPutData { static string fileName; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { char response; bool toProcess; do { Console.Write("\nWhat is the name of the file? "); fileName = Console.ReadLine(); fileName += ".txt"; if(File.Exists(fileName)) { Console.WriteLine("\nThat file already exists."); Console.Write("\nReenter the file name? (Y/N) "); response = Char.Parse(Console.ReadLine()); toProcess = false; } else { response = 'N'; toProcess = true; } }while(response=='Y'||response=='y'); if(!toProcess) { Console.WriteLine("\nThe program will now end. \n\nContinue? "); Console.ReadLine(); } else { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; int moreData = 1; while(moreData == 1) { Console.Clear();
file:///D|/1/final/BBL0034.html (21 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nTo Continue enter 1 and 0 to end. "); moreData = int.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } Console.ReadKey(); } static void OpentoWritetoDataFile() { if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // namespace viewAccountPayable { partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }
file:///D|/1/final/BBL0034.html (22 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.nextAP = new System.Windows.Forms.Button(); this.companyName = new System.Windows.Forms.TextBox(); this.amountDue = new System.Windows.Forms.TextBox(); this.totalAPDue = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(45, 27); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(120, 17); this.label1.TabIndex = 0; this.label1.Text = "Company Name"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(48, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 17); this.label2.TabIndex = 1; this.label2.Text = "Amount Due"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(48, 120); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(104, 17); this.label3.TabIndex = 2; this.label3.Text = "Total AP Due"; // // nextAP // this.nextAP.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.nextAP.Location = new System.Drawing.Point(48, 178); this.nextAP.Name = "nextAP"; this.nextAP.Size = new System.Drawing.Size(84, 23); this.nextAP.TabIndex = 3; this.nextAP.Text = "Next"; this.nextAP.UseVisualStyleBackColor = true; this.nextAP.Click += new System.EventHandler(this.nextAP_Click); // // companyName // this.companyName.Location = new System.Drawing.Point(196, 27); this.companyName.Name = "companyName"; this.companyName.ReadOnly = true; this.companyName.Size = new System.Drawing.Size(112, 22); this.companyName.TabIndex = 4; // // amountDue // this.amountDue.Location = new System.Drawing.Point(196, 70); this.amountDue.Name = "amountDue";
file:///D|/1/final/BBL0034.html (23 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
this.amountDue.ReadOnly = true; this.amountDue.Size = new System.Drawing.Size(112, 22); this.amountDue.TabIndex = 5; // // totalAPDue // this.totalAPDue.Location = new System.Drawing.Point(196, 120); this.totalAPDue.Name = "totalAPDue"; this.totalAPDue.ReadOnly = true; this.totalAPDue.Size = new System.Drawing.Size(112, 22); this.totalAPDue.TabIndex = 6; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(328, 267); this.Controls.Add(this.totalAPDue); this.Controls.Add(this.amountDue); this.Controls.Add(this.companyName); this.Controls.Add(this.nextAP); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.Name = "Form1"; this.Text = "View Account Payable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button nextAP; private System.Windows.Forms.TextBox companyName; private System.Windows.Forms.TextBox amountDue; private System.Windows.Forms.TextBox totalAPDue; } }
// program_id Form1.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace viewAccountPayable { public partial class Form1 : Form { static string fileName = @"accountsPayable.txt"; static FileStream readFileStream; static StreamReader fileReader; static double totalDue; public Form1() { InitializeComponent(); companyName.Text = ""; amountDue.Text = String.Format("{0:c}", 0.00); totalAPDue.Text = String.Format("{0:c}", 0.00); readFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); fileReader = new StreamReader(readFileStream);
file:///D|/1/final/BBL0034.html (24 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
totalDue = 0.00; } private void nextAP_Click(object sender, EventArgs e) { if (fileReader.EndOfStream == false) { companyName.Text = fileReader.ReadLine(); double theAmount = double.Parse(fileReader.ReadLine()); totalDue += theAmount; amountDue.Text = String.Format("{0:c}", theAmount); totalAPDue.Text = String.Format("{0:c}", totalDue); } else MessageBox.Show("There is no more data to read."); } } }
// program_id Program.cs // written_by don voils // date_written 4/3/2006 // description This Windows program demonstrates input // from a text file. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace viewAccountPayable { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id writeToTextfiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file output. // using System; using System.IO; namespace writeToTextfiles { class OutPutData { // Notice that the following variables are static fields // of the class OutPutData. Therefore they are accessible // withing the following methods without the need to be // dotted with an object or the class. In a way they are // acting like "global" variables being used with the // "global" functions/methods. // static string fileName = "datafile.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) {
file:///D|/1/final/BBL0034.html (25 von 26) [01.12.2007 04:48:14]
Lecture 3 Examples
OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; int moreData = 1; while(moreData == 1) { Console.Clear(); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nTo Continue enter 1 and 0 to end. "); moreData = int.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); Console.ReadKey(); } static void OpentoWritetoDataFile() { if( fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream ); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
file:///D|/1/final/BBL0034.html (26 von 26) [01.12.2007 04:48:14]
Lecture 4: Classes in C#
Lecture 4: Classes in C# An Introduction to C# Classes The language C is based upon the concepts of structured programming. By this is meant that C is based upon the three structures: ●
sequence,
●
selection and
●
recursion
with the added feature of program modularization with functions. C++ extended C and added object oriented programming (OOP). To achieve this, C++ added the concept of classes to C. OOP is based upon the concepts of ●
encapsulation,
●
polymorphism and
●
inheritance.
By encapsulation is meant that parts of the code are hidden either fully or partially from access by other parts of the program. Polymorphism means that some parts of the code look like or act like other parts of the code. This feature saves a programmer time and work when these polymorphic relationships are used. By inheritance is meant that previously written code (i.e. classes) may be used in new and previously unconnected ways. These three concepts are achieved in C++ through the use of classes. C# being an extension of these two languages has both the structured programming features as well as the OOP features of the C/C++ family of languages. This lecture introduces the encapsulation part of C# i.e. it introduces C# classes.
Definition of a Class Object In C# the system data types are: boolean, int, float, double etc. These system data types are used to create blocks of memory with a specific size and with specific properties. These data types are used by defining and then using instances that possess these properties. In addition to the system data types, the programmer may add instances of enumerated data types and structures. The system types, the enumerated types and the structures in C# are referred to as value types. As discussed previously, value types are stored on the stack.
file:///D|/1/final/BBL0035.html (1 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
One of the major features of C# is the class. A class is treated similar to how you have been working with the system data types, enumerated data types and structures. However, when classes are used, the instances are referred to as objects of the class. The objects (instances of programmer defined class data types) are handled differently than the instances of the system data types, enumerated data types and structures. Programmer defined objects are reference variable types in that they contain the address of the class object's memory units. These variables are referred to as reference types. The reference variables reside on the stack but the actual objects of the class reside on the heap. Note: References are similar to the pointers in C++. However they are not as dangerous as pointers. Suppose that the program was to contain a reference: theReference to an object of the TheClass. The definition could be handled in one of the following two ways: ●
First the code may define theReference and its object using the following two statements:
TheClass theReference; theReference = new TheClass();
The first statement defines theReference and the second statement creates an object of TheClass and assigns the address of TheClass object to theReference. If theReference is used before the second statement, an error will occur. ●
Second the two statements above could also be written as one statement like the following:
TheClass theReference = new TheClass();
Note: Each of the above statements uses a class constructor as in TheClass(). As will be seen later in this lecture, a class may have additional constructors some of which may have arguments. Note: It is possible to define a class as static. In this case it is not possible to define a reference because there is no new operator for a static class. Further a static class may only have static fields and static methods.
file:///D|/1/final/BBL0035.html (2 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
Note: It is recommended that the name of each class begin with a capital letter and that each additional word of the name should also begin with a capital letter. The reference and the object to which it refers to are stored as in the following graphic:
Note: The new operator is being used above when the object is defined. This operator is similar to the new operator in C++ that creates the object on the heap and returns the address of this object to theReference. What is different from C++ is that this memory does not need to be deallocated. The programs listed below will use the new operator to create the objects but they will not use the delete operator to deallocate the memory as was necessary in C++. When theReference moves out of scope, then the stack memory used by the variable theReference is returned to the system automatically as was done with variables in C++. However the memory on the heap to which it refers is reclaimed later by the Garbage Collector (GC). When the GC executes, it locates the objects that have no reference and automatically returns their memory to the system. While this is true for objects being handled by system objects, those objects that are involved with network connections, database connections and files must be handled by the programmer as will be discussed later in this lecture. Be careful when using references and one reference is set equal to another. What happens is that both references contain the address of the same object. Therefore if the contents of the class object are changed, then these new values will appear for both references.
Class Definition and Member Access By the definition of a class is meant a construct that contains the description of member data (also called fields) that are declared (non-static fields) or defined (static fields) within the definition of the class construct. The nonstatic fields describe the internal construction of each object of the class that is stored on the heap. In addition to the fields, there are member functions (also called methods or operations) defined in the class' definition. The member functions describe how the objects (variables) of the class may interact with the fields of the object and with the remainder of the program. Note: A difference with C++ is that the classes as well as each of its methods and its fields have their own individual access modifier. But similar to C++, the access modifiers are: static, private, public and protected are among the modifiers used. Note: As with the system data types, each class is derived from the System class Object. However this derivation is implicit and requires no explicit coding by the programmer. This therefore implies that methods of Object may be overloaded, overridden and used by programmer defined classes. The class definition construct has the following properties: ●
a header that includes an access modifier, the keyword class and the tag or name of the class.
●
the body of the class that is enclosed by braces: { } (Notice that there is no semicolon after the closing brace.)
●
a collection of zero or more fields declared or defined within the body (Note: Each object contains copies of the
file:///D|/1/final/BBL0035.html (3 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
non-static fields.) ●
a collection of zero or more methods defined within the body. (Note: The objects do not contain the methods but they may use the non-static methods in ways that are consistent with the access modifier of each method.)
●
a collection of zero or more events defined or declared within the body. (Note: More will be discussed about events in later lectures.)
●
the declarations or definitions of each member is preceded and thereby controlled by its own personal access modifier
The construct for a class definition is: access_modifier class Classname { private memberdatatype datamemberlist; private output_datatype memberfunction(signature) { ..... } protected memberdatatype datamemberlist; protected output_datatype memberfunctions(signature) {....} public memberdatatype datamemberlist; public memberfunctions(argument list) {....} ..... }
The access_modifiers for a class is either public or internal. When the definition of a class has an access modifier of public, then that definition may be accessed in any program that includes the file that contains the definition of the class and the program uses the namespace in which the class is defined. The class access modifier internal restricts access to the class by that code which is in the same assembly (i.e. in the same .exe or . dll file.) If the class' definition does not include an explicit access modifier, then the default is internal. The fields and the methods of a class have the following access modifiers:
Open table as spreadsheet Access Modifier
Restrictions
private
those class members that are either defined or declared as private:
protected
●
are accessible only within the class (they are similar to local variables of a function in that they are only visible within the class.)
●
are not accessible anywhere else other than within the class not even by the instance/object of the class in which they are contained not even using the access operator (i.e. the dot operator)
●
or do not have an explicit access modifier are then implicitly private by default.
those class members that are either defined or declared as protected: ●
internal
have the same accessibility and properties as those members defined as private except as they will relate to derived classes (as will be discussed later).
those class members that are either defined or declared as internal: ●
are accessible only within the same assembly (i.e. in the same .exe or .ddl file) in which their class is defined.
file:///D|/1/final/BBL0035.html (4 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
public
those class members that are either declared or defined as public: ●
static
protected internal
have the same accessibility as structure members do in C++ and therefore may be accessed anywhere.
those class members that are either declared or defined as static: ●
are not accessible by objects and are only accessible by the class using the dot operator.
●
may also be either public or private
●
are loaded into memory when the class becomes available
●
exist during the duration of the program that contains the class' definition even when no objects exist.
those class members that are either declared or defined as protected internal have access limited: ●
to the containing class
●
to the derived classes
●
to those classes within the same assembly as the containing class.
Objects get access to the available members using the access member operator (also called the dot operator). That is if anObject is a reference to an object of some class and aMember is some non-static member of that class, then the anObject gets access to aMember through the access member operator as in the following statement (depending on the access specifier of aMember and where the access is being attempted): anObject.aMember;
If the member is static, then instead of anObject, theClass is used to get access as in the following: TheClass.aStaticMember
(Note: When a class accesses a static member, then the dot operator is used rather than the scope specifier operator (::) as is done in C++.) Note: When or where an object of a class may access its members depends on which access modifier precedes the member when it is defined or declared. For example an int field numberCustomers could have private access if it was declared as follows: private int numberCustomers;
A member function countInvoices() could be defined as public as follows: public int countInvoices() { ...... }
file:///D|/1/final/BBL0035.html (5 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
Note: It is recommended that each field and method begin with a lower case letter and that each word beyond the first word should have its first letter a capital letter. In addition, it is recommend that each method begin with a verb as in countInvoices(). At the top of each of the program files should be the following statement: using System;
because these files contain references to that namespace. Further, notice that each of the class definitions may be enclosed in a namespace. This must either be the same namespace that the program is in or a using statement with the class' namespace must be placed at the top of the program code with the other using statements. In the examples below notice that the fields of most classes are private and that the methods are usually public. The members' declarations/definitions may appear in any order within the class' definition. The recommendation is that the fields be listed first and then the methods. Then within these two groups, they should be ordered in terms of their respective access modifier with the recommended order being: private, protected, internal, public, static and finally protected internal. If a member should be declared/defined with no explicit access modifier, then the member will implicitly default to private but the access modifiers should always be present to ensure that the member is following the software specification requirements. Usually the methods are public but they may also be private. For example see the following class: theDate. Notice that some of the methods are private and therefore can be accessed only within the class by other members of the class. As part of the Design Phase, the UML chart for each class should be defined. For example the class: Date in the example above would have the following UML chart:
References to a Class Object When two value types are defined, separate places in stack memory are created. For example: // As a result of the following a and b // refer to two different place in stack // memory. // int a = 5; int b = a; Console.WriteLine("a stored {0} and b stored {1}", a, b); file:///D|/1/final/BBL0035.html (6 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
b = 15; Console.WriteLine("b was changed."); Console.WriteLine("a stored {0} and b stored {1}\n", a, b);
The output of the first statement would show that both a and b contained the value of 5. However once 15 is placed in b, the value in a is still 5 and the value in b is now 15. When two references to class objects are defined, they may point to the same places on the heap. For example in the following code, the class references A and B are different references but they are accessing the same place on the heap. As a result, to begin with both A and B reference memory that contains the value 15. However when B has its object's field changed to 24, the object that A and B refer to is the same place on the heap and therefore the output for both A and B is 24. See references1.cs // As a result of the following both A and B // refer to the same place in heap memory // TheFirst A = new TheFirst(); A.settheFirstone(15); theFirst B = A; Console.WriteLine("A stored {0} and B stored {1}", A.getTheFirstOne(), B.getTheFirstOne()); Console.WriteLine("B was changed."); B.setTheFirstone(24); Console.WriteLine("A stored {0} and B stored {1}\n", A.getTheFirstOne(), B.getTheFirstOne());
Passing Objects to Functions When an object is passed to a function, it is automatically passed by reference with no special notation required as in the following function: static void modifyCustomerBalance(TheCustomer theOne) { Console.Write("What is {0}'s new balance? ",theOne.getTheName()); double theAmount = Double.Parse(Console.ReadLine()); theOne.setTheBalance(theAmount); Console.WriteLine("\n\n"); }
For example see class4.cs.
Classes in Multiple Files In .NET 1.0, the C# methods had to be defined within the class definition and can not be placed into separate files from the class' definition as in C++. If the class was placed into a separate file from the program, then the entire definition including the methods' definitions must be placed into that file and within the definition of the class. .NET 2.0 has added a variation that makes it more like C++ in this respect. This variation requires that each part of the
file:///D|/1/final/BBL0035.html (7 von 8) [01.12.2007 04:48:16]
Lecture 4: Classes in C#
class (and there can be several) can be in a different file. However in order for this to work, the keyword: partial must be used with the class' definition block for each part of the class. The keyword partial must appear immediately before the keyword class. For example the following code could be in one file of the project: public partial class TheAccount { private decimal theBalance; }
while the following code could be in another file of the project.: public partial class TheAccount { public settheBalance(decimal startBalance) { theBalance = startBalance; } }
Note: When the definition of a class is placed in a separate file, the file that contains the class' definition should be enclosed within a namespace. If the file only contained the class' definition, then it is recommended that the namespace be similar to the name of the class. Note: Look at the windows program examples that were considered in previous lectures. Notice that the definition of the class Form1 appeared in two different files: Form1.cs and Form1.Designer.cs and that each class contained part of the class' definition using the word: partial. In Visual Studio .NET 2003 all of this code was in the same file. Create the project processCustomers.cs using the following three files: class5.cs, theCustomer.cs and theCustomer2.cs. Compile and run the program. Notice that the class: Customer was defined in the last two of these files and that each part of the class' definition used the key word: partial. Note: If two classes have the same name and are in different namespaces then the namespace should precede the name of the class when calling the class. In this way the compiler will know which class is being called.
file:///D|/1/final/BBL0035.html (8 von 8) [01.12.2007 04:48:16]
Class Fields
Class Fields Field Initialization If the program does not explicitly initialize the data members (also called fields) of an object, they are initialized automatically to the default for the data type. For example if the field is one of the system numeric values, it will be initialized to 0, if it is a string, it will be initialized to an empty string and if it is a Boolean, then it would be initialized to false. The Visual Studio .NET IDE should produce a warning if the program does not explicitly initialize the fields of an object used in a program. See class1.cs (Note: When this program is compiled, observe all of the warning errors indicating that the class fields have not been initialized, however the program does compile and the default values are automatically assigned to the fields.) As discussed previously, built into C# is the class System.DateTime. If the fields of an object to this class are not initialized, then they will be initialized to 0 automatically. However if you use the property: Now, then the calling object will have its fields initialized to the current time and date. See class2.cs. In C# it is possible to initialize a field to a non-default value within the class' definition. That is in the class' definition a field could be initialized as in the following statement: private double theBalance = 500.00;
Notice how this is done in the following class definition: public class TheClass { private double theBalance = 500.00; private string theName; public void setTheBalance(double theAmount) { theBalance = theAmount; } public void setTheName(string aName) { theName = aName; } public double getTheBalance() { return theBalance; } public string getTheName() { return theName; } }
Therefore each object when defined will have the value of its field theBalance set to 500.00. For example see class3.cs. The following is a UML chart for TheClass in this example:
file:///D|/1/final/BBL0036.html (1 von 2) [01.12.2007 04:48:16]
Class Fields
Constant, Readonly and Static Fields A static field is a field that is declared with the keyword static before its definition. It is not a member of any object. It can only be called by using the name of the class as in the following: TheClass.theStaticField;
A field may be declared as a constant meaning therefore that the program may not change its value during program execution. Making a field a constant can be done by preceding the fields declaration with either the keywords const or readonly. The const fields are static by default and must be initialized when the variable is defined and therefore are not fields of an object. Using the keyword static along with the keyword const will cause a compiler error. Fields that are defined as readonly can be initialized when defined or in a constructor. The const fields are compile time constants and the readonly fields are run time constants. This initialization may be done in any one of several constructors however only one will be called at runtime. The readonly may be preceded with the static modifier. When a field is static and readonly, then the constructor must be static. An int field could be defined as static as follows: static int startYear;
To better understand these concepts, view the definitions of the following classes: Circle and Clock1. A UML chart for the class Circle in the example above is:
file:///D|/1/final/BBL0036.html (2 von 2) [01.12.2007 04:48:16]
Class Methods and Field Properties
Class Methods and Field Properties Initializing Field Methods Generally fields are declared as private. Therefore they can not be accessed except by class members. The question is then how are values placed in fields of the object's memory. One way to do this is with Initializing member methods. These methods require no special code. They usually are defined with public access. They must just permit the data to be loaded into the fields. For example in the class: TheDate defined below, the method: setDate() initializes the fields theMonth, theDay and theYear of an object by assigning the values to the respective field through keyboard input when the method setDate() is called as in the following definition: public class TheDate { private long theMonth, theDay, theYear; public void setDate() { Console.Write("What is the month? "); theMonth = Int32.Parse(Console.ReadLine()); Console.Write("What is the day? "); theDay = Int32.Parse(Console.ReadLine()); Console.Write("What is the year? "); theYear = Int32.Parse(Console.ReadLine()); } // additional code is missing }
For an example of a class that uses the above initialization method see the following program and class pair: viewDateClass.cs and dateClass.cs. This example permitted the initialization of the fields within the body of a class method. However, it is also possible to pass these values in through arguments to initialize the fields. View the following program and class pair: viewBankAccount.cs and bankAccount.cs. Notice how the argument of the method: startAccount() initializes the field: balanceAmount. Note: Initializing field methods usually begin with the word set as in setMonth() Accessor and Mutator Methods The class TheDate just considered in the example dateClass.cs contains the methods getMonth(), getDay(), and getYear(). These methods are called accessor methods because through them it is possible to access the data stored in the fields: theMonth, theDay and theYear. That is the value stored in the field theMonth may be accessed through getMonth() in the following manner: TheDate dob = new TheDate(); dob.setDate(): Console.WriteLine(String.format("The month is {0}", dob.getMonth()));
In addition to accessor methods, the class needs what are called mutator methods. For example, see viewCircleClass.cs and CircleClass.cs. In this example, the field: theRadius is initialized by the mutator method:
file:///D|/1/final/BBL0037.html (1 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
setRadius() and accessed through the access method: getRadius(). Note: In general, each field needs an accessor and a mutator method so that the data within an object's fields may be accessed and changed. These methods should be defined with public access so that the field may be accessed and changed anywhere. Access methods usually begin with the word get as in getRadius() and mutator methods usually begin with the word set as in setRadius(). Field Properties and the get and set Accessors Object oriented programming is based upon the concept of encapsulation. By this is meant that the member data is hidden from accidental modification. This is done by defining the fields with private access. However while this provides the programmer with control, this approach also hinders access and initialization of the fields. The creators of C# came up with what are called the properties of a field. These properties use the keywords: get and set. In the following example Month is a property for the field: theMonth: class TheDate { private int theMonth; private int theDay; private int theYear; int public Month { get { return theMonth; } set { theMonth = (value 12 ? (1):(value); } } ...... // Additional code goes here. }
Notice how the get returns the value of theMonth while set initializes the value of theMonth. As a result of these definitions, the field: theMonth could be modified in the program using its property Month where an object theObject is defined as in the following code: Warning: A property may have only one get or one set. ..... theObject.Month = 3; Console.WriteLine("The month of the day is {0}",theObject.Month); ......
Note: Having properties for a class permits the class to conform to the OOP without breaking the program. Warning: Notice in the definition of the set accessor that the word value was used without an explicit definition. (The variable: value is not a keyword.) This variable is defined by the compiler and may not be used except in a set definition as in the above example. For a complete example look at the following pair of files: ViewNewDate.cs and theNewDate.cs. The UML chart for the class: theDate
file:///D|/1/final/BBL0037.html (2 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
Look at this UML chart very closely. Notice how the fields: theMonth, theDay and theYear of the TheDate class are declared and then how their properties: Month, Day and Year are implemented. Notice the use of > in the UML chart before each of these properties. Observe that there are + signs prior to each property because each is public. However their access modifier could be different. The get and the set do not have an access modifier indicated in the UML chart and therefore they are assumed to be public. However their access modifier may be more restrictive than the property and each could be different from the other. Notice further how in the program ViewNewDate that these properties are used to initialize the fields. Notice also in the class theClass how these properties are used in the method: viewDate(). This example may appear to be destroying encapsulation but it is controlling the fields while restricting how they may be accessed. In a sense you are not destroying encapsulation because the program does not have "direct" access to the fields. When a field's property is defined, it does not require that both the get and the set accessor for that field to be defined. If only the get accessor was defined, then the property would be read only. If only the set accessor was defined, then the property would be write only. The access modifier for the property is usually public and both the get and the set are usually public as well. However the access modifiers for the get or the set may be private as well and thereby further restricting the access to the property of a field. Static fields may be defined to be private. In this case, properties may be defined for the static fields as well as non-static fields. Note: Properties are like the accessor and mutator functions in disguise. It is recommended that the field properties be used rather than the accessor and the mutator methods discussed above. Warning: If properties are defined for a particular field, then the compiler will not permit the definition of accessor or mutator methods. Warning: Fields may be used with ref or out but properties may not be used with ref or out as arguments for a method. Constructor Methods When a class object is defined, memory is set aside, the memory is labeled and restrictions are placed on that memory. This is done by a method called a constructor method. If the programmer does not create one explicitly, the compiler will define a constructor implicitly. Constructors have special characteristic that distinguish them from other methods. While the compiler will create an implicit constructor if one is not explicitly defined, the programmer should always define one explicitly so that it will have the characteristics desired. A constructor is called with the new operator as in the following: theBank theAccount = new theBank(); // the method call on the right of the // assignment is a call to the class // constructor theBank(); file:///D|/1/final/BBL0037.html (3 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
The characteristics of a constructor: ●
has the same name as the class.
●
has no return data type not even void.
●
may have a non-void signature.
●
is created by compiler if none is defined (called the default constructor)
●
may be more than one such method (i.e they may be overloaded.)
●
are usually defined with public access but can also be static if it initializes the static fields or private if the desire is to prevent the creation of objects.
●
will initialize the fields to their default value if not explicitly initialized.
In the statement above, theAccount is a reference to the object that is created by the constructor. The reference resides in the stack and the object to which it refers resides in the heap. These variables are called reference types. Remember that this is different from the variables defined for the system data types which are value types and are stored on the stack. If a constructor has a void signature, then it is called a default constructor. When the compiler creates a constructor, it creates an implicit default constructor. (Note: It is recommended that the programmer always create the default constructor if any other constructors are defined. This will be helpful when defining arrays.) If a constructor has a non-void signature, then it is called an explicit constructor. For an example of a class with explicitly defined constructors, see the file pair: viewBank2.cs and theBank2.cs. A class may have static fields. To initialize these static fields, a static constructor may be defined. These constructors obviously may only initialize the static fields. A class may have only one static constructor. Static constructors may not be assigned an access specifier like public. These constructors are called before any objects of the class are defined. See staticConstructor.cs A constructor in addition to being static or public may also have private access. It may be desirable to have a class be a utility class and to have non-static fields. In this case the constructor could be private to prevent the definition of any objects. See privateConstructor.cs When a class has several constructors, it is possible to define one or more of the constructors in terms of one constructor. For example suppose that a class: theEmployee is to have four different constructors all based upon the following constructor: theEmployee(string anID, string aName, decimal theGross) { theID = anID; theName = aName; grossYTD = theGross; }
The remaining constructors may therefore be defined in the following manner: theEmployee() : this("", "", 0.00) { } theEmployee(string anID) : this(anID, "", 0.00) { } theEmployee(string anID, string aName) : this(anID, aName, 0.00) { }
file:///D|/1/final/BBL0037.html (4 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
For an example of this type of constructors see constructor1.cs. Destructor Methods In addition to constructing the object when it is defined, it is necessary to destroy or reclaim the memory of an object after it is no longer needed. In C# this is achieved by the Garbage Collector (GC). When the reference to the object goes out of scope, its memory on the stack is reclaimed by the system immediately. However the memory on the heap that is held by the object remains assigned until the GC claims it. This memory is reclaimed when the GC periodically reclaims memory on the heap that has no reference. In some cases this may not be immediate and in fact the GC may reclaim some unreferenced memory and not other unreferenced memory. Many times the GC is only activated when the amount of unassigned heap memory is below a certain amount. To assist the GC in the process of reclaiming unreferenced heap memory, the class Object has a method called Finalize(). It is also possible for the programmer to define either an overloaded Finalize() method or the destructor method. The destructor performs its tasks and then calls the Object's Finalize() method that in turn calls the GC to return the heap memory used by the object. A programmer defined Finalize() method is mainly used for unmanaged code. Since there will be no further discussion of unmanaged code in this course, the properties of the Finalize() method will not be discussed in these notes. It is recommended that the student read about this method in case its use is required in a program being written once in the work place. As with constructors, the compiler will define a destructor implicitly if the programmer does not define one explicitly in the class definition. The Finalize() method and the GC provide many of the features of a destructor in C++ and therefore in C#, a destructor is notrequired as much as it is in C++. In C# the destructor may provide for services that the garbage collector does not, e.g., the closing of files or the closing of network connections. If a program is working over a network, a destructor is recommended because the GC will not handle all of the system's needs in this case. In general, it is recommended for most programs that the programmer not define a destructor. The characteristics of a destructor are that: ●
it has the same name as class preceded with ~
●
it has no return data type not even void
●
it has only a void signature
●
it has no access specifier and is public by default.
●
there is only one per class
●
it is created implicitly by the compiler if one is not defined explicitly in the code
●
it should never be called explicitly and is called automatically when the reference to an object leaves scope and then calls the Object's Finalize() method which in turn calls the GC to reclaim the heap memory
For example see the file pair: viewDestructor.cs and ConstructorDestructor.cs. In this example notice when the constructor and the destructor are called with relationship to the starting and the ending of the program. Using the following statements in a program can help to force the GC to reclaim the heap memory for objects that have been dereferenced: // force grabage collection System.GC.Collect(); // wait until garbage collection completes System.GC.WaitForPendingFinalizers();
For example see the following pair that use the statements above:
file:///D|/1/final/BBL0037.html (5 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties ●
Employee.cs
●
StaticTest.cs
Overloaded Methods In the discussion above, overloaded functions were defined as functions within the same scope that have the same name but have different argument data types or a different order of the arguments. Methods are within the same scope namely the class' scope. Therefore if two different methods have the same name but have different signatures then they are called overloaded methods. For example in file: theBANK4.cs, the class BankAccount is defined with both of the following constructors: BankAccount() { theAmount = 0.00; } BankAccount(float startingAmount) { theAmount = startingAmount; }
When objects are defined, their definitions can use either one of these constructors. For example when the objects checkingAccount and savingsAccount were created in viewBANK4.cs, it was done like the following: BankAccount checkingAccount = new BankAccount(); BankAccount savingsAccount = new BankAccount(5000);
In the first case the default constructor initialized checkingAccount to $0.00 while the second definition used the constructor with an argument to initialize savingsAccount to $5000.00. theBANK4.cs is an example of using overloading because the constructor methods both have the same name yet they have different arguments. The arguments are different because the first constructor has a void argument and the second has an argument list consisting of one argument of type float. Static Methods These methods can access only the static fields. They can only be called by the class as in the following: TheClass.theStaticMethod();
A static method has no this reference since they are independent of any class object. They are defined as in the following: static theStaticMethod(signature) { ..... }
Static methods are usually used to manipulate the static fields although the static fields may also be manipulated by non-static methods as well. As seen above, static constructors may be used to initialize static fields. See staticConstructor.cs.
file:///D|/1/final/BBL0037.html (6 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
The UML chart for the class TheAccount used in this example:
Copy Constructors A copy constructor is a method that copies the values of the fields of one class object into the fields of another object of the class. In C++ the compiler provides each class with a copy constructor. However in C++ there are times in which defining a copy constructor was necessary. In C# each class needs a copy constructor and it must be explicitly defined by the programmer if one is needed. In fact, it is a good idea to always define one for each class. For example suppose TheClass had a copy constructor. Its general form would be like the following: public TheClass(TheClass anObject) { ..... }
Then if firstObject is an object of TheClass, the secondObject could be defined and initialized by the following statement: TheClass secondObject = new TheClass(firstObject);
or TheClass secondObject = new TheClass(); secondObject = firstObject;
For an example see copy.cs Overriding the ToString() Method for a Class As mentioned previously, every class in C# is derived from the System class Object. One of the methods in the class: Object is ToString(). This converts the objects of the class Object or objects of other classes to strings. It is therefore possible and recommended to override this method for each class you define to help formatting the output of a class' objects. For example the following method achieves this objective for the class bankAcount: public override string ToString() file:///D|/1/final/BBL0037.html (7 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
{ return("Account ID: " + accountID.ToString() + "\nAccount Name: " + accountName.ToString() + "\nAccount Balance: $" + balanceAmount.ToString()); }
Notice the use of the keyword: override in the definition above. For a full implementation of this concept, see: classToString.cs. A UML chart for this class is the following:
The this Reference In C++ each non-static method had a this pointer which would contain the address of the calling object. C# has something similar. In C# each non-static method contains a this reference that contains the address of the calling object. There are four major uses of the this reference. They are: ●
to enable easier access within the method to storing values into the fields of the calling object. For example
this.amount = amount;
could be used in a method definition when both the field and the argument have the name: amount. Notice that the dot operator is used with this above rather than the arrow operator as was done in C++ with its this operator. For an example see this1.cs ●
to enable output of the calling object from within the method as in
return this;
For an example see this2.cs ●
to enable the calling object to be an argument of a method being called within the body of a method as in.
theMethod(this);
For an example see this3.cs ●
to enable the definition of overloaded constructors as in the following:
public theCustomer():this("","",0.00)
file:///D|/1/final/BBL0037.html (8 von 9) [01.12.2007 04:48:18]
Class Methods and Field Properties
{} public theCustomer(double theAmount):this("","",theAmount) {} public theCustomer(string Name,string ID, double Balance) { this.Name = Name; this.ID = ID; this.Balance = Balance; }
For an example see this4.cs.
file:///D|/1/final/BBL0037.html (9 von 9) [01.12.2007 04:48:18]
Using Classes in C# Programs
Using Classes in C# Programs There are three main approaches to including classes into a C# program. They include the following: ●
define the class within the namespace of the main project but outside of the class' definition of the program that contains Main().
●
define the class within a separate file attached to the program's project either using the same namespace as the program or having its own namespace which is therefore used in the program.
●
define the class within a .dll library and then attach the .dll to the program's project.
Any of these approaches could use the partial class modifier. Using Separate Files for the Class Definition and the Program The first approach was used in the examples earlier in the lecture. The following examples show the second approach. Download each of the following pairs of files (be careful to add the .cs extension to each file): ●
viewClock.cs and Clock1.cs
●
viewCircles.cs and Circle.cs
●
viewPrivateFunctions.cs and theDate.cs
Create a project for each of these pairs of files. Once the project is created, redefined the default .cs file and add each of the files in the pair. The class file should be added as a class. After each pair has been added to its respective solution, compile and run the programs. Next look at each program and observe how the classes are defined, how the objects are defined, what type of methods each uses and how the programs work in general. Notice in the first example that the two files used the same namespace. However in the second example, each file had a different namespace so the program viewCircles.cs had to add an additional using statement. Notice that the classes in the examples above are defined as public. Recall that if a class has no access modifier then it is therefore internal by default. After you have experimented with the above examples, remove the public access specifier for one of the classes and see if the program still compiles. Using Dynamic Linked Libraries (DLL) in a Program When writing programs with classes, the class definition file may be compiled into a .dll (dynamic linked library) file. The dynamic linked library is created at the beginning when the solution is compiled. When defining a .dll, instead of selecting either Windows Application or Console Application, select Class Library. Once the classes have been added to the library, compile the file into a .dll. Then when the program is created that will use the library class, add the .dll by using the Reference Add feature. One last step is to include a using with the class' namespaces (used in the .dll) at the top of the program if the program's namespace is different. Note: When doing this on the job, you should create a dll library folder and after compiling each dll, copy it to the company's component library folder. Using one of the example pairs above, turn the class file into a .dll and add it to the program to see how this feature works. To create .dll file use the following steps: 1. If a dll is used, do the following: i. Create a project using either the same namespace as the program's or a different namespace from the program. (Use the latter approach if the class is to be used for other programs.)
file:///D|/1/final/BBL0038.html (1 von 2) [01.12.2007 04:48:19]
Using Classes in C# Programs
ii. To create the project select C# Program and Class Library. iii. After the class has been defined, build it. Be sure to use the Release version of the build. This creates a file with a dll extension. (Be sure to include the following highlighted code: [Serializable] before the class' definition in the project which may be needed if the classes are going to be used with binary file I/O to be discussed later.) iv. If the class project had a different namespace than the program, create a using statement at the top of the program's code and include the class' namespace name. v. In the program's project select the Solution Explorer and right click on the References' option. vi. Select Add References. vii. When the Add References dialog box appears, select the Browse button and find the class's dll file. viii. Once the class dll has been selected, its name should appear in the Add Reference's dialog box. When this happens, double click on the dll's name and then click the OK button to add the dll to the project's references. ix. The dll has now been added to the program and its contents are now ready to be used by the program. x. If the + sign on the References option of the Solution Explorer is clicked, the name of the dll should appear with the other dlls. 2. If the class is to be part of the program's project as a secondary file, do the following: i. In the Solution Explorer right click on the name of the project. ii. Click on the Add option of the popup menu. iii. If the class's file has already been created, select Add Existing Item and add the file. iv. If the class's file has not been created, select Add New Item and then create the class' definition. After the definition has been created, return to the project file to continue coding. Now create some examples using the partial class modifier. Separate the class definition from the method definitions in different files. Using these separate files, create a .dll file. Using this .dll recompile the program and compare this implementation with the ones above. It is recommended that all of the .dll files be placed into a company component library folder e.g. on a computer that all company programmers would have access to anywhere in the world e.g. on a secure internal network server or accessible through a secure link to an Internet server.
file:///D|/1/final/BBL0038.html (2 von 2) [01.12.2007 04:48:19]
Accessing Class Objects in a Windows Program
Accessing Class Objects in a Windows Program Specifications: Boynton Hauling Lines of Boynton Beach, Florida needs a program that will prepare a shipping manifest which is to be stored to disk. When the program begins, it should seek the truck number and the maximum weight limit of the truck and then store this information in memory to be used as the program progresses. The truck number is to be used to name the file into which the shipping information for each item will be stored. The maximum weight limit of the truck is to be used to limit the items to be shipped. This information is stored in memory by using a button. After the truck items have been entered, the user is provided the opportunity to enter the shipping information for each item that is to be shipped on this truck. The shipping information is to include: the weight of the item, the customer's name, the customer's address, the customer's city, the customer's state and the customer' zip code. As each item to be shipped by the truck is entered, the program should first determine whether the weight of the item added to the weight of each previous entered items does not exceed the maximum weight limit of the truck. This is accomplished by pressing a button. If the weight of the item plus the weight of the items previously entered exceeds the maximum weight limit, the user is provided with a warning and the data is not saved. In this case the user is given the opportunity to try another item or to end the program. If the weight of the item plus the weight of the items previously entered items does not exceed the maximum weight limit of the truck, then the shipping information may be entered. Once the shipping information is entered, the user clicks a button and it is stored to a text file whose name shall be the truck number. The program shall continue until the user decides to exit. Note: The printing of the shipping manifest will be provided by a different program later in the lectures. The screen should look like the following:
The BHL business analyst has decided that the program should be a Windows GUI program written in C#. The file:///D|/1/final/BBL0039.html (1 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
form should have text boxes and labels for each of the following items: ●
truck number
●
truck weight limit
●
sum of weight of previously entered items
●
item weight
●
customer name
●
customer address
●
customer city
●
customer state
●
customer zip
The form should have three buttons for the following purposes: ●
Store Truck Information
●
Check Item Weight
●
Store Item Information
The program should begin by having all of the text boxes cleared except for the sum of weight list box which should begin with the value: 0.00. The text boxes for the truck number and the truck weight limit should be available for data entry when the program begins. All of the other list boxes should be read only at the beginning. In addition the Store Truck Information button should be available for clicking but the other two buttons should not be available at this point. The truck number is to be used to name the text file where the data is to be stored. Once the above conditions are met, the cursor should move to the truck number list box for data entry so that the user may enter the two truck information values. Once the truck information has been entered, the user should click the Store Truck Information button. The clicking of this button stores the truck information into memory. The two text boxes for the truck information entry are then changed to read only. The cursor is to then move to the item weight list box to become available for data entry. When the truck values have been entered, the user is to enter the item weight and then click the Check Item Weight button to determine the sum of the weight of the items entered previously plus the weight of the new item. If the sum of the items previously entered added to the item weight of the new item is over the truck limit, a MessageBox with a warning message should appear. After the warning message disappears, the item weight list box is cleared and the cursor moves back to that list box. In this case the user may again enter a different item or end the program. If the sum of the items previously entered added to the item weight of the new item is below the truck limit, the item weight list box becomes read only and the item weight is added to the sum of weight. The new value of the sum of the weight is then displayed in its list box. The remaining list boxes for the customer information become available for new data entry, After the customer information has been entered, the user may click the Store Item Information button. When this button is clicked, the customer information values are stored in the text file. This is then followed by clearing the customer information list boxes and changing them to read only. After this has been accomplished, the cursor is moved to the item weight text box. Next this list box is changed to become available for entry of another item. At this point the user may again enter another item or end the program. The printing of the shipping manifest will be provided by another program.
file:///D|/1/final/BBL0039.html (2 von 8) [01.12.2007 04:48:20]
Accessing Class Objects in a Windows Program
Design: The program is to be based upon the class: Shipments. The following is the UML chart for the class:
This following is the pseudo code to describe the program's actions: TruckInfo Set Shipments.TruckNumber = truckNumber Set Shipments.TruckWeight = weightLimit Set Shipments.WeightEntered = 0.00; Set truckNumber and weightLimit so that the tab does not stop there Set truckNumber and weightLimit so that no data will apear there SetTruckInfo to be invisible and not to be a tab stop Set itemWeight to be read only, the focus and not to be a tab stop Set checkWeight to permit the tab to stop, to be visible and to accept data End
and checkWeight IF (itemWeight + Shipments.WeightEntered =60) { seconds -= 60; ++minutes; } if (minutes >=60) { minutes -= 60; ++hours; } if (hours >=24) {
file:///D|/1/final/BBL0041.html (15 von 38) [01.12.2007 04:48:26]
Lecture 4 Examples
hours = 0; } } public void displayClock() { int counter; string hours_zero, minutes_zero, seconds_zero; if (hours 12) ? (1) : (value); } } public int Day { get
file:///D|/1/final/BBL0048.html (28 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ return theDay; } set { theDay = (value < 1 || value > 31) ? (1) : (value); } } public int Year { get { return theYear; } set { theYear = value; } } public override string ToString() { // The following is an array of strings. Arrays // will be discussed in a later lecture. // string[] monthName = {"","JANUARY","FEBRUARY","MARCH", "APRIL", "MAY","JUNE","JULY","AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER","DECEMBER"}; if (Year < 10) { Year += 2000; } else if (Year < 100) { Year += 1900; } return ("\n\n" + monthName[Month] + " " + Day + ", " + Year + "\n\n"); } // Notice the definition of the class: Drawdate which is // nested inside of the class theDate. // internal class DrawDate { public void Drawing(theDate d) { Console.WriteLine("Drawing the month {0}", d.Month); Console.WriteLine("Drawing the day {0}", d.Day); Console.WriteLine("Drawing the year {0}", d.Year); } } } class theProgram { static void Main(string[] args) { theDate aDate = new theDate(); Console.Write("What is the month? "); aDate.Month = int.Parse(Console.ReadLine()); Console.Write("What is the day? "); aDate.Day = int.Parse(Console.ReadLine()); Console.Write("What is the year? "); aDate.Year = int.Parse(Console.ReadLine()); Console.WriteLine("\n\n"); Console.WriteLine("The date is {0}", aDate.ToString()); Console.WriteLine("\n\n"); // Notice that the instance newDate is defined to be
file:///D|/1/final/BBL0048.html (29 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// an instance of the class DrawDate which is nested // inside of the class: theDate. // theDate.DrawDate newDate = new theDate.DrawDate(); newDate.Drawing(aDate); Console.WriteLine("\n\n"); Console.ReadKey(); } } }
// program_id People.cs // written_by don voils // date_written 7/13/2006 // description This file contains the definition of // the class People. // namespace thePeople { class People { private string accountNumber; private string name; private string address; private string city; private string state; private string zip; public string Number { get { return accountNumber; } set { accountNumber = value; } } public string Name { get { return name; } set { name = value; } } public string Address { get { return address; } set { address = value; } } public string City { get { return city; } set { city = value; }
file:///D|/1/final/BBL0048.html (30 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} public string State { get { return state; } set { state = value; } } public string Zip { get { return zip; } set { zip = value; } } } }
// program_id Form1.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using thePeople; using theBilling; namespace SEATBilling { public partial class Form1 : Form { private Billing theClient; public Form1() { InitializeComponent(); theCharge.ReadOnly = true; theCharge.TabStop = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); } // This event handler prints the data and then clears the form // private void printBill_Click(object sender, EventArgs e) { // printing of theClient goes here. // accountNumber.Text = ""; theName.Text = ""; theAddress.Text = ""; theCity.Text = ""; theState.Text = ""; theZip.Text = ""; theMonth.Text = ""; theDay.Text = ""; theYear.Text = "";
file:///D|/1/final/BBL0048.html (31 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
theTransaction.Text = ""; theLawyer.Text = ""; theDescription.Text = ""; theRate.Text = ""; theHours.Text = ""; theCharge.Text = ""; accountNumber.ReadOnly = false; theName.ReadOnly = false; theAddress.ReadOnly = false; theCity.ReadOnly = false; theState.ReadOnly = false; theZip.ReadOnly = false; theMonth.ReadOnly = false; theDay.ReadOnly = false; theYear.ReadOnly = false; theTransaction.ReadOnly = false; theLawyer.ReadOnly = false; theDescription.ReadOnly = false; theRate.ReadOnly = false; theHours.ReadOnly = false; checkCharge.Visible = true; printBill.Visible = false; accountNumber.Focus(); } // This event handler stores the data into the object // calculates the fee and then changes the status // of the textboxes. // private void checkCharge_Click(object sender, EventArgs e) { theClient = new Billing(Int32.Parse(theMonth.Text),Int32.Parse(theDay.Text),Int32.Parse(theYear.Text)); theClient.Number = accountNumber.Text; theClient.Name = theName.Text; theClient.Address = theAddress.Text; theClient.City = theCity.Text; theClient.State = theState.Text; theClient.Zip = theZip.Text; theClient.TransactionNumber = theTransaction.Text; theClient.Lawyer = theLawyer.Text; theClient.Description = theDescription.Text; theClient.HourlyRate = double.Parse(theRate.Text); theClient.HoursServed = double.Parse(theHours.Text); theCharge.Text = string.Format("{0:c}", (theClient.HoursServed * theClient.HourlyRate)); accountNumber.ReadOnly = true; theName.ReadOnly = true; theAddress.ReadOnly = true; theCity.ReadOnly = true; theState.ReadOnly = true; theZip.ReadOnly = true; theMonth.ReadOnly = true; theDay.ReadOnly = true; theYear.ReadOnly = true; theTransaction.ReadOnly = true; theLawyer.ReadOnly = true; theDescription.ReadOnly = true; theRate.ReadOnly = true; theHours.ReadOnly = true; printBill.Visible = true; printBill.Focus(); checkCharge.Visible = false; } } }
// program_id Form1.Designer.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // namespace SEATBilling
file:///D|/1/final/BBL0048.html (32 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
{ partial class Form1 { /// <summary> /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.accountNumber = new System.Windows.Forms.TextBox(); this.theName = new System.Windows.Forms.TextBox(); this.theAddress = new System.Windows.Forms.TextBox(); this.theCity = new System.Windows.Forms.TextBox(); this.theState = new System.Windows.Forms.TextBox(); this.theZip = new System.Windows.Forms.TextBox(); this.theMonth = new System.Windows.Forms.TextBox(); this.theDay = new System.Windows.Forms.TextBox(); this.theYear = new System.Windows.Forms.TextBox(); this.theTransaction = new System.Windows.Forms.TextBox(); this.theLawyer = new System.Windows.Forms.TextBox(); this.theDescription = new System.Windows.Forms.TextBox(); this.theHours = new System.Windows.Forms.TextBox(); this.theRate = new System.Windows.Forms.TextBox(); this.printBill = new System.Windows.Forms.Button(); this.label13 = new System.Windows.Forms.Label(); this.theCharge = new System.Windows.Forms.TextBox(); this.checkCharge = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(35, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(127, 17); this.label1.TabIndex = 0; this.label1.Text = "Account Number"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(35, 60);
file:///D|/1/final/BBL0048.html (33 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(49, 17); this.label2.TabIndex = 1; this.label2.Text = "Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(35, 90); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 17); this.label3.TabIndex = 2; this.label3.Text = "Address"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(35, 120); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(35, 17); this.label4.TabIndex = 3; this.label4.Text = "City"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(35, 150); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(46, 17); this.label5.TabIndex = 4; this.label5.Text = "State"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(35, 180); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(31, 17); this.label6.TabIndex = 5; this.label6.Text = "Zip"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(35, 270); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(59, 17); this.label7.TabIndex = 6; this.label7.Text = "Lawyer"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(35, 210); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(246, 17); this.label8.TabIndex = 7; this.label8.Text = "Transaction Date (MM/DD/YYYY)"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(35, 240); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(155, 17); this.label9.TabIndex = 8; this.label9.Text = "Transaction Number"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(35, 300); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(90, 17); this.label10.TabIndex = 9;
file:///D|/1/final/BBL0048.html (34 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.label10.Text = "Description"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(35, 330); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(107, 17); this.label11.TabIndex = 10; this.label11.Text = "Hours Served"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(35, 360); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(94, 17); this.label12.TabIndex = 11; this.label12.Text = "Hourly Rate"; // // accountNumber // this.accountNumber.Location = new System.Drawing.Point(220, 30); this.accountNumber.Name = "accountNumber"; this.accountNumber.Size = new System.Drawing.Size(100, 22); this.accountNumber.TabIndex = 1; // // theName // this.theName.Location = new System.Drawing.Point(220, 60); this.theName.Name = "theName"; this.theName.Size = new System.Drawing.Size(100, 22); this.theName.TabIndex = 2; // // theAddress // this.theAddress.Location = new System.Drawing.Point(220, 90); this.theAddress.Name = "theAddress"; this.theAddress.Size = new System.Drawing.Size(190, 22); this.theAddress.TabIndex = 3; // // theCity // this.theCity.Location = new System.Drawing.Point(220, 120); this.theCity.Name = "theCity"; this.theCity.Size = new System.Drawing.Size(100, 22); this.theCity.TabIndex = 4; // // theState // this.theState.Location = new System.Drawing.Point(220, 150); this.theState.Name = "theState"; this.theState.Size = new System.Drawing.Size(100, 22); this.theState.TabIndex = 5; // // theZip // this.theZip.Location = new System.Drawing.Point(220, 180); this.theZip.Name = "theZip"; this.theZip.Size = new System.Drawing.Size(100, 22); this.theZip.TabIndex = 6; // // theMonth // this.theMonth.Location = new System.Drawing.Point(285, 210); this.theMonth.Name = "theMonth"; this.theMonth.Size = new System.Drawing.Size(26, 22); this.theMonth.TabIndex = 7; // // theDay // this.theDay.Location = new System.Drawing.Point(320, 210); this.theDay.Name = "theDay"; this.theDay.Size = new System.Drawing.Size(26, 22);
file:///D|/1/final/BBL0048.html (35 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
this.theDay.TabIndex = 8; // // theYear // this.theYear.Location = new System.Drawing.Point(355, 210); this.theYear.Name = "theYear"; this.theYear.Size = new System.Drawing.Size(55, 22); this.theYear.TabIndex = 9; // // theTransaction // this.theTransaction.Location = new System.Drawing.Point(220, 240); this.theTransaction.Name = "theTransaction"; this.theTransaction.Size = new System.Drawing.Size(100, 22); this.theTransaction.TabIndex = 10; // // theLawyer // this.theLawyer.Location = new System.Drawing.Point(220, 270); this.theLawyer.Name = "theLawyer"; this.theLawyer.Size = new System.Drawing.Size(100, 22); this.theLawyer.TabIndex = 11; // // theDescription // this.theDescription.Location = new System.Drawing.Point(220, 300); this.theDescription.Name = "theDescription"; this.theDescription.Size = new System.Drawing.Size(190, 22); this.theDescription.TabIndex = 12; // // theHours // this.theHours.Location = new System.Drawing.Point(220, 330); this.theHours.Name = "theHours"; this.theHours.Size = new System.Drawing.Size(100, 22); this.theHours.TabIndex = 13; this.theHours.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // theRate // this.theRate.Location = new System.Drawing.Point(220, 360); this.theRate.Name = "theRate"; this.theRate.Size = new System.Drawing.Size(100, 22); this.theRate.TabIndex = 14; this.theRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // printBill // this.printBill.Location = new System.Drawing.Point(308, 445); this.printBill.Name = "printBill"; this.printBill.Size = new System.Drawing.Size(102, 23); this.printBill.TabIndex = 17; this.printBill.Text = "Print Bill"; this.printBill.UseVisualStyleBackColor = true; this.printBill.Click += new System.EventHandler(this.printBill_Click); // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(35, 390); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(102, 17); this.label13.TabIndex = 16; this.label13.Text = "Total Charge"; // // theCharge // this.theCharge.Location = new System.Drawing.Point(220, 394); this.theCharge.Name = "theCharge"; this.theCharge.Size = new System.Drawing.Size(100, 22); this.theCharge.TabIndex = 15; this.theCharge.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // checkCharge
file:///D|/1/final/BBL0048.html (36 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// this.checkCharge.Location = new System.Drawing.Point(38, 445); this.checkCharge.Name = "checkCharge"; this.checkCharge.Size = new System.Drawing.Size(175, 23); this.checkCharge.TabIndex = 16; this.checkCharge.Text = "Check Total Charge"; this.checkCharge.UseVisualStyleBackColor = true; this.checkCharge.Click += new System.EventHandler(this.checkCharge_Click); // // Form1 // this.ClientSize = new System.Drawing.Size(455, 487); this.Controls.Add(this.checkCharge); this.Controls.Add(this.theCharge); this.Controls.Add(this.label13); this.Controls.Add(this.printBill); this.Controls.Add(this.theRate); this.Controls.Add(this.theHours); this.Controls.Add(this.theDescription); this.Controls.Add(this.theLawyer); this.Controls.Add(this.theTransaction); this.Controls.Add(this.theYear); this.Controls.Add(this.theDay); this.Controls.Add(this.theMonth); this.Controls.Add(this.theZip); this.Controls.Add(this.theState); this.Controls.Add(this.theCity); this.Controls.Add(this.theAddress); this.Controls.Add(this.theName); this.Controls.Add(this.accountNumber); this.Controls.Add(this.label12); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.Name = "Form1"; this.Text = "SEAT Monthly Billing"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox accountNumber; private System.Windows.Forms.TextBox theName; private System.Windows.Forms.TextBox theAddress; private System.Windows.Forms.TextBox theCity; private System.Windows.Forms.TextBox theState; private System.Windows.Forms.TextBox theZip; private System.Windows.Forms.TextBox theMonth; private System.Windows.Forms.TextBox theDay; private System.Windows.Forms.TextBox theYear; private System.Windows.Forms.TextBox theTransaction; file:///D|/1/final/BBL0048.html (37 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
private System.Windows.Forms.TextBox theLawyer; private System.Windows.Forms.TextBox theDescription; private System.Windows.Forms.TextBox theHours; private System.Windows.Forms.TextBox theRate; private System.Windows.Forms.Button printBill; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox theCharge; private System.Windows.Forms.Button checkCharge; } }
// program_id Program.cs // written_by don voils // date_written 7/14/2006 // description This file is part of the program: SEATBilling.exe // using System; using System.Collections.Generic; using System.Windows.Forms; namespace SEATBilling { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
// program_id theAbstract1.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how an abstract // class and method can be defined as // well as how to derive a class from the // abstract class. If the keyword: override // is removed from the definition of the // method show() in the derived class, // the program will not compile. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort;
file:///D|/1/final/BBL0048.html (38 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} override public short show() { return theDerivedMember; } } static void Main() { theDerived theDerivedReference = new theDerived(1, 2); Console.WriteLine("The value of theBaseMember is {0}.\n\n", theDerivedReference.show()); Console.ReadKey(); }
}
// program_id theAbstract2.cs // written by don voils // date_written 10/3/2006 // Descriptioin This program shows how an abstract // class and method can be defined as // well as how to derive a class from a class // that is derived from an abstract class. // In this case, this second derived class // does not have to override the base class' // abstract method. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort): base(firstShort) { theDerivedMember = secondShort; } override public short show() { return theDerivedMember; } } public class nextDerived : theDerived { private short theNextDerivedMember; public nextDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { theNextDerivedMember = thirdShort; } public short showNextDerived() { return theNextDerivedMember; } }
file:///D|/1/final/BBL0048.html (39 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
static void Main() { nextDerived theReference = new nextDerived(1, 2, 3); Console.WriteLine("The value of theNextDerivedMember is {0}.\n\n", theReference.show()); Console.ReadKey(); }
}
// program_id theAbstract3.cs // written by don voils // date_written 10/3/2006 // Descriptioin This program shows how an abstract // class and method can be defined as // well as how to derive a class from a class // that is derived from an abstract class. // In this case, a second derived class // is derived from the first derived class. // In this program a reference to the abstract // base class is used to access methods of // each of the derived classes as if it was // a reference to the respecitive classes. // Without this base class being abstract, // this reference would have been forced to // access the base class' method which would // have been impossible because it is in turn // abstract. // using System; class theProgram { abstract public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } abstract public short show(); } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } override public short show() { return theDerivedMember; } } public class nextDerived : theDerived { private short theNextDerivedMember; public nextDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { theNextDerivedMember = thirdShort; } override public short show() { return theNextDerivedMember;
file:///D|/1/final/BBL0048.html (40 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
} } static void Main() { theDerived theDerivedReference = new theDerived(4, 5); theBase theBaseReference = theDerivedReference; Console.WriteLine("The value of theDerivedMember is {0}.\n", theBaseReference.show()); nextDerived theNextDerivedReference = new nextDerived(1, 2, 3); theBaseReference = theNextDerivedReference; Console.WriteLine("The value of theNextDerivedMember is {0}.\n\n", theBaseReference.show()); Console.ReadKey(); } }
// program_id theReference1.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how references to a base // class can be used to access the base class // part of an object of the derived class. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } static void Main() { theBase theBaseReference; theDerived theDerivedReference = new theDerived(1, 2); theBaseReference = theDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n", theBaseReference.show_theBase());
file:///D|/1/final/BBL0048.html (41 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
// // The following line will not compile. Why? // // Console.WriteLine("The value of theDerivedMember is {0}.\n", // theBaseReference.show_theDerived()); Console.WriteLine("\n\n"); Console.ReadKey(); }
}
// program_id theReference2.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows how references to a base // class can be used to access the base class // part of an object of a class that is derived from a // class that is derived from the base. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } public class anotherDerived : theDerived { private short anotherDerivedMember; public anotherDerived(short firstShort, short secondShort, short thirdShort) : base(firstShort, secondShort) { anotherDerivedMember = thirdShort; } public short show_anotherDerived() { return anotherDerivedMember; } } static void Main() { theBase theBaseReference; theDerived theDerivedReference = new theDerived(1, 2);
file:///D|/1/final/BBL0048.html (42 von 43) [01.12.2007 04:48:36]
Lecture 5 Examples
theBaseReference = theDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n", theBaseReference.show_theBase()); anotherDerived anotherDerivedReference = new anotherDerived(5, 6, 7); theBaseReference = anotherDerivedReference; Console.WriteLine("The value of theBaseMember is {0}.\n\n", theBaseReference.show_theBase()); Console.ReadKey(); }
}
// program_id theReference3.cs // written by don voils // date_written 10/3/2006 // Descriptioin The program shows that a reference to // a derived class may not be used to reference // a base class object. // using System; class theProgram { public class theBase { private short theBaseMember; public theBase(short theShort) { theBaseMember = theShort; } public short show_theBase() { return theBaseMember; } } public class theDerived : theBase { private short theDerivedMember; public theDerived(short firstShort, short secondShort) : base(firstShort) { theDerivedMember = secondShort; } public short show_theDerived() { return theDerivedMember; } } static void Main() { theBase theBaseReference = new theBase(2); theDerived theDerivedReference; theDerivedReference = theBaseReference; Console.WriteLine("\n\n"); Console.ReadKey(); }
}
file:///D|/1/final/BBL0048.html (43 von 43) [01.12.2007 04:48:36]
Lecture 6: Operator Overloading
Lecture 6: Operator Overloading Definition of Operator Overloading Up to this point in C# the programmer could define operations on structure instances and class objects by using a function. For example: c = add(a,b);
where a, b and c are instances of one of the system data types, of a structure or of a class reference. However, this is using non-standard operators. C# as with C++ permits the programmer to use some of the standard operators in a more natural way using what is called: operator overloading. As with C++, the programmer should take care how these operators are defined and these defined operators should model the real world. The approach to this subject in C# is slightly different from the C++ approach. To define operator overloading on class objects requires that the operator: ●
is a system operator.
●
maintains the system order of precedence
●
can not change type: i.e. between unary and binary operators
●
is static and therefore may not use this in the definitions (also may not be virtual, override nor sealed).
●
must be a class method.
●
must have at least one of the parameters an object of the class
●
has in the operator's definition the keyword: operator
Notice the main differences between C# and C++ is that all of the operators in C# are public and static class methods. While this is true, operators may not be virtual, abstract, override or sealed. The permissible operators for overloading are:
Open table as spreadsheet OVERLOADABLE OPERATORS +
-
*
/
%
^
&
|
~
!
>=
=
>
arraySort[i + 1]) { Swap(arraySort, i);
file:///D|/1/final/BBL0070.html (2 von 3) [01.12.2007 04:48:56]
System.Array Class
} } } } public void Swap(int[] arraySwap, int index) { int temp; temp = arraySwap[index]; arraySwap[index] = arraySwap[index + 1]; arraySwap[index + 1] = temp; }
The Bubble Sort is easy to code but it runs slow which causes a serious problem when sorting large arrays. The .NET Framework includes a built-in Sort() method that implements a high-speed sort. Instead of writing the BubbleSort() and the Swap() methods, the Array class' static method Sort() can be called and an array can be passed as an argument like in the following. Array.Sort(theArray);
For an example see sort1.cs. In this example, note that there was no need for an explicit type conversion from an array of System.Object to an array of integers to do the sort.
Searching Arrays: Linear Search A linear search will loop through an array until it finds the value being searched for. If you have 100 elements in the array and the value you are looking for is the 98th element, the search will make 98 comparisons. A linear search works well for small or unsorted arrays. See search1.cs.
Searching Arrays: Binary Search A binary search uses a divide and conquers approach. It is an efficient, high-speed technique that works well on large sorted arrays. The binary search eliminates half the array elements being searched after each comparison. Again, if the element you are searching for is the 98th element, the binary search will only need to make 6 comparisons. The .NET Framework includes a built-in BinarySearch() method that implements a high-speed search on sorted arrays. Instead of writing a binary search method, the program should call the Array class' static method BinarySearch(). This method is overloaded. One of the implementations has as one of the arguments the array to be searched and the other argument is the value being searched for. The method returns the position in the array it found the value searched for. If it was not found, then a negative number is returned. As in the following: thePosition = Array.BinarySearch(theSearchedArray,theValuetoFind);
For an example, see: search2.cs. This was an example using an array with numbers as elements. It is also possible to use these same Array methods with arrays of strings. See search3.cs.
file:///D|/1/final/BBL0070.html (3 von 3) [01.12.2007 04:48:56]
Initialization and Assignment of Arrays
Initialization and Assignment of Arrays Initialization of Array Elements The elements of arrays can be assigned values as the program runs as in the following: string[] employeeName = new string[100]; employeeName[0] = "George Washington"; employeeName[1] = "Thomas Jefferson"; employeeName[2] = "John Adams"; employeeName[3] = "Theodore Roosevelt"; employeeName[4] = "Abraham Lincoln"; …
followed by Console.WriteLine("The name of the first US President was {0}.", employeeName[0]);
as was done in the example: search3.cs. Instead arrays can be initialized when used in loops as in the following: decimal[] unitPrice = new decimal[10]; for(int index=0; index < 10;++index) { Console.Write("\nWhat is the unit price of unit {0}? ", index+1); unitPrice[index] = Decimal.Parse(Console.ReadLine()); }
and then these lines could be followed with code like the following: decimal totalPrice = 0.00M; Console.WriteLine("\tItem\tPrice"); for(int index=0; index < unitPrice.Length;++index) { Console.WriteLine("\t{0}\t{1:c} ",index+1, unitPrice[index]); totalPrice += unitPrice[index]; } Console.WriteLine("\n\tTotal\t{0:c}",totalPrice);
See array1.cs
Assignment and Arrays Suppose that two arrays are defined of the string type and the same size as in the following examples: string[] employeeName = new string[5]; file:///D|/1/final/BBL0071.html (1 von 2) [01.12.2007 04:48:56]
Initialization and Assignment of Arrays
string [] employeeName2 = new string[5];
Further assume that the array emploiyeeName is initialized and then the code contains the following statement: employeeeName2 = employeeName;
When this assignment is made all of the values for the elements of employeeName have been assigned to be the values of the elements of the array employeeName2 Next suppose that the elements of the array employeeName2 are changed. The question should be what happens to the values of the elements of the first array. The answer is that the values of the first array are also changed. For example see: employeeName1.cs So the last example had arrays of the string type. The question should then arise as to whether using arrays: employeeNumber and employeeNumber2 to be arrays of the system data types, would this make a difference? The answer is no. That is if non-string array: employeeNumber is assigned to the non-string array employeeNumber2 and the elements of employeeNumber2 are changed, then the elements of the array employeeNumber are changed as well. See employeeNumber1.cs What should be done instead of using assignment is to use the CopyTo() method of the Array class. See employeeNumber2.cs. Notice in this case the elements of the two arrays are different places in memory because if the values of the elements of one array are changed, then the values of the elements of the other array are not changed. Instead of the method: CopyTo() the static method Copy() could be used instead.
file:///D|/1/final/BBL0071.html (2 von 2) [01.12.2007 04:48:56]
List Definition and Initialization of Arrays
List Definition and Initialization of Arrays As in C++ an array may be defined with a list of the element values. However the C# code is slightly different. For example the traditional array definition may be followed by the list as in the following: int[] theUnitNumbers = new int[6] {23, 42, 123, 42, 13, 123};
This definition would define the array referenced by theUnitNumbers that contains the values 23, 42, 123, 42, 12 and 123 respectively. Note: Unlike C++, when a list definition is used, then the size of the array must be the same as the number of values in the list definition or a compiler error occurs. There is another approach to using a list definition. The list may appear without the new statement as in the following: decimal[] thePrices = {34.23m, 532.43m, 335.45m, 625.34m};
This statement would define the array: thePrices with four decimals elements with the values: 34.23, 523.43, 335.45 and 625.34 respectively. The size of the array: thePrices is calculated from the number of elements in the specified list. For an example of each of the definitions above see list1.cs The example above demonstrated list definition using int and decimal arrays. It is also possible to have a string array with a list definition as in the following: string[] employeeName = { "George Washington", "Thomas Jefferson", "John Adams","Theodore Roosevelt", "Abraham Lincoln"};
Link to list3.cs and view this example. The values in a list do not have to be constant values assigned at compile time. That is they may be calculated at run time as in the following definition: Random theValues = new Random(); int[] theNumbers = new int[5] { theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10), theValues.Next(1,10) };
See list2.cs. The examples so far have shown arrays of system data types. It is possible to create arrays of structures as well. As may be recalled, instances of structures are also value types. Therefore the same rules apply for structures as with the system data types. The interesting feature for structures is that list definitions may use the default
file:///D|/1/final/BBL0072.html (1 von 2) [01.12.2007 04:48:57]
List Definition and Initialization of Arrays
constructor: bankAccount[] theAccount2 = { new bankAccount(), new bankAccount(), new bankAccount() };
or non default constructors bankAccount[] theAccount3 = { new bankAccount("1234", "The first One",100.00m), new bankAccount("1235", "The Second One",200.00m), new bankAccount("1236","The Third One",300.00m)};
See bank9.cs for this example. When observing the output of theAccount2[] array, notice that the balance is 0.00.
file:///D|/1/final/BBL0072.html (2 von 2) [01.12.2007 04:48:57]
Arrays of Class Objects or Structure Instances
Arrays of Class Objects or Structure Instances Arrays of Class Objects In each of the examples above, the arrays contained elements of system data types or structures i.e. arrays of value types. It is also possible to defined arrays of programmer data types. In this case it is necessary to not only instantiate the array reference but also to instantiate each of the elements as well. The elements in this case are references to objects as shown in the following graphic:
For example suppose a program had the following class defined: public class customer { private string name; private decimal amountOwed; public customer() { name = ""; amountOwed=0.00M; } public void setName(string theName) { name = theName; }
file:///D|/1/final/BBL0073.html (1 von 2) [01.12.2007 04:48:57]
Arrays of Class Objects or Structure Instances
public void setAmountOwed(decimal theAmount) { amountOwed = theAmount; } public string getName() { return name; } public decimal getAmountOwed() { return amountOwed; } }
An array myCustomers[] of three objects of type customer could be defined as the following: customer[] myCustomers = new customer[3];
What is different with programmer data types from system data types is that each of the elements of the array myCustomer must be instantiated as in the following statement: myCustomers[index] = new customer();
See array6.cs. In the example above, the fields of a class were a single instance of some system data type. In C# a class may also have arrays as fields as well as simple variables. For example see bank7.cs.
Arrays of Structure Instances The examples above dealt with arrays of class objects. It is also possible to have arrays of structure instances as well. Using the example array6.cs above but changing from a class to a structure as well as eliminating the default constructor, it is possible to have an array of structure instances. See array14.cs
file:///D|/1/final/BBL0073.html (2 von 2) [01.12.2007 04:48:57]
Using foreach() and Enumerated Types with Arrays
Using foreach() and Enumerated Types with Arrays Arrays and the foreach() Loop Previously when C# loops were discussed, the notes mentioned that there was a loop called foreach(). Now that arrays have been introduced, this loop has more meaning. For example the following for() loop that appeared in a previous example: decimal[] unitPrice = new decimal[10]; Console.WriteLine("\tItem\tPrice"); for(int index=0; index < unitPrice.Length; ++index) { Console.WriteLine("\t{0,2} {1,15:c} ",index+1, unitPrice[index]); totalPrice += unitPrice[index]; } Console.WriteLine("\t {0,12}","------------"); Console.WriteLine("\tTotal {0,12:c}",totalPrice); Console.WriteLine("\n\n");
can be rewritten as the following using the foreach() loop: decimal[] unitPrice = new decimal[10]; Console.WriteLine("\tItem\tPrice"); index= 0; foreach(decimal price in unitPrice) { Console.WriteLine("\t{0,}\t{1,15:c} ",index+1, price); totalPrice += price; counter++; } Console.WriteLine("\t {0,12}","------------"); Console.WriteLine("\tTotal {0,12:c}",totalPrice); Console.WriteLine("\n\n");
To see this change, view: array2.cs. When using an array in a foreach() loop, the loop must go from the first element to the last element. If a program needs to iterate from the last to the first, then a for() loop must be used. Further, if the elements are used within the body of the loop, then their values may not be changed. If they need to be changed, then a for() loop must be used.
Arrays and Enumerated Data Types If the program had the following enumerated data type defined, enum Months {January,February,March,April, May,June,July,August,September, October,November,December}
then the code with a loop above could have been written as the following:
file:///D|/1/final/BBL0074.html (1 von 2) [01.12.2007 04:48:58]
Using foreach() and Enumerated Types with Arrays
decimal[] monthlySales = new decimal[12]; for(Months theMonth=Months.January; theMonth>"; this.btnLast.Click += new System.EventHandler(this.btnLast_Click); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(195, 142); this.btnAdd.Name = "btnAdd"; this.btnAdd.TabIndex = 12; this.btnAdd.Text = "&Add"; this.toolTip1.SetToolTip(this.btnAdd, "Adds new GL records"); this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(280, 142); this.btnDelete.Name = "btnDelete"; this.btnDelete.TabIndex = 13; this.btnDelete.Text = "&Delete"; this.toolTip1.SetToolTip(this.btnDelete, "Deletes current records of both tables"); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(365, 142); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 14; this.btnCancel.Text = "&Cancel"; this.toolTip1.SetToolTip(this.btnCancel, "Cancels the current changes"); this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // grdChecks // this.grdChecks.AllowNavigation = false; this.grdChecks.DataMember = "GL Accounts.Expenses"; this.grdChecks.DataSource = this.objTheExpenses; this.grdChecks.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.grdChecks.Location = new System.Drawing.Point(10, 175); this.grdChecks.Name = "grdChecks"; this.grdChecks.Size = new System.Drawing.Size(478, 292); this.grdChecks.TabIndex = 15; // // Expenses // this.AutoScaleBaseSize = new System.Drawing.Size(6, 13); this.ClientSize = new System.Drawing.Size(497, 442); this.Controls.Add(this.btnLoad);
file:///D|/1/final/BBL0094.html (23 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.Controls.Add(this.btnUpdate); this.Controls.Add(this.btnCancelAll); this.Controls.Add(this.lblGL_Account_Name); this.Controls.Add(this.editGL_Account_Name); this.Controls.Add(this.lblGL_Account_Number); this.Controls.Add(this.editGL_Account_Number); this.Controls.Add(this.btnNavFirst); this.Controls.Add(this.btnNavPrev); this.Controls.Add(this.lblNavLocation); this.Controls.Add(this.btnNavNext); this.Controls.Add(this.btnLast); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnCancel); this.Controls.Add(this.grdChecks); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Expenses"; this.Text = "Expenses"; ((System.ComponentModel.ISupportInitialize)(this.objTheExpenses)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.grdChecks)).EndInit(); this.ResumeLayout(false); } #endregion public void FillDataSet(PostingExpenses.TheExpenses dataSet) { // Turn off constraint checking before the dataset is filled. // This allows the adapters to fill the dataset without concern // for dependencies between the tables. dataSet.EnforceConstraints = false; try { // Open the connection. this.oleDbConnection1.Open(); // Attempt to fill the dataset through the OleDbDataAdapter1. this.oleDbDataAdapter1.Fill(dataSet); this.oleDbDataAdapter2.Fill(dataSet); } catch (System.Exception fillException) { // Add your error handling code here. throw fillException; } finally { // Turn constraint checking back on. dataSet.EnforceConstraints = true; // Close the connection whether or not the exception was thrown. this.oleDbConnection1.Close(); } } public void UpdateDataSource(PostingExpenses.TheExpenses ChangedRows) { try { // The data source only needs to be updated if there are changes pending. if ((ChangedRows != null)) { // Open the connection. this.oleDbConnection1.Open(); // Attempt to update the data source. oleDbDataAdapter1.Update(ChangedRows); oleDbDataAdapter2.Update(ChangedRows); } } catch (System.Exception updateException) { // Add your error handling code here. throw updateException; } finally { // Close the connection whether or not the exception was thrown.
file:///D|/1/final/BBL0094.html (24 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
this.oleDbConnection1.Close(); } } public void LoadDataSet() { // Create a new dataset to hold the records returned from the call to FillDataSet. // A temporary dataset is used because filling the existing dataset would // require the databindings to be rebound. PostingExpenses.TheExpenses objDataSetTemp; objDataSetTemp = new PostingExpenses.TheExpenses(); try { // Attempt to fill the temporary dataset. this.FillDataSet(objDataSetTemp); } catch (System.Exception eFillDataSet) { // Add your error handling code here. throw eFillDataSet; } try { grdChecks.DataSource = null; // Empty the old records from the dataset. objTheExpenses.Clear(); // Merge the records into the main dataset. objTheExpenses.Merge(objDataSetTemp); grdChecks.SetDataBinding(objTheExpenses, "GL Accounts.Expenses"); } catch (System.Exception eLoadMerge) { // Add your error handling code here. throw eLoadMerge; } } public void UpdateDataSet() { // Create a new dataset to hold the changes that have been made to the main dataset. PostingExpenses.TheExpenses objDataSetChanges = new PostingExpenses.TheExpenses(); // Stop any current edits. this.BindingContext[objTheExpenses,"GL Accounts"].EndCurrentEdit(); this.BindingContext[objTheExpenses,"Checks"].EndCurrentEdit(); // Get the changes that have been made to the main dataset. objDataSetChanges = ((PostingExpenses.TheExpenses)(objTheExpenses.GetChanges())); // Check to see if any changes have been made. if ((objDataSetChanges != null)) { try { // There are changes that need to be made, so attempt to update the datasource by // calling the update method and passing the dataset and any parameters. this.UpdateDataSource(objDataSetChanges); objTheExpenses.Merge(objDataSetChanges); objTheExpenses.AcceptChanges(); } catch (System.Exception eUpdate) { // Add your error handling code here. throw eUpdate; } // Add your code to check the returned dataset for any errors that may have been // pushed into the row object's error. } } private void btnCancelAll_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to cancel all of the changed records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { this.objTheExpenses.RejectChanges(); }
file:///D|/1/final/BBL0094.html (25 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} private void objTheExpenses_PositionChanged() { this.lblNavLocation.Text = ((((this.BindingContext[objTheExpenses,"GL Accounts"].Position + 1)).ToString() + " of ") + this.BindingContext[objTheExpenses,"GL Accounts"].Count.ToString()); } private void btnNavNext_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.BindingContext[objTheExpenses,"GL Accounts"].Position + 1); this.objTheExpenses_PositionChanged(); } private void btnNavPrev_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.BindingContext[objTheExpenses,"GL Accounts"].Position - 1); this.objTheExpenses_PositionChanged(); } private void btnLast_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = (this.objTheExpenses.Tables["GL Accounts"].Rows.Count - 1); this.objTheExpenses_PositionChanged(); } private void btnNavFirst_Click(object sender, System.EventArgs e) { this.BindingContext[objTheExpenses,"GL Accounts"].Position = 0; this.objTheExpenses_PositionChanged(); } private void btnLoad_Click(object sender, System.EventArgs e) { try { // Attempt to load the dataset. this.LoadDataSet(); } catch (System.Exception eLoad) { // Add your error handling code here. // Display error message, if any. System.Windows.Forms.MessageBox.Show(eLoad.Message); } this.objTheExpenses_PositionChanged(); } private void btnUpdate_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to update the database records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { try { // Attempt to update the datasource. this.UpdateDataSet(); } catch (System.Exception eUpdate) { // Add your error handling code here. // Display error message, if any. System.Windows.Forms.MessageBox.Show(eUpdate.Message); } this.objTheExpenses_PositionChanged(); } } private void btnAdd_Click(object sender, System.EventArgs e)
file:///D|/1/final/BBL0094.html (26 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ if(MessageBox.Show("Do you want to add a GL Account record?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)==DialogResult.Yes) { try { // Clear out the current edits this.BindingContext[objTheExpenses,"GL Accounts"].EndCurrentEdit(); this.BindingContext[objTheExpenses,"GL Accounts"].AddNew(); } catch (System.Exception eEndEdit) { System.Windows.Forms.MessageBox.Show(eEndEdit.Message); } this.objTheExpenses_PositionChanged(); } } private void btnDelete_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to delete both the GL Account record and the Check record?","Warning",MessageBoxButtons.YesNo, MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2)==DialogResult.Yes) { if ((this.BindingContext[objTheExpenses,"GL Accounts"].Count > 0)) { this.BindingContext[objTheExpenses,"GL Accounts"].RemoveAt(this.BindingContext[objTheExpenses,"GL Accounts"].Position); this.objTheExpenses_PositionChanged(); } } } private void btnCancel_Click(object sender, System.EventArgs e) { if(MessageBox.Show("Do you want to cancel the last change to the records?","Warning",MessageBoxButtons.YesNo,MessageBoxIcon. Warning,MessageBoxDefaultButton.Button2)==DialogResult.Yes) { this.BindingContext[objTheExpenses,"GL Accounts"].CancelCurrentEdit(); this.objTheExpenses_PositionChanged(); } } } }
// program_id Form3.cs // written_by don voils // date_written 3/12/2006 // description This program along with Expenses.cs uses // a Data Form to create access to the // database: Expenses.mdb. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace PostingExpenses { /// <summary> /// Summary description for Form1. /// public class Form3 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form3() { //
file:///D|/1/final/BBL0094.html (27 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { // // Form3 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 262); this.Name = "Form3"; this.Text = "Form4"; } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Expenses()); } } }
// program_id NewCustomers.cs // written_by don voils // date_written 10/06/2006 // description This file contains the definition of the // class NewCustomer which is use for random // file access both input and output. // using System; namespace NewCustomers { public class NewCustomer { private const int CHAR_ARRAY_LENGTH = 15; private const int SIZE_OF_CHAR = 2; private const int SIZE_OF_INT32 = 4; private const int SIZE_OF_DECIMAL = 8; private const int Size = 2 * (SIZE_OF_CHAR + CHAR_ARRAY_LENGTH) + SIZE_OF_INT32 + SIZE_OF_DECIMAL; private char[] first = new char[CHAR_ARRAY_LENGTH]; private char[] last = new char[CHAR_ARRAY_LENGTH]; private int ID;
file:///D|/1/final/BBL0094.html (28 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
private decimal Due; static public int theSize { get { return Size; } } public int customerID { get { return ID; } set { ID = value; } } public string firstName { get { return new string(first); } set { int stringSize = value.Length; string firstNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { firstNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { firstNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } first = firstNameString.ToCharArray(); } } public string lastName { get { return new string(last); } set { int stringSize = value.Length; string lastNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { lastNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { lastNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } last = lastNameString.ToCharArray(); } } public decimal balanceDue { get {
file:///D|/1/final/BBL0094.html (29 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
return Due; } set { Due = value; } } public NewCustomer() { customerID = 0; firstName = ""; lastName = ""; balanceDue = 0.00m; } public NewCustomer(int ID,string FirstName,string LastName,decimal BalanceDue) { customerID = ID; firstName = FirstName; lastName = LastName; balanceDue = BalanceDue; } } }
// program_id ReadingRandomAccess.cs // written_by don voils // date_written 12/06/2006 // description This file demonstrates the reading of // random access files. It uses objects from // the class NewCustomer from the file: // NewCustomer.cs // using System; using System.IO; using NewCustomers; namespace ReadingRandomAccessFiles { class ReadingRandomAccess { static FileStream fileInput; static BinaryReader binaryInput; static string randomAccessFile = "randomAccess.dat"; static void Main(string[] args) { char moreData = 'N'; Console.Clear(); NewCustomer theCustomer = new NewCustomer(); if (fileInput != null) fileInput.Close(); // If the file has never been created, then the following will throw an exception // try { fileInput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Read); } // If the file did not exist before this run of the program then the follow catch // executes informs the user that there is no data in the customer file. // catch (FileNotFoundException) { Console.WriteLine("There is no data in the customer file. To end press the Enter key."); Console.ReadLine(); return;
file:///D|/1/final/BBL0094.html (30 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
} binaryInput = new BinaryReader(fileInput); do { int theID; Console.Write("\n\nWhat is the customer ID you are looking for? "); theID = int.Parse(Console.ReadLine()); try { fileInput.Seek(NewCustomer.theSize * (theID - 1), 0); theCustomer.customerID = binaryInput.ReadInt32(); } catch (IOException) { Console.WriteLine("\n\nThat customer ID was not on record!\n"); moreData = 'Y'; } if (moreData != 'Y') { if (theCustomer.customerID == theID) { theCustomer.firstName = binaryInput.ReadString(); theCustomer.lastName = binaryInput.ReadString(); theCustomer.balanceDue = binaryInput.ReadDecimal(); Console.WriteLine("\nCustomer ID: " + theCustomer.customerID); Console.WriteLine("Customer Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("Balance due: {0:c}\n\n", theCustomer.balanceDue)); } else { Console.WriteLine("\n\nThat customer ID was not on record!\n"); } } Console.Write("\n\nProcess another customer? (Y/N). "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } while ((moreData == 'Y') || (moreData == 'y')); Console.WriteLine("\n"); } } }
// program_id theATM.cs // written_by don voils // date_written 11/14/2006 // description This program simulates an ATM. Along with the program // Account.cs, it illustrates how a programmer may create // a program specific exception class. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace theATM { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox txtAccountID; private System.Windows.Forms.TextBox txtWithdrawal; private System.Windows.Forms.Button btnWithdraw; private Account yourAccount = new Account(); private System.Windows.Forms.Button btnEnterID; private System.Windows.Forms.Label lblWithdraw;
file:///D|/1/final/BBL0094.html (31 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
private System.Windows.Forms.Label lblID; /// <summary> /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // yourAccount.ID = "12345"; yourAccount.Balance=454.43m; } /// <summary> /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if(disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.lblID = new System.Windows.Forms.Label(); this.txtAccountID = new System.Windows.Forms.TextBox(); this.btnEnterID = new System.Windows.Forms.Button(); this.lblWithdraw = new System.Windows.Forms.Label(); this.txtWithdrawal = new System.Windows.Forms.TextBox(); this.btnWithdraw = new System.Windows.Forms.Button(); this.SuspendLayout(); // // lblID // this.lblID.Location = new System.Drawing.Point(50, 40); this.lblID.Name = "lblID"; this.lblID.Size = new System.Drawing.Size(120, 23); this.lblID.TabIndex = 0; this.lblID.Text = "Account ID"; // // txtAccountID // this.txtAccountID.Location = new System.Drawing.Point(170, 40); this.txtAccountID.Name = "txtAccountID"; this.txtAccountID.TabIndex = 1; this.txtAccountID.Text = ""; // // btnEnterID // this.btnEnterID.Location = new System.Drawing.Point(160, 80); this.btnEnterID.Name = "btnEnterID"; this.btnEnterID.Size = new System.Drawing.Size(128, 23); this.btnEnterID.TabIndex = 2; this.btnEnterID.Text = "Press to Enter ID"; this.btnEnterID.Click += new System.EventHandler(this.btnEnterID_Click); // // lblWithdraw
file:///D|/1/final/BBL0094.html (32 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
// this.lblWithdraw.Location = new System.Drawing.Point(20, 150); this.lblWithdraw.Name = "lblWithdraw"; this.lblWithdraw.Size = new System.Drawing.Size(150, 23); this.lblWithdraw.TabIndex = 3; this.lblWithdraw.Text = "Withdrawal Amount"; this.lblWithdraw.Visible = false; // // txtWithdrawal // this.txtWithdrawal.Location = new System.Drawing.Point(170, 150); this.txtWithdrawal.Name = "txtWithdrawal"; this.txtWithdrawal.TabIndex = 4; this.txtWithdrawal.Text = ""; this.txtWithdrawal.Visible = false; // // btnWithdraw // this.btnWithdraw.Location = new System.Drawing.Point(160, 192); this.btnWithdraw.Name = "btnWithdraw"; this.btnWithdraw.Size = new System.Drawing.Size(136, 23); this.btnWithdraw.TabIndex = 5; this.btnWithdraw.Text = "Press to Withdraw"; this.btnWithdraw.Visible = false; this.btnWithdraw.Click += new System.EventHandler(this.btnWithdraw_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(7, 15); this.ClientSize = new System.Drawing.Size(496, 262); this.Controls.Add(this.btnWithdraw); this.Controls.Add(this.txtWithdrawal); this.Controls.Add(this.lblWithdraw); this.Controls.Add(this.btnEnterID); this.Controls.Add(this.txtAccountID); this.Controls.Add(this.lblID); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "Form1"; this.Text = "The ATM"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void btnEnterID_Click(object sender, System.EventArgs e) { if((yourAccount.ID).Equals(txtAccountID.Text)) { txtWithdrawal.Visible=true; btnWithdraw.Visible=true; lblWithdraw.Visible=true; txtAccountID.Clear(); txtAccountID.Visible=false; lblID.Visible=false; btnEnterID.Visible=false; txtWithdrawal.Focus(); } else { MessageBox.Show("You are not a customer","Error"); txtAccountID.Focus(); txtAccountID.Clear(); } } private void btnWithdraw_Click(object sender, System.EventArgs e)
file:///D|/1/final/BBL0094.html (33 von 34) [01.12.2007 04:49:21]
Lecture 10 Examples
{ decimal withdrawal = decimal.Parse(txtWithdrawal.Text); try { yourAccount.withdrawal(decimal.Parse(txtWithdrawal.Text)); MessageBox.Show("Here is your money.","Withdrew amount requested"); } catch(BalanceException f) { MessageBox.Show(String.Format("Your withdrawal of {0:c} exceeds your balance. ",f.Balance),"Error"); } finally { txtWithdrawal.Visible=false; btnWithdraw.Visible=false; lblWithdraw.Visible=false; txtWithdrawal.Clear(); lblID.Visible=true; btnEnterID.Visible=true; txtAccountID.Visible=true; txtAccountID.Focus(); } } } }
file:///D|/1/final/BBL0094.html (34 von 34) [01.12.2007 04:49:21]
Lecture 11: Generics in C#
Lecture 11: Generics in C# Introduction to C# Generics The language C++ has a construct called: templates (also known as generics). C++ has two types of templates: template functions and template classes.
Template Functions in C++ By template functions is meant that a function may be defined in such a way that the functional definition does not specify the data types of some of the variables involved in the function. For example a C++ function MAX( ) could have the following definition: template T MAX(T value1, T value2) { return ((value1 theMax) theMax = theFirst; else theMax = theSecond; return theMax; }
The answer is that it is possible and the two methods overload each other. For example see: theMaximum2.CS. Create a C# console project named: MAXIMUM2.CS and copy this file into the project. First, notice that the program compiles. Next notice that when the integers are entered this time, the non-generic MAX() is called and when the doubles are entered, the generic MAX() is called. The next question that should arise is whether it is possible for two generic methods to be in the same program and have the same name but different signatures. For example suppose the following method was added to the first example above: static T MAX(string theMessage, T theFirst, T theSecond) where T : IComparable { Console.WriteLine("\nThe generic MAX() with " + "three arguments was called \n" + "and the message was: {0}",theMessage); T theMax = theSecond; ; if (theFirst.CompareTo(theMax) > 0) theMax = theFirst; else theMax = theSecond; return theMax; }
The answer is that it is possible for a program to have both of these methods overload each other. For example see: theMaximum3.CS. Create a console project: Maximum3.CS. Copy the code in this file into the project. Compile and run it. Notice that it works similarly to the example in the C++ programs.
file:///D|/1/final/BBL0097.html (2 von 2) [01.12.2007 04:49:23]
Generic Classes
Generic Classes Defining Generic Classes As with C++, C# may have generic classes (the following discussion is also true for structures). The general form of the generic class definition is like the following: class firstGenericClass { ..... }
The example above only has one unknown type: T. As with C++, it is also possible to have generic classes in which there may be more than one unknown data type as in the following general form: class secondGenericClass { ..... }
Again having three unknowns is not a restriction. That is there may be more or less unknown data types than these three. Using the first example: firstGenericClass could be defined as the following: class firstGenericClass { private T theField; public T TheField { get { return theField; } set { theField = value; } } }
Using this class' definition, a program with code like the following could be written: firstGenericClass theIntObject = new firstGenericClass(); Console.Write("What is the value of the int field? "); theIntObject.TheField = Int32.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the " +
file:///D|/1/final/BBL0098.html (1 von 5) [01.12.2007 04:49:24]
Generic Classes
"int object was {0}. \n\n", theIntObject.TheField); firstGenericClass<double> theDoubleObject = new firstGenericClass<double>(); Console.Write("What is the value of the double field? "); theDoubleObject.TheField = Double.Parse(Console.ReadLine()); Console.WriteLine("\n\nYou said the value of the field for the" + " double object was {0}. \n\n", theDoubleObject.TheField);
See the following class' definition: firstGenericClass.cs and the following program: testingGenericClass.cs. Create the project: testingGenericClass. Copy these two files into the project where the second file replaces: Program.cs and the first file is a class file. Next compile and run the program. Notice how the program was able to handle the two different data types: int and double to implement the class. The example above only had one unknown data type. The following class processes when there are two unknown data types: class secondGenericClass { private T theFirst; private R theSecond; public T First { get { return theFirst; } set { theFirst = value; } } public R Second { get { return theSecond; } set { theSecond = value; } } }
To view how this class works create the project: testingGenericClasses2.cs. Copy the file: testingGenericClasses2 in Program.cs and create a class file for the file: secondGenericClass.cs.
Problems with Generic Classes Now things have worked so far in the examples above. However that is only because the examples are so simple. Suppose that a program included the class: thirdGenericClass which is defined as the following:
file:///D|/1/final/BBL0098.html (2 von 5) [01.12.2007 04:49:24]
Generic Classes
class thirdGenericClass { private T theField; thirdGenericClass() { theField = new T(); } }
If you place this class within a project, it will not compile. The reason is that the definition assumes that the data type T has a default constructor. Since this is a not requirement of all classes, the assumption is not acceptable. Another problem can be writing a generic class definition which assumes that the unknown data type has the operators: == and != defined. This feature is also not a requirement, so such a class will also not compile. Another problem can occur if it is necessary to initialize a field which is an instance of the unknown data type. That is suppose the fourthGenericClass needs a constructor definition to include the following: class fourthGenericClass { T theField; fourthGenericClass() { theField = ???; } ....... }
The question is what should replace the ???. One possibility is 0 and another is null. But these are not the same and therefore can not be used for all unknown data types. One solution is to use the function: default() as in the following: class fourthGenericClass { T theField; fourthGenericClass() { theField = default(T); } ....... }
In this case, if the data type T was a value type, then a 0 as one of the possibilities would be supplied by the compiler. However, if the data type T was a reference type, then null would be supplied instead. Another type of error that can occur is if the generic class attempts to use any of the following operators: +, -, *, / or %. These operators can not be used either because they are not required of all classes. In addition, the .Net methods: Add(), Multiply(), Subtract() and Divide() may not be used because it is not a requirement that all classes implement these methods.
Generic Constraints
file:///D|/1/final/BBL0098.html (3 von 5) [01.12.2007 04:49:24]
Generic Classes
As discussed above, a generic class must be defined in such a way that the unknown data types do not provide compiler errors because some data type T may not possess a particular property needed in the class' definition‥ Recall that above, one of the examples required that the default constructor be defined on the unknown data type T. As a result, the code would not compile. The reason for this is that the generic classes discussed so far have what is called: unbounded constraints. To solve this problem requires the use of constraints and the use of the key word: where. To implement this feature, the header of the generic class needs to be defined like the following: class theClass where T: theconstraint { ...... }
or if there is more than one constraint, then they may appear sequential separated by commas as in the following example: class theClass where T : theTconstraint, where R : theRconstraint { ..... }
The following table contains the possible constraints:
Open table as spreadsheet Constraint
Meaning
where T: struct
T must be a value type
where T: class
T must be a reference type
where T: new()
T must have a default constructor
where T: derivedFromParticularClass
T must be derived from the class: derivedFromParticularClass
where T: derivedFromParticularInterface
T must be derived from the interface: derivedFromParticularInterface
The following are some examples of the class header of generic classes that have constraints: class Class1 where T: new() { … }
so that the data type T implements a default constructor, or class Class2 where T:struct { .... }
file:///D|/1/final/BBL0098.html (4 von 5) [01.12.2007 04:49:24]
Generic Classes
so that the data type T is a value type, or class Class3 where T: class { … }
so that the data type T is a reference type, or class Class4 where T: struct, where R: theInterface { … }
so the data type T is a value type and the data type R is derived from theInterface.
file:///D|/1/final/BBL0098.html (5 von 5) [01.12.2007 04:49:24]
Generic Class Inheritance from Classes and Interfaces
Generic Class Inheritance from Classes and Interfaces Generic Classes Inheritance from Classes Suppose that you had the following generic class: class theGenericClass1 { .... }
It is possible to not only derive other generic classes from theGenericClass but it is also possible to derive non generic classes from this class. Having said this, one must keep in mind that there may be several restrictions. Suppose that you wanted to derive a non-generic class from theGenericClass. In order to do this the data type going to be used for T in the non-generic class must be explicitly specified in the class' header as in the following: class nonGenericClass:theGenericClass1<decimal> { ..... }
It would also be possible to derive a generic class from theGenericClass1. The only restriction would be that the derived class must also implement the data type T. For example the following would be permissible: class theDerivedGenericClass : theGenericClass1 { … }
Next suppose that a generic class had constraints as in the following case: class theGenericClass2 where T: struct { … }
In this case the generic (or the nongeneric) class derived from theGenericClass2 must also have the same constraint. And of course, if there was more than one constraint then each of them must be implemented by the derived class. If the generic base class had virtual or abstract methods, then the derived class must override these methods. The examples above only dealt with one unknown data type in the generic base class. What should be kept in mind is that the statements above for one unknown data type can also be extend to the case where the base class has more than one unknown data type.
Interfaces, Inheritance and Generics file:///D|/1/final/BBL0099.html (1 von 2) [01.12.2007 04:49:25]
Generic Class Inheritance from Classes and Interfaces
As noted in an earlier section of this lecture, there are built into C# several generic interfaces. Therefore it is obvious that generic interfaces may be written as well. The main thing to keep in mind when deriving from a generic interface, is that the derived class must implement the unknown data type as a specific data type. That is, if T is the unknown data type, then the derived class must implement T with a specific data type like: decimal.
Comment about Generics and Inheritance As can be seen from the discussion in this section of the lecture, C# implements inheritance with respect to generic classes, generic interfaces and non-generic classes. While this is possible, there seems to be at the moment little likely hood that other than the builtin generics, little code will be written which implements generic inheritance.
file:///D|/1/final/BBL0099.html (2 von 2) [01.12.2007 04:49:25]
Lecture 11 Examples
Lecture 11 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
CustomerList.cs
This program along with the class file People.cs uses the generic List to manage a customers list.
firstGenericClass.cs
This file along with testingGenericClasses.cs simulates generic classes.
MAXMUM2.CPP
This example shows how to use template functions with a non-class argument.
MAXIMUM.CPP
This example shows how to use template functions which have arguments all of which are of the same data type.
People.cs
This file contains the definition of the class: People.
secondGenericClass.cs
This file along with testingGenericClasses2.cs demonstrates using generic class with two unknown data types.
testingGenericClasses2. cs
This file along with secondGenericClass.cs demonstrates using generic class with two unknown data types.
testingGenericClasses.cs
This file along with firstGenericClas.cs demonstrates how generic classes could be defined.
theMaximum2.cs
This program demonstrates that generic methods in C# may overload non-generic methods.
theMaximum3.cs
This program demonstrates that two generic methods in C# may overload each other.
theMaximum.cs
This program demonstrates generic methods in C# similar to the template methods in C++.
// program_id CustomerList.cs // written_by Don Voils // date_written 11/10/2006 // description This program along with the class file People.cs // uses the generic List to manage a customers list. // using System; using System.Collections.Generic; using System.Text; using thePeople; namespace CustomersList { class Program { static List theCustomers = new List(); static void Main(string[] args) { bool moreOptions = true; int theOption; do { Console.Clear(); Console.WriteLine(" Select an option\n\n");
file:///D|/1/final/BBL0100.html (1 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.WriteLine(" 1. Add a customer\n"); Console.WriteLine(" 2. Find a customer\n"); Console.WriteLine(" 3. Delete a customer\n"); Console.WriteLine(" 4. Exit\n"); Console.Write("\n Which Option? "); theOption = Int16.Parse(Console.ReadLine()); Console.Clear(); switch (theOption) { case 1: AddCustomer(); break; case 2: FindCustomer(); break; case 3: DeleteCustomer(); break; case 4: moreOptions = false; break; default: break; } } while (moreOptions); } static void AddCustomer() { Console.Clear(); People thePerson = new People(); Console.Write(" What is the customer's Credit Card Company? "); thePerson.TheCompany = Console.ReadLine(); Console.Write("\n What is the customer's ID? "); thePerson.TheID = Console.ReadLine(); Console.Write("\n What is the customer's name? "); thePerson.TheName = Console.ReadLine(); Console.Write("\n What is the customer's address? "); thePerson.TheAddress = Console.ReadLine(); Console.Write("\n What is the customer's city? "); thePerson.TheCity = Console.ReadLine(); Console.Write("\n What is the customer's state? "); thePerson.TheState = Console.ReadLine(); Console.Write("\n What is the cusotmer's zip code? "); thePerson.TheZipCode = Console.ReadLine(); Console.Write("\n\n Is the information above correct? (Y/N) "); char theResponse = Char.Parse(Console.ReadLine()); if ((theResponse == 'Y') || (theResponse == 'y')) { Console.WriteLine("\n\n The information to be saved is:"); Console.Write("\n\n" + thePerson.ToString()); Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); theCustomers.Add(thePerson); } else { Console.WriteLine("\n\n The information will not be saved.\n");
file:///D|/1/final/BBL0100.html (2 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); } } static void FindCustomer() { Console.Clear(); string findID; int foundIt = -1; Console.Write(" What is the customer's ID you wish to find? "); findID = Console.ReadLine(); for(int index = 0;index < theCustomers.Count;++index) { if (theCustomers[index].TheID == findID) { Console.Write("\n\n" +theCustomers[index].ToString()); foundIt = index; } } if (foundIt == -1) Console.WriteLine("\n That customer is not on record.\n\n"); Console.Write("\n\n Press any key to continue. "); Console.ReadKey(); } static void DeleteCustomer() { Console.Clear(); string findID; int foundIt = -1; Console.Write(" What is the customer's ID you wish to find? "); findID = Console.ReadLine(); for (int index = 0; index < theCustomers.Count; ++index) { if (theCustomers[index].TheID == findID) { Console.Write("\n\n"+theCustomers[index].ToString()); foundIt = index; Console.Write("\n\n Delete this customer? (Y/N) "); char theAnswer = Char.Parse(Console.ReadLine()); if((theAnswer=='Y')||(theAnswer=='y')) { bool wasDeleted = theCustomers.Remove(theCustomers[index]); if(wasDeleted) Console.WriteLine("\n\n This customer will be deleted.\n\n"); else Console.WriteLine("\n\n This customer was not deleted.\n\n"); } else Console.WriteLine("\n\n That customer will be retained.\n\n"); } } if (foundIt == -1) Console.WriteLine("\n That customer is not on record.\n\n");
file:///D|/1/final/BBL0100.html (3 von 13) [01.12.2007 04:49:26]
Lecture 11 Examples
Console.Write("\n\n Press any key to continue."); Console.ReadKey(); } } }
// program_id firstGenericClass.cs // written_by don voils // date_written 11/10/2006 // description This file along with testingGenericClasses.cs // simulates generic classes. // using System; using System.Collections.Generic; using System.Text; namespace thefirstGenericClass { class firstGenericClass { private T theField; public T TheField { get { return theField; } set { theField = value; } } } }
// program_id MAXMUM2.CPP // author don voils // date written 10/23/2006 // // program description This example shows how to use // template functions with a non-class // argument. // #include using namespace std; template T MAX(char *word,T value1, T value2) { cout /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.txtMonth = new System.Windows.Forms.TextBox(); this.btnMonth = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtCompanyName = new System.Windows.Forms.TextBox(); this.txtBalanceDue = new System.Windows.Forms.TextBox(); this.txtTotalARDue = new System.Windows.Forms.TextBox(); this.btnNext = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(50, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(52, 17); this.label1.TabIndex = 0; this.label1.Text = "Month";
file:///D|/1/final/BBL0124.html (7 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// // txtMonth // this.txtMonth.Location = new System.Drawing.Point(140, 30); this.txtMonth.Name = "txtMonth"; this.txtMonth.Size = new System.Drawing.Size(50, 22); this.txtMonth.TabIndex = 1; this.txtMonth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // btnMonth // this.btnMonth.Location = new System.Drawing.Point(307, 29); this.btnMonth.Name = "btnMonth"; this.btnMonth.Size = new System.Drawing.Size(128, 32); this.btnMonth.TabIndex = 2; this.btnMonth.Text = "Select Month"; this.btnMonth.UseVisualStyleBackColor = true; this.btnMonth.Click += new System.EventHandler(this.btnMonth_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(40, 110); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 17); this.label2.TabIndex = 3; this.label2.Text = "Company Name"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(40, 170); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 17); this.label3.TabIndex = 4; this.label3.Text = "Balance Due"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(40, 230); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(105, 17); this.label4.TabIndex = 5; this.label4.Text = "Total AR Due"; // // txtCompanyName // this.txtCompanyName.Location = new System.Drawing.Point(170, 110); this.txtCompanyName.Name = "txtCompanyName"; this.txtCompanyName.ReadOnly = true; this.txtCompanyName.Size = new System.Drawing.Size(140, 22); this.txtCompanyName.TabIndex = 3; this.txtCompanyName.TabStop = false; // // txtBalanceDue // this.txtBalanceDue.Location = new System.Drawing.Point(170, 170); this.txtBalanceDue.Name = "txtBalanceDue"; this.txtBalanceDue.ReadOnly = true; this.txtBalanceDue.Size = new System.Drawing.Size(100, 22); this.txtBalanceDue.TabIndex = 4; this.txtBalanceDue.TabStop = false; this.txtBalanceDue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtTotalARDue // this.txtTotalARDue.Location = new System.Drawing.Point(170, 230); this.txtTotalARDue.Name = "txtTotalARDue"; this.txtTotalARDue.ReadOnly = true; this.txtTotalARDue.Size = new System.Drawing.Size(100, 22); this.txtTotalARDue.TabIndex = 8; this.txtTotalARDue.TabStop = false; this.txtTotalARDue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; //
file:///D|/1/final/BBL0124.html (8 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// btnNext // this.btnNext.Location = new System.Drawing.Point(54, 288); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(75, 28); this.btnNext.TabIndex = 5; this.btnNext.Text = "Next"; this.btnNext.UseVisualStyleBackColor = true; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(452, 347); this.Controls.Add(this.btnNext); this.Controls.Add(this.txtTotalARDue); this.Controls.Add(this.txtBalanceDue); this.Controls.Add(this.txtCompanyName); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.btnMonth); this.Controls.Add(this.txtMonth); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.MaximumSize = new System.Drawing.Size(460, 380); this.MinimumSize = new System.Drawing.Size(460, 380); this.Name = "Form1"; this.Text = "View Accounts Receivable"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtMonth; private System.Windows.Forms.Button btnMonth; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtCompanyName; private System.Windows.Forms.TextBox txtBalanceDue; private System.Windows.Forms.TextBox txtTotalARDue; private System.Windows.Forms.Button btnNext; } }
// program_id Program.cs // written_by Don Voils // date_wrtten 11/2/2006 // description This program reads the data written to a text // file by the program:Accounts Receivable Posting. // It permits the selection of the month and then // reads one record at a time. // using System; using System.Collections.Generic; using System.Windows.Forms; namespace viewReceivables { static class Program { /// <summary> /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
file:///D|/1/final/BBL0124.html (9 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Application.Run(new Form1()); } } }
// program_id BufferedStream1.cs // written_by don voils // date_written 3/24/2006 // description This program sends data to a BufferedStream. Next // it displays the data stored in memory. Then // it creates a file using theFile. The data in // the BufferedStream is then sent to the FileStream // data file. // using System; using System.IO; namespace MemoryStreamApp { public class theProgram { public static int Main(string[] args) { Console.WriteLine("\nWorking the BufferedStream!\n\n"); FileStream theFile = new FileStream("theData.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream myFileBuffer = new BufferedStream(theFile); byte[] theBuffer = {0x55, 0x71, 0x4, 0x0, 0x0, 0x16,0xAB,0x44,0x35}; myFileBuffer.Write(theBuffer, 0, theBuffer.Length); myFileBuffer.Close(); return 0; } } }
// program_id customer.cs // written_by don voils // date_written 10/30/2006 // description This file contains the definition of the // class Customer. // using System; namespace Customers { [Serializable] public class Customer { private string ID; private string first; private string last; private decimal Due; public string customerID { get { return ID; } set { ID = value; } }
file:///D|/1/final/BBL0124.html (10 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public string firstName { get { return first; } set { first = value; } } public string lastName { get { return last; } set { last = value; } }
public decimal balanceDue { get { return Due; } set { Due = value; } } public Customer() { customerID = ""; firstName = ""; lastName = ""; balanceDue = 0.00m; } } }
// program_id DirectoryInfo1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates new subdirectories. // using System; using System.IO; namespace DirectoryInfo1 { class theProgram { static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥/‥/‥/"); Console.Write("What is the company name? "); string theName = Console.ReadLine(); try {
file:///D|/1/final/BBL0124.html (11 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
theDirectory.CreateSubdirectory(theName); string theSales = theName + @"\Sales"; string theExpenses = theName + @"\Expenses"; theDirectory.CreateSubdirectory(theSales); theDirectory.CreateSubdirectory(theExpenses); } catch(IOException e) { Console.WriteLine(e.Message); } Console.WriteLine("\n"); } } }
// program_id DirectoryInfo2.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new DirectoryInfo object // and then displays information about the // directory to which the object is initialized. // using System; using System.IO; namespace DirectoryInfo1 { class theProgram { static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥\‥\bin"); Console.WriteLine("****Directory Information****"); Console.WriteLine("FullName: {0}",theDirectory.FullName); Console.WriteLine("Name: {0}",theDirectory.Name); Console.WriteLine("Parent: {0}",theDirectory.Parent); Console.WriteLine("Creation: {0}",theDirectory.CreationTime); Console.WriteLine("Attributes: {0}",theDirectory.Attributes.ToString()); Console.WriteLine("Root: {0}",theDirectory.Root); Console.WriteLine("**********************"); } } }
// program_id DirectoryInfo3.cs // writen_by don voils // date_written 3/19/2006 // description This program creates new subdirectories in // the folder of the program. After compiling this // program, create a directory called: TheAccounting. // Next place the executable for this program in that // folder. // using System; using System.IO; namespace DirectoryInfo1 {
class theProgram {
static void Main(string[] args) { DirectoryInfo theDirectory = new DirectoryInfo(@"‥\TheAccounting"); Console.Write("What is the company name? ");
file:///D|/1/final/BBL0124.html (12 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
string theName = Console.ReadLine(); try { theDirectory.CreateSubdirectory(theName); string theSales = theName + @"\Sales"; string theExpenses = theName + @"\Expenses"; theDirectory.CreateSubdirectory(theSales); theDirectory.CreateSubdirectory(theExpenses); } catch(IOException e) { Console.WriteLine(e.Message); } Console.WriteLine("\n"); } } }
// program_id DirectoryManagement.cs // written_by don voils // date_written 12/06/2005 // description This program demonstrates how to access the // directory information for a locations specified // from keyboard input. // using System; using System.IO; namespace DirectoryManagement { class DirectoryManagement { // if you have permission try the following directory: @"c:\Program Files"; // try other directories to observe how the code works. // if your a: disk does not have sub directories, make some to see how this // program works. // static string theDirectory; static int dirCounter = 1; static int indentLevel = -1; static void Main(string[] args) { char more = 'Y'; do { Console.Clear(); Console.Write("What is the drive and directory you want to search? "); theDirectory = Console.ReadLine(); DirectoryInfo theInfo = new DirectoryInfo(theDirectory); ExploreDirectories(theInfo); Console.WriteLine("\n\n{0} directories were found in {1}\n",dirCounter,theDirectory); Console.Write("\n\nAnother locations? (Y/N) "); more = Char.Parse(Console.ReadLine()); Console.Clear(); }while((more=='Y') || (more=='y')); } // The following is a recursive method that moves up and down the directory tree // static void ExploreDirectories(DirectoryInfo info) { indentLevel++; for(int index = 0; index < indentLevel; ++index) Console.Write(" ");
file:///D|/1/final/BBL0124.html (13 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.WriteLine("Level:[{0}] Name:[{1}] Date of last access:[{2}]",indentLevel, info.Name, info.LastAccessTime); DirectoryInfo[] directories = info.GetDirectories(); foreach(DirectoryInfo newDir in directories) { dirCounter++; ExploreDirectories(newDir); } indentLevel--; } } }
// program_id FileInfo1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new file: CompanyInformation.txt // in a folder created in DirectoryInfo1.cs and then displays // the information about the directory. At the end, the program // requests that any key be pressed. Once the key is pressed the file // is deleted. // using System; using System.IO; namespace FileInfo1 {
class theProgram {
static void Main(string[] args) { Console.WriteLine("In the following use the same name"); Console.WriteLine("as used with DirectoryInfo1.cs example.\n"); Console.Write("What is the name of the company? "); string theName = Console.ReadLine(); FileInfo theInfo = new FileInfo(@"‥\‥\‥\"+theName +@"\CompanyInformation.txt"); FileStream theStream = theInfo.Create(); Console.WriteLine("\n\n****File Information****"); Console.WriteLine("FullName: {0}",theInfo.FullName); Console.WriteLine("Creation: {0}",theInfo.CreationTime); Console.WriteLine("Attributes: {0}",theInfo.Attributes.ToString()); Console.WriteLine("**********************"); Console.WriteLine("\n\nLook in the "+theName+ " folder to view this file."); Console.WriteLine("\nAfter you press any key, the file will be deleted.\n"); Console.WriteLine("Press a key to delete the file."); Console.Read(); theStream.Close(); theInfo.Delete(); } } }
// program_id FileManagement.cs // written_by don voils // date_written 12/06/2005 // description This program enables access to a location // and seeks to determine the number of files // and folders at this location. // using System; using System.IO;
file:///D|/1/final/BBL0124.html (14 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
namespace FileManagement {
class FileManagement { // if you have permission try the following directory: @"c:\Program Files"; // try other directories to observe how the code works. // if your a: disk does not have sub directories, make some to see how this // program works. // static string theDirectory; static int dirCounter = 1; static int indentLevel = -1; static int fileCounter = 0; static void Main(string[] args) { char more = 'Y'; do { Console.Clear(); Console.Write("What locations do you wish to explore? "); theDirectory = Console.ReadLine(); DirectoryInfo theInfo = new DirectoryInfo(theDirectory); ExploreDirectories(theInfo); Console.WriteLine("\n\n{0} files in {1} directories were found.\n",fileCounter,dirCounter); Console.Write("Do you want to search another location? Y/N) "); more = Char.Parse(Console.ReadLine()); }while((more=='Y')||(more=='y')); Console.Clear(); } // The following is a recursive method that moves up and down the directory tree // static void ExploreDirectories(DirectoryInfo info) { indentLevel++; for(int index = 0; index < indentLevel; ++index) Console.Write(" "); Console.WriteLine("Level:[{0}] Name:[{1}] Date of last access:[{2}]",indentLevel, info.Name, info.LastAccessTime); FileInfo[] filesinDirectory = info.GetFiles(); foreach(FileInfo newFile in filesinDirectory) { for(int index = 0; index < indentLevel+1;++index) Console.Write(" "); Console.WriteLine("File:[{0}] Last Written:[{1}] Size {2} bytes",newFile.Name,newFile.LastWriteTime,newFile.Length); ++fileCounter; } DirectoryInfo[] directories = info.GetDirectories(); foreach(DirectoryInfo newDir in directories) { dirCounter++; ExploreDirectories(newDir); } indentLevel--; } } }
file:///D|/1/final/BBL0124.html (15 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// program_id FileMode1.cs // writen_by don voils // date_written 3/19/2006 // description This program creates a new file: Text.ini // and then display information about the // directory. The program requests that any // key be pressed. Once it does the file // is deleted. // using System; using System.IO; namespace FileInfo1 {
class theProgram {
static void Main(string[] args) { Console.Write("What is your name? "); string theName = Console.ReadLine(); FileInfo theInfo = new FileInfo(@"‥\‥\"+theName+@"'s InformationFile.txt"); FileStream theStream = theInfo.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite); Console.WriteLine("****File Information****"); Console.WriteLine("FullName: {0}",theInfo.FullName); Console.WriteLine("Creation: {0}",theInfo.CreationTime); Console.WriteLine("Attributes: {0}",theInfo.Attributes.ToString()); Console.WriteLine("**********************"); Console.WriteLine("\nLook in the bin directory of the program's folder to view this file."); Console.WriteLine("\nAfter you press any key, the file will be deleted.\n"); Console.WriteLine("Press a key to delete the file."); Console.Read(); theStream.Close(); theInfo.Delete(); } } }
// program_id FileStream1.cs // written_by don voils // date_written 3/24/2006 // description This program creates a file using FileStream // and sends bytes to the file after which // it resets the Position and the bytes are // then read back into the program. // using System; using System.IO; namespace FileStream1 { class theProgram { static void Main(string[] args) { FileStream theStream = new FileStream("myData.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); for(int index = 65; index < 125;++index) theStream.WriteByte((byte)index); theStream.Position = 0; for(int index = 65; index = stringSize) { firstNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { firstNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } first = firstNameString.ToCharArray(); } } public string lastName { get { return new string(last); } set { int stringSize = value.Length; string lastNameString = value; if(CHAR_ARRAY_LENGTH >= stringSize) { lastNameString = value + new string(' ',CHAR_ARRAY_LENGTH - stringSize); } else { lastNameString = value.Substring(0,CHAR_ARRAY_LENGTH); } last = lastNameString.ToCharArray(); } }
file:///D|/1/final/BBL0124.html (18 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public decimal balanceDue { get { return Due; } set { Due = value; } } public NewCustomer() { customerID = 0; firstName = ""; lastName = ""; balanceDue = 0.00m; } public NewCustomer(int ID,string FirstName,string LastName,decimal BalanceDue) { customerID = ID; firstName = FirstName; lastName = LastName; balanceDue = BalanceDue; } } }
// program_id ReadFromBinaryFiles // written_by don voils // date_written 11/04/2006 // using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; namespace ReadFromBinaryFiles { class Program { static void Main(string[] args) { FileStream theInFile; decimal theTotalDue = 0.00m; try { Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); theInFile = new FileStream("Customers.dat", FileMode.Open, FileAccess.Read); // The following loop continues until there is no more data // then an exception occurs to end the try block. The catch() // with the SerializationException catches the end of file // error and the program terminates successfully. // while (true) { theCustomer = serializer.Deserialize(theInFile) as Customer; Console.WriteLine("Customer's ID: " + theCustomer.customerID); Console.WriteLine("Customer's Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("\nBalance due is: {0:c}\n\n", theCustomer.balanceDue)); theTotalDue += theCustomer.balanceDue; } } catch (SerializationException) {
file:///D|/1/final/BBL0124.html (19 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.WriteLine("Total Account Receivable {0:c}", theTotalDue); Console.ReadKey(); } catch (IOException e) { Console.WriteLine("An IO exception has occurred."); Console.WriteLine(e.ToString()); } } } }
// program_id ReadFromTextFiles2.cs // written_by don voils // date_written 3/25/2006 // description This program is similar to ReadFromTextFiles.cs // except it uses StreamReader instead FileStream. using System; using System.IO; namespace ReadFromTextFiles2 { class InPutData { static string fileName = @"‥\‥\‥\‥\datafile2.txt"; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerID = fileReader.ReadLine(); while(customerID != null) { Console.WriteLine("Customer's ID: "+customerID); customerFirstName = fileReader.ReadLine(); customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+ " "+customerLastName); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("\nBalance due: {0:c}\n\n", customerBalanceDue)); customerID = fileReader.ReadLine(); } CloseDataFiles(); } static void OpentoReadDataFile() { fileReader = File.OpenText(fileName); } static void CloseDataFiles() { fileReader.Close(); } } }
// program_id ReadFromTextFiles.cs // written_by don voils // date_written 12/19/2005 // description This program demonstrates how to read data // from a text file. //
file:///D|/1/final/BBL0124.html (20 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
using System; using System.IO; namespace ReadFromTextFiles { class InPutData { static string fileName = @"‥\‥\‥\‥\datafile.txt"; static FileStream readFileStream; static StreamReader fileReader; static void Main(string[] args) { OpentoReadDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; customerID = fileReader.ReadLine(); while(customerID != null) { Console.WriteLine("Customer's ID: "+customerID); customerFirstName = fileReader.ReadLine(); customerLastName = fileReader.ReadLine(); Console.WriteLine("\nCustomer's name: "+customerFirstName+" "+customerLastName); customerBalanceDue = decimal.Parse(fileReader.ReadLine()); Console.WriteLine(String.Format("\nBalance due: {0:c}\n\n",customerBalanceDue)); customerID = fileReader.ReadLine(); } CloseDataFiles(); } static void OpentoReadDataFile() { if(readFileStream!=null) readFileStream.Close(); if(fileReader!=null) fileReader.Close(); readFileStream = new FileStream(fileName,FileMode.Open,FileAccess.Read); fileReader = new StreamReader(readFileStream); } static void CloseDataFiles() { fileReader.Close(); readFileStream.Close(); } } }
// program_id readingBinaryFiles.cs // written_by don voils // date-written 10/30/2006 // description This program demonstrates the reading of // serialzed objects of the class customer // from a binary file. // namespace CustomSerialization { using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; public class theInputProgram {
file:///D|/1/final/BBL0124.html (21 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
public static int Main(string[] args) { BinaryFormatter myBinaryFormat = new BinaryFormatter(); Customer theCustomer = new Customer(); Stream myStream = File.OpenRead(@"‥\‥\‥\‥\CustomerData.dat"); decimal theTotal = 0.00m; Console.WriteLine(" Accounts Receivable\n\n"); try { while(true) { theCustomer = (Customer)myBinaryFormat.Deserialize(myStream); Console.WriteLine("Customer's ID: "+ theCustomer.customerID); Console.WriteLine("Customer's name: "+theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("\nBalance due is:{0:c}\n\n", theCustomer.balanceDue)); theTotal += theCustomer.balanceDue; } } catch(SerializationException) { myStream.Close(); } Console.WriteLine("Total Accounts Receivable {0:c}",theTotal); char resp; Console.Write("\n\nContinue?"); resp = Char.Parse(Console.ReadLine()); return 0; } } }
// program_id ReadingRandomAccess.cs // written_by don voils // date_written 12/06/2006 // description This file demonstrates the reading of // random access files. It uses objects from // the class NewCustomer from the file: // NewCustomer.cs // using System; using System.IO; using NewCustomers; namespace ReadingRandomAccessFiles { class ReadingRandomAccess { static FileStream fileInput; static BinaryReader binaryInput; static string randomAccessFile = "randomAccess.dat"; static void Main(string[] args) { char moreData = 'N'; Console.Clear(); NewCustomer theCustomer = new NewCustomer(); if (fileInput != null) fileInput.Close(); // If the file has never been created, then the following will throw an exception
file:///D|/1/final/BBL0124.html (22 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
// try { fileInput = new FileStream(randomAccessFile, FileMode.Open, FileAccess.Read); } // If the file did not exist before this run of the program then the follow catch // executes informs the user that there is no data in the customer file. // catch (FileNotFoundException) { Console.WriteLine("There is no data in the customer file. To end press the Enter key."); Console.ReadLine(); return; } binaryInput = new BinaryReader(fileInput); do { int theID; Console.Write("\n\nWhat is the customer ID you are looking for? "); theID = int.Parse(Console.ReadLine()); try { fileInput.Seek(NewCustomer.theSize * (theID - 1), 0); theCustomer.customerID = binaryInput.ReadInt32(); } catch (IOException) { Console.WriteLine("\n\nThat customer ID was not on record!\n"); moreData = 'Y'; } if (moreData != 'Y') { if (theCustomer.customerID == theID) { theCustomer.firstName = binaryInput.ReadString(); theCustomer.lastName = binaryInput.ReadString(); theCustomer.balanceDue = binaryInput.ReadDecimal(); Console.WriteLine("\nCustomer ID: " + theCustomer.customerID); Console.WriteLine("Customer Name: " + theCustomer.firstName + " " + theCustomer.lastName); Console.WriteLine(String.Format("Balance due: {0:c}\n\n", theCustomer.balanceDue)); } else { Console.WriteLine("\n\nThat customer ID was not on record!\n"); } } Console.Write("\n\nProcess another customer? (Y/N). "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } while ((moreData == 'Y') || (moreData == 'y')); Console.WriteLine("\n"); } } }
// program_id: WriteToBinaryFile // written_by: don voils // date_written: 11/04/2006 // description: This program writes to binary files. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers;
file:///D|/1/final/BBL0124.html (23 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
namespace WriteToBinaryFiles { class Program { static void Main(string[] args) { Customer theCustomer = new Customer(); IFormatter serializer = new BinaryFormatter(); FileStream theOutFile = new FileStream("Customers.dat", FileMode.Append, FileAccess.Write); char moreData = 'Y'; while ((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); theCustomer.customerID = Console.ReadLine(); Console.Write("\n\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\n\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\n\nHow much does the customer owe? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); serializer.Serialize(theOutFile, theCustomer); Console.Write("\n\nEnter another customer (Y/N)? "); moreData = Char.Parse(Console.ReadLine()); } theOutFile.Close(); Console.Clear(); } } }
// program_id WriteToTextFile2.cs // written_by don voils // date_written 3/25/2006 // description This program is similar to WriteToTextFile.cs // except it uses an object of FileInfo rather than // an object of FileStream. // using System; using System.IO; namespace WriteToTextFile2 { class OutPutData2 { static string fileName = @"‥\‥\‥\‥\datafile2.txt"; static FileInfo writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? ");
file:///D|/1/final/BBL0124.html (24 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush(); Console.Write("\n\n\nContinue? (Y/N) "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } static void OpentoWritetoDataFile() { if(fileWriter!=null) fileWriter.Close(); writeFileStream = new FileInfo(fileName); fileWriter = writeFileStream.CreateText(); } static void CloseDataFile() { Console.WriteLine("\n");
} } }
// program_id WriteToTextFiles.cs // written_by don voils // date_written 12/19/2006 // description This program demonstrates text file output. // using System; using System.IO; namespace WriteToTextFiles { class OutPutData { static string fileName = @"‥\‥\‥\‥\datafile.txt"; static FileStream writeFileStream; static StreamWriter fileWriter; static void Main(string[] args) { OpentoWritetoDataFile(); string customerFirstName; string customerLastName; string customerID; decimal customerBalanceDue; char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { Console.Clear(); Console.Write("\n\nWhat is the customer's ID? "); customerID = Console.ReadLine(); fileWriter.WriteLine(customerID); Console.Write("\n\nWhat is the customer's first name? "); customerFirstName = Console.ReadLine(); fileWriter.WriteLine(customerFirstName); Console.Write("\n\nWhat is the customer's last name? "); customerLastName = Console.ReadLine(); fileWriter.WriteLine(customerLastName); Console.Write("\n\nHow much does the customer owe? "); customerBalanceDue = decimal.Parse(Console.ReadLine()); fileWriter.WriteLine(customerBalanceDue); fileWriter.Flush();
file:///D|/1/final/BBL0124.html (25 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
Console.Write("\n\n\nContinue? (Y/N) "); moreData = Char.Parse(Console.ReadLine()); Console.Clear(); } CloseDataFile(); } static void OpentoWritetoDataFile() { if(fileWriter!=null) fileWriter.Close(); if(writeFileStream!=null) writeFileStream.Close(); // The enumerator FileMode.Create should be // Append if the file already exists and the // program should add to existing data. // writeFileStream = new FileStream(fileName,FileMode.Create, FileAccess.Write); fileWriter = new StreamWriter(writeFileStream); } static void CloseDataFile() { Console.WriteLine("\n"); fileWriter.Close(); writeFileStream.Close(); } } }
// program_id writingBinaryFiles.cs // written_by don voils // date_written 10/30/2006 // description This program writes serialized objects // of the class customer to a binary file. // namespace CustomSerialization { using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Customers; public class theOutputProgram { public static int Main(string[] args) { Customer theCustomer = new Customer(); Stream saveFileStream = File.Open(@"‥\‥\‥\‥\CustomerData.dat",FileMode.Append); BinaryFormatter fileFormatter = new BinaryFormatter(); char moreData = 'Y'; while((moreData == 'Y') || (moreData == 'y')) { clearScreen(); Console.Write("\n\nWhat is the customer's ID? "); theCustomer.customerID = Console.ReadLine(); Console.Write("\n\nWhat is the customer's first name? "); theCustomer.firstName = Console.ReadLine(); Console.Write("\n\nWhat is the customer's last name? "); theCustomer.lastName = Console.ReadLine(); Console.Write("\n\nHow much does the customer owe? "); theCustomer.balanceDue = decimal.Parse(Console.ReadLine()); fileFormatter.Serialize(saveFileStream,theCustomer);
file:///D|/1/final/BBL0124.html (26 von 29) [01.12.2007 04:50:23]
Lecture 14 Examples
clearScreen(); Console.Write("\n\n\nContinue? (Y/N)"); moreData = Char.Parse(Console.ReadLine()); clearScreen(); } saveFileStream.Close(); return 0; } static void clearScreen() { for(int index = 0;index button. When this is done the next dialog should be like the following:
Click the Next > button one more time. When this is done, the following screen should appear. Note that the NothwindConnectionString is being created:
file:///D|/1/final/BBL0126.html (5 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Click the Next > button on this screen and you should see the following after clicking the + sign to the left of both the Tables and Customers. This example will use just the CustomerID, CustomerName and ContactName fields so click the checkboxes to the left of each of these fields and then click the Finish button:
Next click on the Data menu option and select Show Data Source as in the following:
file:///D|/1/final/BBL0126.html (6 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
A Data Sources window like the following should appear:
Click on each of the Customers' fields that were selected one at a time and drag them onto the form. When you do, the following will appear like the following after some adjustments for size and location of these tools:
file:///D|/1/final/BBL0126.html (7 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Notice the tools that were added to the bottom of the form. Next look at the top of the form. Notice tools that were added automatically to the form. For example there are the arrows, the + sign, the red X and the Save button. Each of these tools was added automatically to the form without the need to do any coding just the dragging of the fields onto the form. Change the Text of the Form to Customers and then compile and run the program. What you should see is something like the following:
Notice that when the program runs, that the data from the table is loaded into the form. Using the blue arrows, it is possible to move one record at a time up or down the table or use the blue arrows with the bar to move to the beginning or to the end of the table. By clicking the + sign, blank fields appear in the table permitting the user to add data to a new record. Click this button and add some data to the empty fields as it appears in the graphic below. This can be followed up by clicking the Save button to save the new data into the table in RAM. Notice that the Northwind database was
file:///D|/1/final/BBL0126.html (8 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
attached to the form and the following record is displayed in the table. The table now lists 92 records:
Using the arrows, move around in the different records and observe the field data. Next click the + button once again. Remember that this button is for the purpose of adding records. Notice that the fields are now empty again and the number of records listed is now 93. Enter some data into the fields. Take these steps several times so that there are at least 95 records listed. Notice that there is a X button. This button is for the purpose of deleting records from the table held in RAM. Click it. Notice that the number of records is now 94. By using the arrows and move around in the data, you will notice that the 95th record was deleted. After making these changes, press the Save button. Next shut the program down and then restart it. What should now appear are the 91 records that were in the original database plus the 3 additional ones that you entered. Note: While there were new records stored in RAM, the new records may not have been saved to the table. The claim by one author was that early versions of Visual Studio .NET 2005 do not save the data to the table stored on the disk. However this was fixed and later versions apparently do save the new fields to the database. What I found was that if you leave Visual Studio .NET and go to the bin\Debug folder and double click on the .exe file, following this up by the same steps taken above, the data entered will be saved.
Using the DataGrid View Visual Studio has additional ADO .NET features which may be used to view the data. One of these is the DataGridView. This view shows the data in a format similar to one you would see in a spreadsheet where the records are the rows and the fields are the columns. Using the example above, make the form larger. Make the Size, Minimum Size and the Maximum Size 600, 530. Next click on the Customer table link in the Data Sources dialog like the following:
file:///D|/1/final/BBL0126.html (9 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next drag this link onto the enlarged form and then stretch the DataGrid to look like the following:
After making the above changes have been made, compile and run the program. The form should now look like the following with the data not only in the textboxes but also in the DataGrid below:
file:///D|/1/final/BBL0126.html (10 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Using either the arrows at the top of the form, the vertical scroll on the right of the DataGrid, or by just moving the cursor up and down through the columns, notice how the DataGrid provides a new view and a new way to access this data. As you scrolled through the data, you should have noticed that some of the data in the CompanyName and in the ContactName columns were not viewable. What needs to be done is to format the DataGrid so that the columns are wide enough to permit a complete view of the data in each column. To achieve this objective, do a right click on the DataGrid and select Edit Columns as in the following graphic:
When this is done, the screen should show a view like the following:
file:///D|/1/final/BBL0126.html (11 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Clicking on the field name on the left one at a time, in the Bound Column Properties window, change the Width of CustomerID to 75, CompanyName to 200 and ContactName to 180. Now compile and run the program. The form should now appear like the following:
There are several other modifications that can be made in addition to changing the size of the columns. For example, it is possible to change the appearance of the form. One way of doing this is to right click on the DataGrid and select Properties. Under Properties select the button to the right of : ColumnHeadersDefultCellStyle. Like the following:
file:///D|/1/final/BBL0126.html (12 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
When this button is clicked a CellStyle Builder dialog like the following will appear:
Click on the BackColor button on the right and then the following selections will appear:
file:///D|/1/final/BBL0126.html (13 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Under the Web tab, select Orchid. Now compile and run the program. The DataGrid should now appear like the following:
When you get a chance, experiment with some of the other options in the CellStyle Builder.
Using a Listbox View Other controls may be used as well. For example, it is possible to place a ListBox onto the form and then to connect it to one of the fields. To achieve this objective, using the Toolbox place a ListBox onto the form to the right of the textboxes like the following:
file:///D|/1/final/BBL0126.html (14 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
Next, click on the Listbox and then on Properties. On Properties select DataSource and then customersBindingSource as in the following:
After having selected customerBindingSource for DataSource, click on DisplayMember and select CustomerID as in the following:
file:///D|/1/final/BBL0126.html (15 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
To complete this exercise, place a label with the following text above the listbox: Select Cusomter ID. Compile and run the program. The form should now appear as in the following:
In previous Windows examples, there were only three files that needed to be viewed and copied: Form1.cs, Form1. Designer.cs and Program.cs. However in the program created up to this point, there are several other files as can be seen in looking at the following graphic of the Solution Explorer:
file:///D|/1/final/BBL0126.html (16 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizards on a Single Table
In particular notice the file app.config. Double click on this file listed in the Solution Explorer. Notice that this file contains XML instructions about the configuration of the database as can be seen in the following:
Additional files listed in the Solution Explorer include: ●
Northwind.mdb
●
NorthwindDataSet.xsd ❍
NorthwindDataSet.Designer.cs
❍
NothwindDataSet..xsc
❍
NothwindDataSet.xss
Double click on NorthwindDataSet.Designer.cs and observe all of the code in the file. This code was generated by the IDE and should not be modified.
file:///D|/1/final/BBL0126.html (17 von 17) [01.12.2007 04:50:27]
Using ADO.NET wizard on Multiple Related Tables
Using ADO.NET wizard on Multiple Related Tables This exercise will discuss how a program can be created that permits the viewing of fields from two different but related tables in the Northwind database namely the Customers and Orders tables. Begin by creating the project: CustomerOrders. Change the Text of Form1 to Customer Orders.
Proceed as was done in the previous example except when the tables are being selected. In this case the Server Explorer should show something like the following:
Notice in the graphic above that the following fields have been selected in the Customers table and in the graphic below that the Orders fields listed below have been selected: ●
Customers Table:
file:///D|/1/final/BBL0127.html (1 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
●
❍
CustomerID
❍
CompanyName
❍
ContactName
❍
Phone
Orders Table ❍
OrderID
❍
CustomerID
❍
EmployeeID
❍
OrderDate
These fields from the two related tables will be used in this exercise. Next under the Data menu option, select Show Data Source and the following Data Sources will appear:
file:///D|/1/final/BBL0127.html (2 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
Grab each of the fields for the table: Customers and add them to the form. Arrange them in an attractive manner similar to the following:
Next click on the Orders icon that is listed a part of the Customers listing and drag it onto the form adjusting the size to look similar to the following:
file:///D|/1/final/BBL0127.html (3 von 4) [01.12.2007 04:50:28]
Using ADO.NET wizard on Multiple Related Tables
Next compile and run the program. When you do, a screen similar to the following should appear:
Next click on the arrows and move around in the Customers data. As you move around in this table, the Orders data in the Data Grid below should now reflect those Orders for the Customers viewed as in the following graphic:
This exercise has demonstrated how a form can be made which demonstrates how the ADO.NET can be used on Multiple Related Tables. If you click on the add or the delete buttons, then it adds or deletes the customer records and their related orders.
file:///D|/1/final/BBL0127.html (4 von 4) [01.12.2007 04:50:28]
An Expense Ledger: Using DataSet and Windows Forms
An Expense Ledger: Using DataSet and Windows Forms This section of the lecture will demonstrate the use of a DataSet with a Windows Form. To begin, create a Windows project: ExpenseLedger.cs. Copy the database: expenses.mdb into the bin\Debug folder of the project. Check the using statements at the top of the program to ensure that the following two are there and if not, add them: using System.Data; using System.Data.OleDb;
Change the Text of the form to Expense Ledger. Change the Font to Bold. Change the Size, Minimum Size and Maximum Size to 410, 300. Drag on to the form: five labels, four textboxes, one button and one DateTimePicker. Change the Text of the labels and the button and arrange each of these tools to make the Form look similar to the following:
Change the Form1 constructor to the following: public Form1() { InitializeComponent(); txtGLAccountNumber.Focus(); }
Double click on the Add button. When the event handler opens, add the following code: private void btnAddRecord_Click(object sender, EventArgs e) { // Be sure that the following is all in one line of code. // OleDbConnection expensesConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;
file:///D|/1/final/BBL0128.html (1 von 2) [01.12.2007 04:50:28]
An Expense Ledger: Using DataSet and Windows Forms
Data Source=expenses.mdb"); // Be sure that the following is all in one line of code. // OleDbDataAdapter expensesAdapter = new OleDbDataAdapter("SELECT GLAccountNumber,PayeeName,CheckNumber, CheckAmount,CheckDate FROM Checks", expensesConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(expensesAdapter); DataSet expensesDataSet = new DataSet(); expensesAdapter.Fill(expensesDataSet,"Checks"); DataRow thisRow = expensesDataSet.Tables["Checks"].NewRow(); thisRow["GLAccountNumber"] = String.Format("{0}",txtGLAccountNumber.Text); thisRow["PayeeName"] = String.Format("{0}",txtPayeeName.Text); thisRow["CheckDate"] = checkDate.Value; thisRow["CheckNumber"] = Int32.Parse(String.Format("{0}", txtCheckNumber.Text)); thisRow["CheckAmount"] = Convert.ToDouble(txtCheckAmount.Text); expensesDataSet.Tables["Checks"].Rows.Add(thisRow); expensesAdapter.Update(expensesDataSet,"Checks"); txtGLAccountNumber.Clear(); txtPayeeName.Clear(); txtCheckNumber.Clear(); txtCheckAmount.Clear(); txtGLAccountNumber.Focus(); expensesConnection.Close(); }
Compile and run the program. Enter several checks into the program and click the Add button after each check has been entered. After you have entered several checks, open expenses.mdb in Access and look at the data in the Checks table to see if the data you entered was stored into the database correctly. See the file: ExpenseLedger. cs
file:///D|/1/final/BBL0128.html (2 von 2) [01.12.2007 04:50:28]
Lecture 15 Examples
Lecture 15 Examples Open table as spreadsheet PROGRAM
DEMONSTRATES THE USE OF
AddRowstoCustomers.cs
This program demonstrates how to modify add rows to a table.
ChartOfAccounts.cs
This program demonstrates the use of the reader to read data from the GLAccounts table in the expenses.mdb database.
CustomersAndOrders.cs
This program demonstrates how to view the data in related tables of a database.
DataSetCustomers.cs
This program demonstrates how to view data using a Data Set.
DeleteRowstoCustomers.cs
This program demonstrates how to delete records from a database table data using a Data Set.
expenses.mdb
An Access database that is used in several of the examples in this lecture.
ExpenseLedger.cs
This program along with the Access database: expenses.mdb simulates an Expense ledger.
GLAccounts.cs
This program demonstrates how to find a particular GL Account in the database expenses.mdb GLAccounts table.
ModifyCustomersInMemory. cs
This program demonstrates how to modify data in memory using a Data Set.
Northwind.mdb
An Access database that is used in several of the examples in this lecture.
SelectCustomers2.cs
This program demonstrates how to view data how to find a particular record.
SelectCustomers3.cs
This program demonstrates how to view data how to find a particular record.
SelectCustomers.cs
This program demonstrates how to view data.
// program_id AddRowstoCustomers.cs // written_by Don Voils // date_written 11/16/2006 // description This program demonstrates how to modify add // rows to a table. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName FROM Customers", customerConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}", "Customer ID", "Customer Name");
file:///D|/1/final/BBL0129.html (1 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
Console.WriteLine("{0}\t{1}", " -----------", "--------------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"]); ++numberCustomers; } Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); DataRow thisRow = customerDataSet.Tables["Customers"].NewRow(); numberCustomers = 1; Console.Write("What is the Customer ID you are adding? "); string theID = Console.ReadLine(); Console.Write("\n\nWhat is the Company Name? "); string theName = Console.ReadLine(); thisRow["CustomerID"] = theID; thisRow["CompanyName"] = theName; customerDataSet.Tables["Customers"].Rows.Add(thisRow); Console.WriteLine("# of rows after change: {0}", customerDataSet.Tables["Customers"].Rows.Count); Console.WriteLine("\n\n {0}\t{1}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}", " -----------", "--------------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"]); ++numberCustomers; } Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); customerAdapter.Update(customerDataSet, "Customers"); customerConnection.Close(); } } }
// program_id ChartOfAccounts.cs // written_by don voils // date_written 11/14/2006 // description This program demonstrates the use of the reader // to read data from the GLAccounts table in the // expenses.mdb database. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace ChartOfAccounts {
file:///D|/1/final/BBL0129.html (2 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
class Program { static void Main(string[] args) { OleDbConnection GLAccountConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand(); accessCommand.CommandText = "SELECT GLAccountNumber, GLAccountName FROM GLAccounts"; OleDbDataReader AccountReader = accessCommand.ExecuteReader(); int numberAccounts = 0; Console.WriteLine("\t\tChart of Accounts"); Console.WriteLine(" {0} \t{1}", " GL Account Number", "GL Account Name"); Console.WriteLine("--------------------------------------------"); while (AccountReader.Read()) { ++numberAccounts; Console.WriteLine("{0,3} \t{1}\t\t{2}", numberAccounts, AccountReader["GLAccountNumber"], AccountReader["GLAccountName"]); } Console.WriteLine("\n\nThere are {0} GL Accounts.\n",numberAccounts); AccountReader.Close(); GLAccountConnection.Close(); } } }
// program_id CustomersAndOrders.cs // written_by don voils // date_written 11/18/2006 // description This program demonstrates how to view the data // in related tables of a database. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace CustomersAndOrders { class Program { static void Main(string[] args) { OleDbConnection thisConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter theAdapter = new OleDbDataAdapter( "SELECT CustomerID, CompanyName FROM Customers", thisConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(theAdapter); DataSet thisDataSet = new DataSet(); OleDbDataAdapter customerAdapter = new OleDbDataAdapter( "SELECT * FROM Customers", thisConnection); OleDbDataAdapter ordersAdapter = new OleDbDataAdapter( "SELECT * FROM Orders", thisConnection);
file:///D|/1/final/BBL0129.html (3 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
customerAdapter.Fill(thisDataSet, "Customers"); ordersAdapter.Fill(thisDataSet, "Orders"); DataRelation customersandOrdersRelation = thisDataSet.Relations.Add("CustomerOrders", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]); int numberCustomers = 0; foreach (DataRow customerRow in thisDataSet.Tables["Customers"].Rows) { numberCustomers++; Console.WriteLine("\nCustomer ID: " + customerRow["CustomerID"] + " Company Name: " + customerRow["CompanyName"]); foreach (DataRow orderRow in customerRow.GetChildRows(customersandOrdersRelation)) { Console.WriteLine(" Orders: " + orderRow["OrderID"]); } if (numberCustomers == 10) { Console.WriteLine("\n\nPress the Enter key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 0; } } thisConnection.Close(); Console.WriteLine("\n\nPress the Enter key to continue."); Console.ReadKey(); } } }
// program_id DataSetCustomers.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // using a Data Set. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone");
file:///D|/1/final/BBL0129.html (4 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n", --numberCustomers); Console.ReadKey(); } } }
// program_id DeleteRowstoCustomers.cs // written_by Don Voils // date_written 11/18/2006 // description This program demonstrates how to delete records // from a database table data using a Data Set. // // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NorthwindAdd.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); OleDbCommandBuilder tableBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers,
file:///D|/1/final/BBL0129.html (5 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } DataColumn[] theKeys = new DataColumn[1]; theKeys[0] = customerDataSet.Tables["Customers"].Columns["CustomerID"]; customerDataSet.Tables["Customers"].PrimaryKey = theKeys; Console.Write("\nWhat is the Customer ID for the record you wish to remove? "); string theCustomerID = Console.ReadLine(); try { DataRow rowToDelete = customerDataSet.Tables["Customers"].Rows.Find(theCustomerID); if (rowToDelete != null) { Console.WriteLine("\n{0} is in the table.", theCustomerID); rowToDelete.Delete(); customerAdapter.Update(customerDataSet, "Customers"); Console.WriteLine("\nThat record has been deleted from the database.\n"); } else Console.WriteLine("\n{0} was not in the table.\n", theCustomerID); Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.Clear(); numberCustomers = 1; Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } } catch (Exception e) { Console.WriteLine("\nThat record may not be deleted. {0}", e.Message); } finally { customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n", --numberCustomers); Console.ReadKey(); } } } }
// program_id ExpenseLedger.cs
file:///D|/1/final/BBL0129.html (6 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
// written_by Don Voils // date_written 11/19/2006 // description This program along with the Access database: expenses.mdb // simulates an Expense ledger. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Data.OleDb; using System.Text; using System.Windows.Forms; namespace Expenses { public partial class Form1 : Form {
public Form1() { InitializeComponent(); txtGLAccountNumber.Focus(); } private void btnAddRecord_Click(object sender, EventArgs e) { OleDbConnection expensesConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); OleDbDataAdapter expensesAdapter = new OleDbDataAdapter("SELECT GLAccountNumber,PayeeName,CheckNumber,CheckAmount,CheckDate FROM Checks", expensesConnection); OleDbCommandBuilder thisBuilder = new OleDbCommandBuilder(expensesAdapter); DataSet expensesDataSet = new DataSet(); expensesAdapter.Fill(expensesDataSet,"Checks"); DataRow thisRow = expensesDataSet.Tables["Checks"].NewRow(); thisRow["GLAccountNumber"] = String.Format("{0}",txtGLAccountNumber.Text); thisRow["PayeeName"] = String.Format("{0}",txtPayeeName.Text); thisRow["CheckDate"] = checkDate.Value; thisRow["CheckNumber"] = Int32.Parse(String.Format("{0}",txtCheckNumber.Text)); thisRow["CheckAmount"] = Convert.ToDouble(txtCheckAmount.Text); expensesDataSet.Tables["Checks"].Rows.Add(thisRow); expensesAdapter.Update(expensesDataSet,"Checks"); txtGLAccountNumber.Clear(); txtPayeeName.Clear(); txtCheckNumber.Clear(); txtCheckAmount.Clear(); txtGLAccountNumber.Focus(); expensesConnection.Close(); } } }
// program_id GLAccounts.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates // how to find a particular GL Account // in the database expenses.mdb GLAccounts // table. //
file:///D|/1/final/BBL0129.html (7 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { OleDbConnection GLAccountConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=expenses.mdb"); GLAccountConnection.Open(); OleDbCommand accessCommand = GLAccountConnection.CreateCommand();
accessCommand.CommandText = "SELECT GLAccountNumber, GLAccountName FROM GLAccounts"; OleDbDataReader GLAccountReader; char doAnother; int numberAccounts; do { Console.Clear(); GLAccountReader = accessCommand.ExecuteReader(); numberAccounts = 1; Console.Write("What is the GL Account Number? "); string theGLAccountNumber = Console.ReadLine(); Console.Clear(); bool isThere = false; Console.WriteLine("\n\n {0,-20}\t{1,-20}", "GL Account Number", "GL Account Name"); Console.WriteLine(" {0,-20}\t{1,-20}", "-----------------", "---------------"); while (GLAccountReader.Read()) { if (theGLAccountNumber == String.Format("{0}", GLAccountReader["GLAccountNumber"])) { Console.WriteLine("{0,3}{1,18}\t {2,20}", numberAccounts, GLAccountReader["GLAccountNumber"], GLAccountReader["GLAccountName"]); isThere = true; } ++numberAccounts; } if (!isThere) { Console.WriteLine("\n\nThat account number is not on file!"); } Console.WriteLine("\n\n All {0} of the GL Accounts have been checked.\n\n", --numberAccounts); Console.Write("\nWhat you like to search for another account? (Y/N) "); doAnother = Char.Parse(Console.ReadLine()); GLAccountReader.Close(); } while ((doAnother=='Y')||(doAnother=='y')); GLAccountConnection.Close(); Console.WriteLine("\n\nPress Enter to exit.\n"); Console.ReadLine(); } } }
file:///D|/1/final/BBL0129.html (8 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
// program_id ModifyCustomersInMemory.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to modify data // in memory using a Data Set. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers4 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); OleDbDataAdapter customerAdapter = new OleDbDataAdapter("SELECT CustomerID, CompanyName, Phone FROM Customers", customerConnection); OleDbCommandBuilder theBuilder = new OleDbCommandBuilder(customerAdapter); DataSet customerDataSet = new DataSet(); customerAdapter.Fill(customerDataSet, "Customers"); int numberCustomers = 1; Console.Clear(); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------", "--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; }
Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n", --numberCustomers); Console.Write("What is the number of the customer you want to change the name? "); int customerRecord = Int16.Parse(Console.ReadLine()); customerRecord--; Console.WriteLine("\nThe current name is: {0}\n",customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"]); Console.Write("\nWhat do you want to change the name to? "); string newName = Console.ReadLine(); customerDataSet.Tables["Customers"].Rows[customerRecord]["CompanyName"] = newName; Console.Clear(); Console.WriteLine("The names are now: "); Console.WriteLine("\n\n {0}\t{1}\t\t\t\t{2}", "Customer ID", "Customer Name", "Phone"); Console.WriteLine("{0}\t{1}\t\t\t{2}", " -----------",
file:///D|/1/final/BBL0129.html (9 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
"--------------------", "-------------"); foreach (DataRow theRow in customerDataSet.Tables["Customers"].Rows) { Console.WriteLine("{0,3} {1}\t{2,-35}\t{3}", numberCustomers, theRow["CustomerID"], theRow["CompanyName"], theRow["Phone"]); ++numberCustomers; } customerConnection.Close(); } } }
// program_id SelectCustomers2.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // how to find a particular record. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers2 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers"; int numberCustomers = 1; Console.Write("What is the customer ID? "); string theCustomerID = Console.ReadLine(); Console.Clear(); OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("\n\n{0}\t{1}", " Customer ID", "Customer Name"); Console.WriteLine("{0}\t{1}", " -----------", "-------------"); while (customerReader.Read()) { if(theCustomerID == String.Format("{0}",customerReader["CustomerID"])) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"],customerReader["CompanyName"]); } ++numberCustomers; } customerReader.Close();
file:///D|/1/final/BBL0129.html (10 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n",--numberCustomers); Console.ReadKey(); } } }
// program_id SelectCustomers3.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data // how to find a particular record. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers3 { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName, Phone FROM Customers"; int numberCustomers = 1; Console.Write("What is the Customer ID? "); string theCustomerNumber = Console.ReadLine(); Console.Clear(); OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("\n\n{0}\t{1}\t\t{2}", " Customer ID", "Customer Name","Phone"); Console.WriteLine("{0}\t{1}\t{2}", " -----------", "--------------------", "-------------"); while (customerReader.Read()) { if(theCustomerNumber == String.Format("{0}",customerReader["CustomerID"])) { Console.WriteLine("{0,3} {1}\t{2} \t\t{3}", numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"], customerReader["Phone"]); } ++numberCustomers; } customerReader.Close(); customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been checked.\n\n Press any key to exit.\n",--numberCustomers); Console.ReadKey(); }
file:///D|/1/final/BBL0129.html (11 von 12) [01.12.2007 04:50:30]
Lecture 15 Examples
} }
// program_id SelectCustomers.cs // written_by Don Voils // date_written 11/11/2006 // description This program demonstrates how to view data. // using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace SelectCustomers { class Program { static void Main(string[] args) { OleDbConnection customerConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"); customerConnection.Open(); OleDbCommand accessCommand = customerConnection.CreateCommand(); accessCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers"; int numberCustomers = 1; OleDbDataReader customerReader = accessCommand.ExecuteReader(); Console.WriteLine("{0}\t{1}", " Customer ID", "Customer Name"); Console.WriteLine("{0}\t{1}", " -----------", "-------------"); while (customerReader.Read()) { Console.WriteLine("{0,3} {1}\t{2}",numberCustomers, customerReader["CustomerID"], customerReader["CompanyName"]); ++numberCustomers; } customerReader.Close(); customerConnection.Close(); Console.WriteLine("\n\n All {0} of the customers have been listed.\n\n Press any key to exit.",--numberCustomers); Console.ReadKey(); } } }
file:///D|/1/final/BBL0129.html (12 von 12) [01.12.2007 04:50:30]
List of Tables
List of Tables Lecture 1: Introduction to Business Programming Southern Warehousing Monthly Accounts Profit or Loss Statement Expense Ledger Sales Ledger
file:///D|/1/final/BBL0130.html [01.12.2007 04:50:31]