Download presentation
Presentation is loading. Please wait.
Published byDeborah Baker Modified over 9 years ago
1
Jerry Post Copyright © 1998 1 Database Management Systems Chapter 8 Applications
2
DATABASE 2 Customer Report File Edit Help Application Features Application organization Menu Toolbar Help Transactions Improving forms Customized reports Distributing Applications Sales Report File Edit Help Switchboard
3
DATABASE 3 Application Design Customer Form Order Form Bad design: Enter data twice. Poor design: Memorize data (ID) on one form to enter on second. Better design: Automatically transfer data across forms. Customer 1592 Jane Doe 333 Elm St. Order Customer: 1592 Jane Doe 333 Elm St.
4
DATABASE 4 Application Importance User interface Make users’ jobs easier. Tie input forms and reports. Automate basic tasks Tie to external data collection devices. Help system. Ensure data integrity Validate data. Perform computations. Verify totals. Control user access. Maintain related transactions. Backup and recovery. Decision Support Monitoring of events. Analysis, Graphs, Reports. Statistical analysis and optimization. Forecasts and simulation. Linking to other software. Expert Systems & Intelligence Logic and forward chaining. Analysis and decisions in code. Databases of cases, situations and solutions.
5
DATABASE 5 Purchase ItemQuantity 387610 Sale ItemQuantity 38761 Automated Inventory Inventory table holds quantity- on-hand (QOH). Sale subtracts items from QOH. Purchase adds items to QOH. Need a separate routine to validate the current total. Inventory ItemDescriptionQOH 3876Saddle7 6 16 subtract add
6
DATABASE 6 Application Organization Organized by user needs. Identify user. Outline tasks. Organize forms and reports. Direct users to tasks. Potential drawbacks Too many layers makes it difficult for users to find anything. Poor organization confuses users and requires additional support and training. Build forms and reports. Start with a core concept. Identify most important features. Get them correct. Add features, forms and reports. Issue application updates--number and date! Use menu stubs for incomplete and future work. Make them invisible to the user with the Visible property. Be sure they are disabled.
7
DATABASE 7 User Orientation Database application is a model of the organization. Applications based on user jobs. Flexibility and user control. Application organization User tasks. User control over sequence. Forms Minimize user entry. Anticipation. Reports Easy access from forms. User selection of scope and conditions or filters.
8
DATABASE 8 Initial Menu / Switchboard Starting point for users. Identify the user. From network if possible. Separate log in if needed. Customized for users. Hide restricted options. Different forms as needed. Avoid cluttered screens. Use graphics and color to enhance the presentation. Limit the number of options.
9
DATABASE 9 Switchboard Uses Acts as a directory for the application. Identifies users. Contains startup and shutdown code. Can preload forms in background. Make them invisible. Speed up later usage. Can initiate transaction and security logs. Can establish network connections. Contains copyright and usage notes.
10
DATABASE 10 Sally’s Pet Store: Poor Organization Order Merchandise Item Receive Merchandise Item Sell Merchandise Item Get Customer Data What is wrong? Focus needs to be at higher level (Order, Receipt, Sale); not Item.A You cannot go from Order to Receipt. You cannot go from Receipt to Sale. You need to get customer data before recording the sale.
11
DATABASE 11 Sally’s Pet Store: Better Organization OrdersReceipt Sale Supplier Customer Inventory Items special orders More links--usually as buttons. Separate sales from orders, except for special orders.
12
DATABASE 12 Sally’s Pet Store: Initial VTOC Sales Animals Customers Suppliers Purchase Merchandise Sale Animal Sale Merchandise Customer Receipts Supplier Payments Animal Health Animal Genealogy Purchase Animals Accounting Marketing Employees Sales Report Cash Flow Accounts Payable Accounts Receivable Inventory
13
DATABASE 13 Menus Why a custom menu? Limit user actions. Simplify user interface. Add custom actions. Menus can be activated by keystrokes. Accessibility Touch-typists and heads-down data entry. Sometimes need different menus for each form. FileHelp Contents Search About Rolling Thunder FileHelpEdit Add Customer Delete CustomerCtrl+D Modify Customer Data
14
DATABASE 14 Creating Menus View | Toolbars | Customize Drag and Drop Multilevel menu. Sublevels/hierarchy. Each level is a separate menu with its own name. Menu choices Each entry has a name. Access key: & (e.g., &File). Status Bar Text Actions Submenu. Run any code.
15
DATABASE 15 Toolbars Why toolbars? Single click for complex actions. Commands available across the application / shortcuts. Position and customization by user. Toolbar components Button Text Icon/graphic (bitmap) Tool Tip Status Bar description Action Print ·Identify report ·Ask for single or multiple pages. ·Preview or print. Switchboard Weekly Sales Analysis Build graphs Print reports Export data to spreadsheet
16
DATABASE 16 Creating Toolbars View | Toolbars | New Customizing Add new button. Select from DBMS list. Bring up query/form/report. Run code. Change icon. Modify existing icon. Replace icon. Create your own icon and paste it on the button. Place text label on button. Tool tips are vital. Status bar for description.
17
DATABASE 17 Icons 16 by 16 pixels 16 colors Bright and shaded Dither to mix colors Outline in black
18
DATABASE 18 Activating Toolbars and Menus Install a menu Form: Attach a bar using the form properties. Code On Activate On Deactivate Modify from code Add or remove options Enable/Disable (dim) With myBar.Controls.Add Type:=msoControlButton, Id:=3.Controls(1).Enabled = False.Controls.Add Type:=msoControlButton, Id:=3 End With myBar.Visible = True Set myBar = CommandBars(”Custom1") If user = ”Clerk" Then myBar.Visible = True Else CommandBars(”Database").Reset myBar.Enabled = False End If
19
DATABASE 19 Help On-line help replaces manuals Context sensitive: Pressing F1 key provides information on topic with current focus Hypertext links to related topics Sequential topics Descriptions Examples Definitions / Glossary Contents / overview Index / keywords Full-text search Windows 95 & Win-NT Sally’s Pet Store--Contents Copyright Notice The Firm Introduction Processes Entering Data Sales Animal Health Breeds (and other terms)
20
DATABASE 20 Help Structure Help files are processed by Windows™. Write the help text. Each topic on one page. Give it a unique TOPIC_NAME. Give it a number. Enter the topic number in the database. Forms Controls Create Help project file Map TOPIC_NAME to number. Specify window sizes and colors. Use help compiler to build the help file. Test the help system!
21
DATABASE 21 Writing the Help File Use a word processor that can store a Rich Text Format (rtf) file. Write a single topic on a page. Set unique TOPIC_NAME specified in a footnote (#). Set a title for the topic in the footnote ($). Choose key words for each topic in footnote (K). Identify related topics in a sequence, set by footnote (+): INTRODUCTION:001 Topics Written in any order. Keep a separate list for your own use later. No spaces in topic names. Build links to other topics. Double underline the displayed word. (C-S-d) Type TOPIC_NAME immediately after and make it hidden. (C-S-h) Definitions/glossary words are marked with a single underline (C-u), followed by the TOPIC_NAME (C-S-h). Figures/Bitmaps: Use graphics package to create, edit, set size and reduce to 16 colors. {bml filename.bmp} (Left align) {bmr filename.bmp} (Right)
22
DATABASE 22 Sample Help Page Double Underline: Link textCtrl+Shift+D Hidden text: Link nameCtrl+Shift+H
23
DATABASE 23 Sample Help Project (HCW) MAP Each topic name must be given a number. Files The name of the rtf help file.
24
DATABASE 24 Help Project File (.HPJ) [OPTIONS] Basic setup. title= “Main title/caption” contents = TOPIC_NAME [FILES] Specifies all files used. myhelp.rtf graphics files, etc. [MAP] Maps names to numbers. TOPIC_NAME #### [WINDOWS] Sets windows sizes. [CONFIG] Sets macros and buttons. Major sections: OPTIONS FILES MAP WINDOWS CONFIG
25
DATABASE 25 Context-Sensitive Help Set the help file name in the form properties. Set the topic number (Context Id) for each form or control.
26
DATABASE 26 Transactions Some transactions result in multiple changes. These changes must all be completed successfully, or the group must fail. Protection for hardware and communication failures. example: bank customer transfers money from savings account to checking account. Decrease savings balance Increase checking balance Problem if one transaction and machine crashes. Possibly: give users a chance to reverse/undo a transaction. Performance gain by executing transactions as a block. Savings Accounts Inez:5340.92 4340.92 Checking Accounts Inez:1424.27 Transaction 1. Subtract $1000 from savings. (machine crashes) 2. Add $1000 to Checking. (money disappears) $1000
27
DATABASE 27 Defining Transactions The computer needs to be told which changes must be grouped into a transaction. Turn on transaction processing. Signify a transaction start. Signify the end. Success: save all changes Failure: cancel all changes Usually set inside code in a form. Microsoft Access workspace.BeginTrans workspace.CommitTrans workspace.Rollback Dim wsp As Workspace, dbs As Database, rst As Recordset Set wsp = DBEngine.Workspaces(0) Set dbs = CurrentDb Set rst = dbs.OpenRecordset(...) wsp.BeginTrans DoCmd.RunSQL “UPDATE Savings… ” DoCmd.RunSQL “UPDATE Checking… “ If (MsgBox("Save all changes?", vbQuestion + vbYesNo, " Save Changes") = vbYes) Then wsp.CommitTrans Else wsp.Rollback End If
28
DATABASE 28 Transaction Locks Pessimistic locks Recordset.LockEdits = True Locked from Edit to Update Optimistic locks Recordset.LockEdits = False Compares data between Edit and Update. Used for all external/ODBC. Optimistic: if data has changed, generates error #3197. Pessimistic: Edit can trigger an error if table is already locked by another user. Let users retry update. Unless you need code fully automatic Then consider random wait. Error Handling for Updates On Error Goto lblError rst.Edit ‘ sample partial code rst!Column = Value rst.Update lblExit: Exit Sub lblError: If (MsgBox(Err.Description,_ vbRetryCancel, “Error...”)_ = vbRetry) Then Resume Else ‘ Clean up changes wsp.Rollback ‘ If transactions set Resume lblExit End If End Sub
29
DATABASE 29 Improving Forms Combo Boxes Restricting with WHERE. NotInList to add data. Make it easy for user Click for autoentry. Advanced lookup. Print options. Decision Support Statistical analysis Optimization Simulation Adding Expert System features Automatically compute values. Guide user by asking questions and suggesting answers. Intelligence/logic in code.
30
DATABASE 30 Form Events (Some) Open, Close Load, Unload Activate, Deactivate, Got Focus, Lost Focus Delete, Before Delete Confirm, After Delete Confirm Before Update, After Update Before Insert, After Insert Current (Change row) Click, Double Click Mouse Down, Mouse Move, Mouse Up Key Press, Key Down, Key Up Timer
31
DATABASE 31 1) Open2) Load3) Resize4) Activate5) Current 12 33 b a d 6) Enter 12 33 b a d 7) GotFocus 12 33 b a d 5) Close4) Deactivate3) Unload2) LostFocus 12 33 b a d 1) Exit 12 33 b a d ControlsForms Change rows Event Sequences (Form) Close a Form Open a Form
32
DATABASE 32 1) BeforeUpdate2) AfterUpdate3) Exit4) LostFocus 5) Enter6) GotFocus New data Check it. Saved data Update others. New control Event Sequences (Enter Data) User enters data & focus moves to new control. Difference between Exit and LostFocus If user clicks a different form, then clicks back. LostFocus and GotFocus events will trigger, but not Exit/Enter.
33
DATABASE 33 Triggers and Conditional Changes Enter Can save current value before it is changed. Before Update Test new value before saving it. Verify that user wants to make change. If possible, use database criteria instead. After Update Make changes to other data. Use transactions to ensure all changes are completed. General : Declarations Dim varOld As Variant Sub ctl_Enter varOld = ctl End Sub Sub ctl_Before Update If (MsgBox (“OK to change?”...) = vbNo) Then [ctl] = varOld End If EndSub 32 131 Enter GotFocus Keystrokes Exit BeforeUpdate AfterUpdate time controlevent 131 LostFocus
34
DATABASE 34 Automated Inventory Link Inventory/QOH to SaleItem table on Sale subform query. QuantitySold control On Enter varOld = Quantity If IsNull(varOld) Then varOld = 0 Defined in General : Declarations. AfterUpdate QOH = QOH - (Quantity - varOld) varOld handles user corrections. Need a separate program that verifies and corrects all totals. Allow managers to set QOH by hand. Run separately to correct errors. Security controls on usage. Sales Item Price Quantity QOH 11224.992143 20315.4718 5 User enters initial value.
35
DATABASE 35 Automated Inventory Events ItemQOHQOH-Qty 112145 112143= 145 - 2 112138= 143 - 5 Inventory Initial value. User enters sale of 2 items. User changes value to a 5. Time Event Declarations Dim varOld As Variant On Enter varOld = Quantity If IsNull(varOld) Then varOld = 0 AfterUpdate QOH = QOH - (Quantity - varOld) Corrected code
36
DATABASE 36 Opening Forms for Related Data Open a second form based on value in current form. Print a report for current entry on a form. Customer CustomerID Name Address 11 Lee Gentry 5744 High Street Payments Customer Payments CustomerID 11 DateAmount 2-15-98$97.00 3-15-98$97.00 Print Customer Bill Name Address Balance Due Payments 2-15-98 $97 3-15-98 $97 Sub Payments_Click() Dim stDocName As String Dim stLinkCriteria As String stDocName = "CustomerPayment" stLinkCriteria = "[CustomerID]=" & Me![CustomerID] DoCmd.OpenForm stDocName,,, stLinkCriteria End Sub
37
DATABASE 37 Department Evaluation Division Department Combo Boxes / Hierarchical Data Many business situations use hierarchical relationships Divisions: Departments Category: Product Data entry on a form User select higher level from first combo box. For lower level, select from list that is restricted to those in the higher level. Add a WHERE clause to the lower level combo box SQL. Force the new clause to requery when entry changes. Finance Investments Budgeting Cost Analysis cboDivision cboDivision: AfterUpdate cboDepartment.Requery cboDepartment.RowSource SELECT Department FROM DepartmentList WHERE DepartmentList.Division = [cboDivision];
38
DATABASE 38 Combo Boxes / NotInList Two ways to add to list. Separate button NotInList event To user NotInList is easy. Be careful when adding Give user chance to cancel. Don’t make user enter data twice. Add data to all necessary tables. Set LimitToList = True. Basic structure See if user wants to cancel. Open table, AddNew row. Copy new value. Open form at that value and get additional data. Potential problems Method might not be obvious to user. Difficult to enter data with matching key, e.g., phone number shared by two customers. Might need button as well.
39
DATABASE 39 NotInList Code Set dbs = CurrentDB() Set rst = dbs.OpenRecordset(“Customer”) Set ctl = Me!Customer ctl.Undo If (MsgBox(" Do you wish to add a new Customer? ", vbYesNo, " Customer " & NewData & "is not in list yet. ") = vbYes) Then rst.AddNew rst!CustomerName = NewData strMatch = "[CustomerID] = " & rst!CustomerID rst.UPDATE DoCmd.OpenForm ”Customer",,, strMatch rst.Close Response = acDataErrAdded Else Response = acDataErrContinue End If
40
DATABASE 40 Click Events for Automatic Entry User selects from list. Code sets default values. Rolling Thunder Assembly Clicking on PartID signals that it was installed. Speeds up data entry. Minimizes errors. Rolling Thunder Assembly Sub EmployeeID_Click() [EmployeeID] = Forms![BicycleAssembly]![EmployeeID] [DateInstalled] = Now End Sub Sub ComponentID_DblClick() DoCmd.OpenForm "Component",,, _ "ComponentID=" & Me![ComponentID], acReadOnly End Sub Bicycle Assembly EmployeeID BicycleParts ComponentID EmployeeID
41
DATABASE 41 Advanced Lookup Lists List of items Rolling Thunder Supplies Click shows details. DblClick sets receive date. Button opens matching form to change details. Sort buttons rebuild list query ORDER BY clause. DoCmd.GoToControl "PurchaseID" DoCmd.FindRecord [OrderList] ‘Displaydata If (DoUpdate = True) Then ‘Parameter If (IsNull([ReceiveDate])) Then [ReceiveDate] = Now ‘DblClick-set date SetQuantityReceived (Now) Else ‘If date set, DblClick means remove [ReceiveDate] = Null SetQuantityReceived (Null) End If Forms![ReceiveSupplies].Refresh Forms![ReceiveSupplies]![OrderList].Requery
42
DATABASE 42 ' Global PrintWhereClause As String ' Global PrintOptionResponse As Integer ' It is called as follows: ' PrintWhereClause = "CustomerID = " & [CustomerID] ' DoCmd OpenForm "PrintOptions" "1Print the _____ report for " & CustomerName ' The leading value is the default selection: 1=one record, 2=all records, 3=criteria ' Select Case PrintOptionResponse ' Case 1 ' DoCmd OpenReport "myReport", acViewPreview,, "Customer ID = " & [CustomerID] ' Case 2 ' DoCmd OpenReport "myReport", acViewPreview ' Case 3 ' DoCmd OpenReport "myReport", acViewPreview,, PrintWhereClause ' Case Else ' Do nothing ' End Select ' Be sure to have an ON ERROR section to catch bad where clauses set by users in option 3 Print Options Message Single Item Entire Set Page layout,... Selection Criteria Criteria invisible until user picks 3 Message set by calling subroutine
43
DATABASE 43 Custom Reports Limitations to report writers Limited computations Control over layout Format codes: SGML & HTML Conditional (data driven) changes Color-codes based on data (show negative as red). Data thresholds (over 100,000 different formula). Hints for custom code Be careful with proportional typefaces and graphics. Best to write to a standard file format like RTF or EPS and print with a word processor.
44
DATABASE 44 Report Layout Report Footer Report header Page header Group1 header Group2 header Detail Group2 footer Group1 footer Page footer Report footer Customer Purchases Customer: Jones Order 4748 Item #Value 11987$ 198.75 14847$7462.83 Total$7661.58 Order 5092 Item#Value 73632$ 52.35 Total$ 52.35 Customer Total$7713.93 Page 32
45
DATABASE 45 Report Coding Structure Report Header Loop Test for top of page Test for top of group 1 Test for top of group 2... Perform calculations and subtotals Print detail Increment line/position counters Test for page break Set all prior group values Read next row of data Test for end of groups Last to first Print group footers Report Footer
46
DATABASE 46 Report Coding Define base query first. Write separate lookups if: queries are not available. performance problems. Pages Counter for page numbers. Line counter or position measure, and page size. Groups Accumulator for sum, avg. Counter for average. Prior value to test break.
47
DATABASE 47 Multiple Group Reports
48
DATABASE 48 Paging Complications Print to word processor. User can modify/customize. Need file formats / RTF. Whenever anything is displayed Update page position Test for page break Try to keep group on page. Not possible if too long. Pre-test group before printing. If forced to break across a page, might reprint group headers. All print sections as subroutines. One call to estimate size. Second call to actually print. Bookmarks keep position.
49
DATABASE 49 Report Paging Note: To use bookmark you must set Option Compare Binary!
50
DATABASE 50 Distributing an Access Application Make the application standalone. Runs completely from your forms. Never need to use the Access database menu (Tables, Queries, Forms, Reports). Automatically starts when the database is opened. Tools | Database Utilities | Startup. AutoExec macro. Application format. Standard mdb file. Encrypted mde file. Run-time package (Developer’s Edition). Security (Chapter 10). Installation package (Developer’s Edition).
51
DATABASE 51 Appendix: VB Applications VB Advantages Standalone application. Compiled code (speed). Easy to connect to multiple databases. Support and control over Windows resources. Easier than C++. Drawbacks Requires more programming than Access. Building projects Design and create the data tables. Design and prototype the forms and application design. Create skeleton VB forms (try the Application Wizard and Data Form Wizard). Add features to make the application easier to use.
52
DATABASE 52 Appendix: VB Sales Form Similar to Access Ease of Use features
53
DATABASE 53 Appendix: Sales Form Design Data control Combo box dbGrid
54
DATABASE 54 Appendix: Data Control 1. Type of DBMS 2. Actual database 3. Query or Table
55
DATABASE 55 Appendix: Data Grid Subform Sale Animal Data control for grid (invisible) datSecAnimal Grid control Data control for main form datPrimaryRS ' restrict the grid’s data control query to match main form strSQL = “SELECT … WHERE [SaleID] = " & datPrimaryRS.Recordset![SaleID] datSecAnimal.RecordSource = strSQL ' then refresh the control, which forces a redisplay datSecAnimal.Refresh Reposition Event for datPrimaryRS
56
DATABASE 56 Appendix: Adding Data to a Subform Grid Private Sub grdAnimal_BeforeUpdate(Cancel As Integer) If Not IsNull(grdAnimal.Columns(1).Value) Then datSecAnimal.Recordset.Fields("SaleID").Value = datPrimaryRS.Recordset.Fields("SaleID").Value Else Cancel = True End If End Sub Sale(SaleID, SaleDate, CustomerID, EmployeeID, SalesTax) SaleAnimal(SaleID, AnimalID, SalePrice) An animal is sold by adding a row to the SaleAnimal table in the Animal subform/grid. Application code should automatically copy the current SaleID into the new row.
57
DATABASE 57 Appendix: VB Combo Boxes 3. Name of column to use (ID). 2. Name of column to display. 1. Data control to fill the list. 5. Name of column to receive value. 4. Data control to store choice. SELECT CustomerID, [LastName] & ", " & [FirstName] AS CName, FROM Customer ORDER BY [LastName] & ", " & [FirstName].
58
DATABASE 58 Appendix: Adding New Customers Private Sub cmdNewCustomer_Click() Dim v As Variant ' Create new customer datCustomer.Recordset.AddNew v = datCustomer.Recordset.Fields("CustomerID") datCustomer.Recordset.Update ' get CustomerID, and stick it in the primary/sales recordset datPrimaryRS.Recordset.Edit datPrimaryRS.Recordset.Fields("CustomerID") = v datPrimaryRS.Recordset.Update ' Since all the necessary data is on this form, just fill it out txtFields(8).SetFocus ' If you need, you can open the Customer form, in case there is more data 'frmCustomer.Show 'frmCustomer.SetFocus 'frmCustomer.datPrimaryRS.Recordset.FindNext "CustomerID=" & v End Sub
59
DATABASE 59 Appendix: Data Grid Combo Box AnimalID Name Category … Animal grid (list animal being sold) AnimalID grid: Invisible (list all animals available to sell) 1. Data control to list all animals available. 2. Data grid to display the animals, but start invisible. 3. Turn on the button property for the AnimalID column in the underlying Animal grid. 4. In the button_click event for the underlying Animal grid, make the new AnimalID grid visible. 5. When the clerk double-clicks a row in the AnimalID grid, transfer the selected AnimalID back to the SaleAnimal table.
60
DATABASE 60 Appendix: Grid Control Button Click grdAnimal.Columns(1).Button = True When you define the animal grid, turn on the combo box arrow (button) for the AnimalID column. When the button is clicked, make the new AnimalID grid visible. Private Sub grdAnimal_ButtonClick(ByVal ColIndex As Integer) If (ColIndex <> 1) Then Exit Sub datAnimal.RecordSource = "SELECT AnimalID, Category, Breed, …” datAnimal.Refresh grdAnimalID.Visible = True grdAnimalID.Columns("AnimalID").Width = 720 ' Reset to default values grdAnimalID.Columns("Category").Width = 945 ' in case user changed grdAnimalID.Columns("Breed").Width = 1545 ' them last time grdAnimalID.Columns("Name").Width = 1170 grdAnimalID.Columns("ListPrice").Width = 870 grdAnimal.Columns("ListPrice").NumberFormat = "#,##0.00" grdAnimalID.SetFocus End Sub
61
DATABASE 61 Appendix: Transfer Selection to Table Private Sub grdAnimalID_DblClick() datSecAnimal.Recordset.Edit datSecAnimal.Recordset.Fields("AnimalID") = datAnimal.Recordset.Fields("AnimalID") datSecAnimal.Recordset.Update varTotalAnimalSale ComputeTax datPrimaryRS.UpdateRecord grdAnimal.SetFocus ' Just to be safe grdAnimalID.Visible = False End Sub Code is triggered by double-click event in the grdAnimalID.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.