390 likes | 527 Views
ITEC 334 Fall 2011 Online (Business) Application Development. Topic: Programming Concepts Professor J. Alberto Espinosa. Agenda. Object Orientation Programming Fundamentals. Object Orientation (OO). Object-Orientation (OO). The Idea Behind OO
E N D
ITEC 334 Fall 2011 Online (Business) Application Development Topic: Programming Concepts Professor J. Alberto Espinosa
Agenda • Object Orientation • Programming Fundamentals
Object-Orientation (OO) • The Idea Behind OO • Computer applications are the virtual representation of some real world activity (e.g., buying goods, paying invoices, processing payroll, etc.) • The physical world is composed of physical objects (e.g., people, buildings, automobiles, computers) • Each physical object has properties or attributes (e.g., size, weight, age, name) and behaviors (e.g., purchase, enroll, register, paying) • The idea behind OO is to represent physical objects as virtual objects in a computer application (e.g., courses, students, orders) • By recording their properties (e.g., course name, student ID, order no) and programming their behaviors (e.g., registration, payments, etc.) • OO programming writing software code by creating, manipulating and using objects
Objects and Classes • An object is a person, place, event or other thing • A class is a category or grouping of similar objects • We say that an object (e.g., Prof. Espinosa) is an “instance” of a class (e.g., professors) • An object has: • Attributes (i.e., data; e.g. Courses.Semester) • Behaviors (i.e., programs; e.g., Courses.ModifyCourse( )) • Keeping attributes and methods in the sameobject is a concept known as “encapsulation” • Another important OO concept is “inheritance” • Objects inherit all attributes and methods from their class • Classes inherit all attributes and methods from super-classes
Attributes (or Properties) • A class attribute is like a database field (e.g., clientID, instructorName) • For example, this command in ASP (we will see this later in the semester) retrieves database records into an ASP object called “recordset”: • Set rsCust = Conn.Execute("SELECT ClientID, ClientName FROM Clients“) • ASP creates this record set object we have named rsCust. This object not only has all the data retrieved from the SQL query results, but it also contains other attributes with very useful information provided by ASP, including the number of fields in the recordset, names of those fields, number of records in the set and much more: see http://www.w3schools.com/ado/ado_ref_recordset.asp • An object attribute can be usually accessed with syntax like object.property (e.g., student.name) • For example, a set of ASP commands like these can access values stored in fields in the record set rsCust: • MyFirstCustID = rsCust.fields(“ClientID“) .valueMyFirstCustName = rsCust.fields(“ClientName“) .value
Behaviors (or Methods or Operations) • Methods or Operations are procedures/programs (written in an OO programming language) to update, manipulate or query data in object attributes • Some of them apply to a single object in a class (e.g., create, modify, delete or display data from an object) whereas some others apply over a range of objects (e.g., list a range of products, print course catalog) • A method or operation can usually be executed with syntax like object.method( ) • For example, in ASP (we will see this later in the semester) a command like conn.Execute( ) is a method available to execute an external command (e.g., an SQL query). • The ( ) is used to pass information to the method, e.g., conn.Execute(“SELECT * FROM Clients”) • The ( ) some times are not needed, e.g., rsCust.MoveFirst
Inheritance • Objects inheritoperations and properties from their respective class • Sub-classes can be created under other classes • Sub-classes inherit operations and properties from super-classes • For example, in ASP the Set command creates a sub-class from another class – e.g., this is the typical set of commands you will use to get data from an MS Access database: • Set conn = Server.CreateObject("ADODB.Connection“) ‘create a connection objectconn.open “delivery” ‘open a connection to the delivery database (DSN = delivery)Set rsCust = Conn.Execute("SELECT clientID, clientName FROM clients") • OO languages are great for programming, but not that great to handle persistent (i.e., stored) data. In contrast, database programs are not that great for programming, but they are great at handling persistent data. • Solution: Store data in databases retrieve data into objects manipulate the objects using an OO language store results in database
Application Building Blocks Other development platforms and software languages:Perl C# Python Ruby on Rails • Server-Side Scripting: ASP.NET • ASP.NET object manipulation with • VB.NET software language we will use togenerate HTML code ColdFusion SharePoint WordPress AJAX Java/JSP PhP/LAMP • Client-Side Scripting: • JavaScript programming • Database: • Relational Design • SQL Queries • HTML: • Hand-coding HTML • Automatic generation of HTML code w/scripts iPhone/Mobile RSS/XML HTML 5
HTML and the Document Object Model (DOM) DOM: A convention adopted to represent and access HTML objects by programs and scripts (particularly useful with JavaScript
JavaScript, OO & the Document Object The Document Object– i.e., the web page you are in, used by JavaScript to interact with elements of the web page. For example document.write( ) is a method in JavaScript that writes text in the document object (i.e., the web page being loaded) Example 1 Ex1. document.write(“<h1>Welcome to my Web Page</h1>”); Ex2. text1 = “<h1>Welcome to ”; text2 = “my Web Page</h1>”;document.write(text1 + text2); Example 2 <form name="MyOrder" method="post"> <input type="text" name="Qty“ /> <input type="text" name="Price“ /> etc. </form> <script> var Q1 = document.MyOrder.Qty.value; var P1 = document.MyOrder.Price.value; var total = P1*Q1 ; </script> JavaScript HTML JavaScript
ASP.NET’s OO Programming Environment • Active Server Pages (ASP.NET) is a Microsoft server-side development platform available in Microsoft Internet Information Servers (IIS) • Essentially, ASP.NET consists of a number of object classes that have been already developed by Microsoft and made available to developers like you to facilitate web development • These classes have pre-defined properties and pre-programmed methods to do several things, like: connect to databases, query databases, access data retrieved with database queries, send HTML text and tags to web pages, etc.) • How to do this? By writing scripts using a scripting language (e.g., VisualBasic.NET, Perl, C#) and including commands to manipulate ASP.NET objects to: • Access ASP object properties (i.e., data) and • Invoke ASP object methods (i.e., run available programs).
Important ASP.NET Objects • The Response Object: is the actual response page the web server is generating to send to the browser – i.e., a “response” • Ex1. response.write(“<h1>Welcome to my Web Page</h1>”) • Ex2. text1 = “<h1>Welcome to ” • text2 = “my Web Page</h1>”document.write(text1 + text2) • The Connection Object: to connect to data sources (e.g., databases) • Set conn = Server.CreateObject("ADODB.Connection") ‘create connection object “conn” • conn.open "delivery” ‘open the connection to the database associated with “delivery”DSN • rsOrders = conn.Execute(“SELECT * FROM Orders”) ‘execute a command • The Record Set Object: where database data is stored temporarily – e.g., rsOrders • rsOrders.MoveFirst ‘record set object method to go to the first record in the set • OrderNo = rsOrders.fields(“OrderNo”).value ‘the value property stores the data queried • CustomerName = rsOrders.fields(“CustomerName”).value ‘same thing • rsOrders.MoveNext ‘record set object method to move to the next record in the set • For more information on the record set object, see http://www.w3schools.com/ado/ado_ref_recordset.asp
Embedding SQL in Scripts • Example 1: embedding a literal SQL command: • rsOrders = conn.Execute(“SELECT * FROM Orders”) • Example 2: embedding a an SQL command in a text variable • QueryString = “SELECT * FROM Orders WHERE CompID = ‘IBM’ ” • rsCompanies = conn.Execute(QueryString) • Example 3: concatenating portions of an SQL command • QueryString = “SELECT * FROM Orders WHERE CompID = ” & “ ‘IBM’ ” • rsCompanies = conn.Execute(QueryString) • Example 4 – concatenating multiple text variables into an SQL command • QStr1 = “SELECT CompID, CompName ” • QStr2 = “FROM Companies ” • QStr3 = “WHERE CompType = ” • QStr4 = “Consulting” • QueryString = QStr1 & QStr2 & QStr3 & “ ‘Consulting’ ” • (or) QueryString = QStr1 & QStr2 & QStr3 & “ ‘ ” & QStr4 & “ ’ ”
Programming Languages • A program is simply a list of instructions written for the computer to execute a desired task • The instructions need to be written in a specific language • Examples of software languages: Visual Basic, Java, C++ • A script is a small program embedded within a web page, comingled with HTML, XML, CSS, etc. • Scripting Languages – specifically created to write scripts • Examples of Scripting Languages: VisualBasic.NET (VB.NET), Csharp (C#), Perl, JavaScript (no relationship to Java) • Structured English: the use of English-like commands to illustrate programming concepts (useful because it is language neutral) – we will use it in the next following slides • All programming languages have: • Semantics: the set of possible computations that can be accomplished with the language – i.e., its “meaning” • Syntax: the rules of how to write programs in that language
Language Translation • Source code:humans write software in languages that only humans understand – the programs written by humans is called source code • Object code: computers can’t execute programs from the source code – computers only understand “machine language” • Therefore, source code (the programs we write) need to be translated into object code (what computers can execute) • There are 2 general software translation methods: • Interpretation – source code is translated one line at a time as needed – e.g., JavaScript (the interpreter is in the browser), Classic ASP (the interpreter is in the web server) • Compilation – all source code is translated at once before it is ever used – e.g., Java (compiled by the programmer), ASP.NET (compiled by the web server)
Variables • Think of them as containers of data (in memory) • A variable has a name (e.g., x, Age, Salary) so that the data in that container can be accessed • Variable types – e.g. text, numeric, date, logical • An array a matrix of variables – e.g., Salary(3) • Variable assignment: • x = 4 (store the value of 4 in variable or container x) • x = x + 1 (take whatever is in x and add 1 to it) • Salary = 100000 (note that there are no commas in the number) • Name = “alberto” (note that text data needs delimiters) • Name = Name + “ espinosa” • DateToday = now()
Variable Declarations • Some program language require that you initialize or declare variables before you can use them • For example:VB.NET (notice, no need for semicolon):Dim NameName = “Alberto”JavaScript (notice, it MUST end the command with a semicolon):Var Name = “Alberto”; • Dim Salary(3) ‘this creates an “array” which can store 3 salary values: Salary(0), Salary(1), Salary(2) – confusing, I know – each behave as an individual variable • Implicit declarations: some software languages don’t need variable declarations – they are automatically (i.e., implicitly) declared the first time they are used in a program
Input and Output • An input is a value entered for the program to process (e.g., Login ID) – entered by a user or retrieved from another program or database • An output are the results produced by the program – displayed or printed to the user or fed to another program or database • Note: ‘ is used to write comments in ASP and VB.NET • Example 1 – Visual BasicINPUT EmployeeID, Salary ‘prompt user to enter this dataNewSalary = Salary * 1.10OUTPUT EmployeeID, NewSalary‘screen display outputExample 2 – ASPrs = conn.Execute(“SELECT EmployeeID, Salary FROM Employees”) ‘input datars.MoveFirst ‘go to the first row of the record set • EmployeeID = rs.fields(“EmployeeID”) .valueSalary = rs.fields(“Salary”) .value NewSalary = Salary * 1.10Response.Write(EmployeeID & “ “ & NewSalary) ‘output results into web page
Program Flow • It is the sequence in which program instructions are executed, also known as the program • Program lines are generally executed one at a time in the order that they are written • But some instructions can change the flow (i.e., sequence) • Unconditional branching: changing the program flow without a specified reason • e.g., GoTo 100 (go to instruction line #100) • Except for special cases, unconditional branching is a BAD idea • Conditional branching: changing the program flow when certain conditions are met (much more common) • e.g., If Salary > 100000 then … go to some part of the program • The various instructions and branching conditions in a program is know as the program’s “logic”
IF, ELSE, ENDIF(VB.NET) • IF structures are one of the most popular (conditional branching) programming concepts. e.g.:ifSalary < 100000 then‘you can enter comments like this NewSalary = Salary * 1.15 ‘it is customary to indent for readabilityelse‘this is optional NewSalary = Salary * 1.10end if‘an if statement MUST be coupled with an end if • Nested IF’s:if Salary < 100000 then ‘common error: forgetting thenif YearsOfService > 10 THEN NewSalary = Salary * 1.20else NewSalary = Salary * 1.15end if ‘common error: not spacing end ifelse NewSalary = Salary * 1.10end if
IF, ELSE (JavaScript) • The IF examples from the prior slide would have to be written differently in JavaScript// You can enter comments like this – notice the if block with ( ), { } and ;// Common mistakes: misplacing { }; forgetting the ;if(Salary < 100000){NewSalary = Salary * 1.15;}else {NewSalary = Salary * 1.10;}// No need for end if the } ends the if block • Nested IF’s:// Notice that you can place the { } in other lines// Common mistake: you need one } for each { if (IF Salary < 100000) { if (YearsOfService > 10){NewSalary = Salary * 1.20;}else{NewSalary = Salary * 1.15;}} else {NewSalary = Salary * 1.10;}
Loops (ASP.NET and VB.NET) • Loops are very useful when you want to perform similar calculations a number of times until a certain condition is met. Example – For/Next Loop • NumEmployees = 10 ‘good practice to group key variables togetherTotPayroll = 0 ‘common practice to keep an accumulator or count variable • for i = 1 to NumEmployees TotPayroll = TotPayroll + Salary(i) ‘an array that contains salary amountsnext ‘automatically increases i by 1 ‘ You could have for i = 1 to 10 step 2 above to increase by 2 in each loopExample – Do While Loop • rs = Execute(“SELECT EmpID, Salary, NewSalary FROM Employees”)rs.MoveFirst ‘Start with the first record of the record set rs x = 1 • do while not rs.eof ‘eof means end of file or last record of rs NewSalary(x) = Salary(x) * 1.10 x = x +1 ‘do while doesn’t keep a counter, you must keep it yourself rs.MoveNext ‘advance to the next record in rsloop‘common mistake: every do while needs a loop somewhere else
Loops (JavaScript) Example – For/Next Loopvar NumEmployees = 10;var TotPayroll = 0; for (i = 1; i<=NumEmployees; i++) { // i++ increases i by 1 in each loop; i = i + 2 would increment by 2 // i– – would decrease i by 1 in each loop TotPayroll = TotPayroll + Salary(i); } ‘no need for next– the } keeps the for block together Example – Do While Loopvar i = 0; do { document.write("<p> The value of i is ” + i + "</p>"); i+=2; }/increment i by 2 while(i<=20); /stop after i exceeds 20
Functions (VB.NET) • Built-in – every software language has built in functions, examples: • now() gives today’s date and time • Sum(2,3,5) – adds 2+3+5 • DateSerial(2001,2,1) – converts date to 2/1/2001 format • Defined– you need to create them – see agefunction below • Functions are created (programmed) first and then invoked • Functions often include parameters, but they don’t have to • Functions often return a result, but they don’t have to • VB.NET Example: • First define the function: • functionage(BirthDate) DaysSinceBirth = now() – BirthDateage = int(DaysSinceBirth/365)end function • Then invoke the function as needed with something like: • MyAge = age(DateSerial(1990,2,4)) Parameter No Parameter Value returned
Functions (JavaScript) JavaScript Example functionsquareMe(x) {varMySquare = x*x;returnMySquare; } Somewhere else in the program you can use something like: vari;for(i=1; i<=5; i++){document.write(“<p>The square of " + i + " is " + squareMe(i));}
Example: Counting Chocolates (in Structured English) Var color() ‘declare a chocolate color variable array Var flavor() ‘declare a chocolate flavor variable array TotChocolates() ‘declare a chocolate counter variable array color[1] = “red”; color[2] = “blue”; color[3] = “orange” ‘assign colors flavor[1] = “dark”; flavor[2] = “milk”; flavor[3] = “caramel” ‘assign flavors TotChocolates[1] = TotChocolates[2] = TotChocolates[3] = 0 ‘set chocolate counters to 0 GrandTotal = 0 ‘set student counter to 0 NumStudents = 0 ‘set student counter to 0 VarStudentName() ‘declare a student name variable array For n = 1 to Last Student ‘loop through each student StudentName[n] = Input StudentName‘Get student name variable array NumStudents = NumStudents + 1 ‘Count student TotChocolates[1] = TotChocolates[1] + Input “Number of red chocolates?” TotChocolates[2] = TotChocolates[2] + Input “Number of blue chocolates?” TotChocolates[3] = TotChocolates[3] + Input “Number of orange chocolates?” GrandTotal = GrandTotal + TotChocolates[1] + TotChocolates[2] + TotChocolates[3] Next n‘next student For i = 1 to 3 ‘display counting results by color Output “Total Number of ” + color[i] + “chocolates “ + of flavor “ + flavor[i] + = “ + TotChocolates[i] Next I Output “Total Number of chocolates = “ + GrandTotal‘display grand total
Exercise 1:Car Loan Payments You get a 3-year, $10,000 car loan from the bank at a 3% annual interest. How much are your monthly payments?
Exercise (The math behind the solution) First, let’s understand the mathematics behind the required calculation: Payments are made monthly, not yearly, so we need to figure out the number of payment periods and the compounding interest per period (i.e., per month). L = $10,000 n = Months = 12 * Years = 12 * 3 = 36 i = Monthly Interest = Annual Interest / 12 = 0.03 / 12 = 0.0025 Monthly Payment = L * i * (1 + ) Monthly Payment = 10000 * 0.0025 * (1 + ) = 290.81 1 (1 + i) n - 1 1 (1 + 0.0025) 36 - 1
Exercise (The JavaScript Program for 3 yrs only) // Declare and initialize variables var LoanAmount = 10000; var annualRate = 0.03; // The percent below is only to display 0.03 as 3% - not needed to calculate var annualPercent = annualRate*100; // Compute the monthly interest rate and total number of (monthly) payments var monthlyRate = annualRate/12; var months = 12*yrs; // Now a tough one, apply the monthly payment formula // Notes: In JavaScript Math.Pow(x,n) calculates xn // See how I use parentheses to ensure the proper computation sequence // You can break a single instruction into multiple lines // the command continues until it finds the ; var monthlyPayment = LoanAmount * monthlyRate * (1 + 1 / ( (Math.pow( (1+monthlyRate), months) ) - 1) ); // The toFixed(n) is a JavaScript method to format to n decimals monthlyPayment = monthlyPayment.toFixed(2);
Exercise (Expressions) // Let’s look more closely at the expression: LoanAmount * monthlyRate * (1 + 1 / ( (Math.pow( (1+monthlyRate), months) ) - 1) ); // Expressions evaluate in this general order: (1) inner parenthesis; (2) outer// parenthesis; (3) power operations; (4) multiplications and divisions; // (5) additions and subtractions; and (6) when equal, left to right LoanAmount * monthlyRate * (1 + 1 / ( (Math.pow( (1+monthlyRate), months) ) - 1) ); 1st 1+i 2nd {(1+i), n} 2nd (1+i)n 3rd (1+i)n 4th (1+i)n -1 1 5th 1+ (1+i)n -1
Exercise 2: Counting Bills You need to pay a payroll for several workers in cash. You have each individual salary amount in a database and you need to bring to the job site an “exact” amount of cash to pay everyone without having to receive change. Write a program that will read all salaries from a database and then compute the total number of 20, 10, 5 and 1 dollar bills you need to get from the bank to pay everyone their exact salary.
Structured English Solution – 1 Employee Only) SalaryPmt = 1,239 B20 = Integer(SalaryPmt/20) ‘# $20 bills Remainder = SalaryPmt – 20*B20 B10 = Integer(Reminder/10) ‘# $10 bills Remainder = Reminder – 10*B10 B5 = Integer(Reminder/5) ‘# $5 bills B1 = Reminder – 5*B5 ‘# $1 bills Output B20, B10, B5, B1
Exercise (Structured English Solution) NumEmployees = 10 ‘change this value for more or less employees VarSalaryPmt() ‘declare variable as an array Payroll = 0 ‘create a variable to accumulate salary payments B20 = B10 = B5 = B1 = 0 ‘counters for number of bills For i = 1 to NumEmployees ‘loop through each employee Input SalaryPmt[i] Payroll = Payroll + SalaryPmt [i] B20 = B20 + Integer(SalaryPmt [i]/20) Remainder = SalaryPmt [i] – 20*B20 B10 = B10 + Integer(Reminder/10) Remainder = Reminder – 10*B10 B5 = B5 + Integer(Reminder/5) B1 = Reminder – 5*B5 Next i Output Payroll, B20, B10, B5, B1