Wednesday, January 28, 2015

Word and Dictionary Example

Here is the code for the WordClass

package com.spconger.DictionaryProgram;

public class Word {
 /*************************
  * this class store the content
  * of a word and definition
  * It has a toString() method
  * that concatenates the word and
  * a definition with a dash between
  */
 //private fields
 private String word;
 private String definition;
 
 public String getWord() {
  return word;
 }
 public void setWord(String word) {
  this.word = word;
 }
 public String getDefinition() {
  return definition;
 }
 public void setDefinition(String definition) {
  this.definition = definition;
 }
 
 //this overrides the toString method
 //that comes from object
 public String toString(){
  return getWord() + "--" + getDefinition();
 }

}

Here is the MyDictionary class

package com.spconger.DictionaryProgram;

import java.util.ArrayList;

public class MyDictionary {
 /*****
  * this class stores the Word objects
  * in an Arraylist. It provides methods
  * for adding words, removing them and 
  * returning the whole list of words
  */
     private ArrayList<Word> words;
     
     //initialize the ArrayList in the constructor
     public MyDictionary(){
      words = new ArrayList<Word>();
     }
     
     //add words to the list
     public void addWord(Word w){
      words.add(w);
     }
     
     //remove words from the list
     public void removeWord(Word w){
      for(Word wd : words){
       if(wd.getWord().equals(w.getWord())){
        words.remove(wd);
       }//end if
      }//end for
     }//end removeword
     
     //return the whole list of words
     public ArrayList getWords(){
      return words;
     }
}

Here is the Form Again

package com.spconger.DictionaryProgram;

//import allthe various form elements
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class WordForm {

 /***************
  * this class creates the form to add 
  * words and display the results in a 
  * JList object.  The form contains
  * four panels: A border panel to orient
  * the others, A grid panel that contains
  * labels and textboxes, a scrollpane 
  * with a list in the center and a 
  * flow panel with the buttons at
  * the bottom
  */
 private JFrame frame;
 private JPanel borderPanel;
 private JPanel newWordPanel;
 private JPanel buttonPanel;
 private JScrollPane scrollPane;
 private JList wordList;
 private JLabel wordPrompt;
 private JTextField wordText;
 private JLabel defPrompt;
 private JTextField defText;
 private JButton addButton;
 private JButton getWordsButton;
 private JButton exitButton;

 //instantiate the dictionary class
 private MyDictionary tech;

 public WordForm() {
  createFrame();
  tech = new MyDictionary();
 }

 private void createFrame() {
  frame = new JFrame();
  frame.setBounds(100, 100, 300, 300);
  frame.add(createBorderPanel());
  frame.setVisible(true);
 }

 private JPanel createBorderPanel() {
  borderPanel = new JPanel();
  borderPanel.setLayout(new BorderLayout());
  borderPanel.add(createNewWordPanel(), BorderLayout.NORTH);
  borderPanel.add(createScrollPane(), BorderLayout.CENTER);
  borderPanel.add(createButtonPanel(), BorderLayout.SOUTH);
  return borderPanel;
 }

 private JPanel createNewWordPanel() {
  newWordPanel = new JPanel();
  newWordPanel.setLayout(new GridLayout(2, 2));
  wordPrompt = new JLabel("Enter Word");
  wordText = new JTextField();
  defPrompt = new JLabel("Enter Definition");
  defText = new JTextField();
  newWordPanel.add(wordPrompt);
  newWordPanel.add(wordText);
  newWordPanel.add(defPrompt);
  newWordPanel.add(defText);
  return newWordPanel;
 }

 private JScrollPane createScrollPane() {
  wordList = new JList();
  // add the selection listener to the list
  // wordlist.addListSelectionListener(new SelectionListener());
  scrollPane = new JScrollPane(wordList);
  scrollPane.setBounds(20, 20, 100, 200);

  return scrollPane;
 }

 private JPanel createButtonPanel() {
  buttonPanel = new JPanel();
  buttonPanel.setLayout(new FlowLayout());
  addButton = new JButton("Add Word");
  addButton.addActionListener(new AddButtonListener());
  getWordsButton = new JButton("Get Words");
  getWordsButton.addActionListener(new GetWordsListener());
  exitButton = new JButton("Exit");
  exitButton.addActionListener(new ExitListener());

  buttonPanel.add(addButton);
  buttonPanel.add(getWordsButton);
  buttonPanel.add(exitButton);

  return buttonPanel;
 }

 private class AddButtonListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
   //in this method we add a word object
   //to the dictionary class
   Word w = new Word();
   w.setWord(wordText.getText());
   w.setDefinition(defText.getText());
   tech.addWord(w);

   wordText.setText("");
   defText.setText("");
  }

 }

 private class GetWordsListener implements ActionListener {

  @Override
  //here we write to the JList
  public void actionPerformed(ActionEvent e) {
   ArrayList<Word> words = tech.getWords();
   DefaultListModel model = new DefaultListModel();

   for (Word w : words) {
    model.addElement(w.toString());
   }
   wordList.setModel(model);
  }

 }

 private class ExitListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent e) {
   System.exit(0);

  }

 }
}

Here is the Program class

package com.spconger.DictionaryProgram;

public class Program {

 public static void main(String[] args) {
  WordForm wf = new WordForm();

 }

}

Here is a picture of the program running

Code for WordForm

Here is the code for the word form. I thought I would give it to you to save a little time. I have not given you the word class or the TechnicalDictionary class. We will do them together.

package com.spconger.TechDictionary;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class WordForm {
 
 private JFrame frame;
 private JPanel borderPanel;
 private JPanel newWordPanel;
 private JPanel buttonPanel;
 private JScrollPane scrollPane;
 private JList wordList;
 private JLabel wordPrompt;
 private JTextField wordText;
 private JLabel defPrompt;
 private JTextField defText;
 private JButton addButton;
 private JButton getWordsButton;
 private JButton exitButton;
 
 private TechnicalDictionary tech;
 
 public WordForm(){
  createFrame();
  tech = new TechnicalDictionary();
 }
 
 private void createFrame(){
  frame = new JFrame();
  frame.setBounds(100, 100, 300, 300);
  frame.add(createBorderPanel());
  frame.setVisible(true);
 }
 
 private JPanel createBorderPanel(){
  borderPanel = new JPanel();
  borderPanel.setLayout(new BorderLayout());
  borderPanel.add(createNewWordPanel(), BorderLayout.NORTH);
  borderPanel.add(createScrollPane(),BorderLayout.CENTER);
  borderPanel.add(createButtonPanel(), BorderLayout.SOUTH);
  return borderPanel;
 }
 
 private JPanel createNewWordPanel(){
  newWordPanel = new JPanel();
  newWordPanel.setLayout(new GridLayout(2,2));
  wordPrompt=new JLabel("Enter Word");
  wordText = new JTextField();
  defPrompt = new JLabel("Enter Definition");
  defText = new JTextField();
  newWordPanel.add(wordPrompt);
  newWordPanel.add(wordText);
  newWordPanel.add(defPrompt);
  newWordPanel.add(defText);
  return newWordPanel;
 }
 
 private JScrollPane createScrollPane(){
  wordList = new JList();
  //add the selection listener to the list
  //wordlist.addListSelectionListener(new SelectionListener());
  scrollPane = new JScrollPane(wordList);
  scrollPane.setBounds(20, 20, 100, 200);
 
  
  return scrollPane;
 }
 
 private JPanel createButtonPanel(){
  buttonPanel = new JPanel();
  buttonPanel.setLayout(new FlowLayout());
  addButton = new JButton("Add Word");
  addButton.addActionListener(new AddButtonListener());
  getWordsButton = new JButton("Get Words");
  getWordsButton.addActionListener(new GetWordsListener());
  exitButton = new JButton("Exit");
  exitButton.addActionListener(new ExitListener());
  
  buttonPanel.add(addButton);
  buttonPanel.add(getWordsButton);
  buttonPanel.add(exitButton);
  
  return buttonPanel;
 }
 
 private class AddButtonListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   Word w = new Word();
   w.setWord(wordText.getText());
   w.setDefinition(defText.getText());
   tech.addWord(w);
   
   wordText.setText("");
   defText.setText("");
  }
  
 }
 
 private class GetWordsListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   ArrayList words = tech.getWords();
   DefaultListModel model = new DefaultListModel();
   
   for(Word w: words){
    model.addElement(w.toString());
   }
   wordList.setModel(model);
  }
  
 }
 private class ExitListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   System.exit(0);
   
  }
  
 }
}

Insert Update Delete

--insert update delete
use Automart

--basic insert, inserting two rows
Insert into Person (LastName, FirstName)
values('Jaunes', 'Lindsey'),
('Norton', 'Martin')

--insert with a subquery
Select * From Customer.Vehicle
Insert into Customer.Vehicle(LicenseNumber, VehicleMake, VehicleYear, PersonKey)
Values('EFG123', 'Pontiac', '1969', 
(Select Personkey From Person Where LastName='Norton' and Firstname='Martin'))

--a set of inserts, inserting a new person
--a vehicle, a registered customer
--and a vehicle service
Insert into Person(lastName, firstname)
Values('Ignatius', 'Gonzaga')

--IDENT_CURRENT ('TABLENAME') is a function that returns the last
--identity (autonumber) created in the table named
Insert into Customer.Vehicle(LicenseNumber, VehicleMake, VehicleYear, PersonKey)
Values('123TWS', 'Fiat', '2012',IDENT_CURRENT('Person'))

Insert into Customer.RegisteredCustomer(Email, CustomerPassword, PersonKey)
Values ('gonzaga@gmail.com', 'gpass', IDENT_CURRENT('Person'))

INsert into Employee.VehicleService(VehicleID, LocationID, ServiceDate, ServiceTime)
values(IDENT_CURRENT('Customer.Vehicle'), 2, getDate(), getDate())

Select * from Customer.Vehicle

Select * From Employee.VehicleService

--create a temp table
Create table PersonB
(
    personkey int,
 LastName nvarchar(255),
 FirstName nvarchar(255)
)

--insert all the records from person into personb
Select * from PersonB
Insert into PersonB(personkey, LastName, FirstName)
Select personkey, LastName, firstname from Person

--updates: these are the most dangerous statments
--make sure you have an appropriate where clause for criteria
Select * From customer.vehicle
Update PersonB
Set Firstname = 'Jason' 
Where PersonKey=1

Update Customer.Vehicle
Set VehicleMake='firebird',
LicenseNumber='GFE123'
Where VehicleID=47

--manually begin a transaction
Begin transaction

Update Person
Set LastName='Smith'
where personkey=13

Select * From Personb

--rollback undoes any thing done during the transaction
rollback tran
--commit writes it
Commit tran

Delete from Person where personKey > 20

--removes the actual table and any data in the table
Drop table PersonB
--truncate is basically the same as delete
Truncate table Person

Monday, January 26, 2015

Swing form examples

package com.spconger.FormLayouts;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FormLayout {
 JFrame frame;
 JPanel panel1;
 JPanel borderPanel;
 JPanel buttonPanel;
 JLabel label1;
 JLabel label2;
 JTextField textName;
 JButton button;
 JButton exitButton;
 
 public FormLayout(){
  
  createFrame();
  
 }
 
 private void createFrame(){
  frame = new JFrame();
  frame.setBounds(100, 100, 400, 200);
  frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
  frame.add(createBorderPanel());
  frame.setVisible(true);
 }
 
 private JPanel createBorderPanel(){
  borderPanel= new JPanel();
  borderPanel.setLayout(new BorderLayout());
  borderPanel.add(createPanel(), BorderLayout.NORTH);
  borderPanel.add(createButtonPanel(), BorderLayout.SOUTH);
  return borderPanel;
  
 }
 
 private JPanel createButtonPanel(){
  buttonPanel = new JPanel();
  buttonPanel.setLayout(new FlowLayout());
  button = new JButton("Click");
  button.addActionListener(new ButtonListener());
  exitButton = new JButton("Exit");
  exitButton.addActionListener(new ExitListener());
  buttonPanel.add(button);
  buttonPanel.add(exitButton);
  return buttonPanel;
 }
 
 private JPanel createPanel(){
  panel1=new JPanel();
  panel1.setLayout(new GridLayout(2,2));
  label1 = new JLabel("Enter Your name");
  textName=new JTextField(25);
  
  label2=new JLabel();
  panel1.add(label1);
  panel1.add(textName);
  panel1.add(label2);
  
  return panel1;
 }
 
 private class ButtonListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   label2.setText("Hello, " + textName.getText());
   
  }
  
 }
 
 private class ExitListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   System.exit(0);
   
  }
  
 }

}

Requirements and Business Rules

Requirements-Things the database has to do (for each stakeholder)

The database must • Allow registered users to post reviews
• Registered users can enter comments on Reviews
• Track books and authors
• Books reviewed will be rated
• Keep track of registered reviewers
• Assign categories to books
• The database will be searchable by Title, ISBN,
Author, Rating, Category, Date of Review, Reviewer,
publication date

Security Requirements

• Only registered users can leave reviews or comments
• A Registered user can only edit their own reviews
and comments
• All users can read and search database content

Business Rule

More how information is entered and accessed

• Only Registered users can enter reviews Comments
• Only Registered users can leave comments
• All reviews and comments must be signed
• To register a user must agree to terms,
provide a username and password and an valid email
• All passwords will be hashed
• Numerical ratings will be from 1 to 5 with 5 being best
• For a new review, if the book is not currently in the
database, the reviewer will enter it.
• Allow reviews of self-published books
• Violation of terms can get a reviewer removed from
database

Entities and Attributes

Nouns: users, Reviews, comments, books, authors, reviewers, categories, passwords, titles, ISBN, ratings, Publication Date, Email

Entities—people or objects the database is concerned with (These will probably become your tables)


Users
Books (Title, ISBN, Publication Date)
Authors (Name, Dates, Country of Origin)
Reviews (Date, Rating, Reviewer, book, Review)
Reviewers (username, password, email)
Categories (Category Name, Category Description)
Comments (Date, Book, Reviewer, Comment)

Keys

Candidate Keys –potential primary keys
Natural keys—are attributes that belong naturally to the entity
Surrogate keys—randomly assigned numbers or values
Composite keys—combinations of attributes to for a key

Sub Queries

--sub queries
use Automart
--If you want to see which service has the max price you
--need to use a subquery in the where clause
Select ServiceName, max(servicePrice) From Customer.AutoService
Group by ServiceName

Select ServiceName, ServicePrice From Customer.Autoservice
Where ServicePrice = (Select max(ServicePrice) from Customer.Autoservice)

--you can also use subqueries in the select clause
Select ServiceName, ServicePrice, (Select Max(ServicePrice) From customer.AutoService) as Maximum,(Select Max(ServicePrice) From customer.AutoService)-servicePrice as [Difference]
From Customer.AutoService


--this one goes a little crazy, the idea is that
--we will show the total count of auto's served
--the we will show the counts for each individual
--location and then what percent each represents
--of the total.
--there are three casts. The innermost cast converts
--the division to decimal to preserve the decimal part
--(count returns an integer)
--the next cast (second one in) converts the whole
--result to decimal to limit the number of decimal places
--showing. The outermost cast converst the whole expression
--to nvarchar in order to concatinate the % sign in
--
Select 
(Select Count(*) From Employee.VehicleService) Total,
LocationName, count(*) [Number per Location], 
cast(cast(cast (count(*) as decimal(4,2))
 / (Select Count(*) From Employee.VehicleService) * 100 as decimal(4,2)) 
 as Nvarchar) + '%' [Percent]
From Employee.VehicleService vs
inner join Customer.location loc
on vs.LocationID=loc.LocationID
Group by LocationName

--the in keyword returns any value that matches
--one of the values in the result set
--here the second query
Select Servicename from Customer.AutoService
Where AutoServiceID not in 
(Select AutoserviceID From Employee.VehicleServiceDetail)

--using not with in has the same result as an outer join
Select LocationName from Customer.Location
 where LocationID not in 
 (Select LocationID from Employee.VehicleService)
 
Select LocationName from Customer.Location
 where LocationID in 
 (Select LocationID from Employee.VehicleService)

 Select * From customer.AutoService

 --You can link several tables with "in"
--the logic is the same as for joins
--primary key to foreign key
--follow the relationship path to get the data
--you want
 Select LicenseNumber, VehicleMake, VehicleYear From Customer.vehicle
 Where vehicleID in
 (Select VehicleId from Employee.VehicleService 
 where VehicleServiceID in 
 (Select VehicleServiceID from Employee.VehicleServiceDetail
 Where AutoserviceID in 
 (Select AutoserviceID from Customer.AutoService 
 where ServiceName='Replace Alternator')))

 --exits returns a boolean yes/no
 Select * From Employee.VehicleServiceDetail 
 Where exists (Select AutoServiceID from Employee.VehicleServiceDetail where AutoserviceID =7)

--I often use exists to test for the existence of an object 
--if exists
 if exists
  (Select name from sys.Databases where name = 'CommunityAssist')
 Begin
 print 'yep, it''s here'
 End

 Select * from sys.Databases
 --The MagazineSubscription database is available in canvas files
 use MagazineSubscription
 Select * from Customer
 Select * From Magazine
 Select * From MagazineDetail
 Select * From SubscriptionType
 Select * From Subscription

--a correlated subquery is when the subquery uses a value in the 
 --outer query as part of its criteria
 --it results in something resembling a recursive function
 --in this case what it does is makes sure that
 --like is compared to like
 --subscription type 1 (one year) is compared only to other
 --subscription type 1's and subscription type 5 (five year) 
 --is compared only to other subscription type 5's etc.

 Select avg(SubscriptionPrice) From MagazineDetail where
 SubscriptTypeID=5

 Select SubscriptTypeId, MagDetID, SubscriptionPrice 
 From MagazineDetail md
 Where SubscriptionPrice >= 
 (Select Avg(SubscriptionPrice) From MagazineDetail md2
 where md.SubscriptTypeID=md2.SubscriptTypeID)
 And SubscriptTypeID = 5
 order by SubscriptTypeID

 

Wednesday, January 21, 2015

Joins


--Joins
--inner joins 
use Automart
Select * from Customer.RegisteredCustomer

--simple inner join using inner join syntax
--inner joins retrurn only matching records from
--the joined tables
Select LastName, Firstname, Email, CustomerPassword
from Person 
Inner Join Customer.RegisteredCustomer
on person.Personkey=Customer.RegisteredCustomer.PersonKey

--another, older way to join tables
--it uses the where clause to make the join
--it seems easier but is more dangerous and can
--result in unintended cross joins
Select LastName, Firstname, Email, CustomerPassword
From Person p, Customer.RegisteredCustomer rc
Where p.Personkey=rc.PersonKey

--intentional cross join
Select LastName, Firstname, Email, CustomerPassword
From Person p
Cross join Customer.RegisteredCustomer

--multitable inner join
 Select LastName, Firstname, Email, CustomerPassword,
 VehicleMake, VehicleYear, LicenseNumber, serviceDate
 From Person p
 inner join Customer.RegisteredCustomer rc
 on p.Personkey=rc.PersonKey
 inner join Customer.vehicle v
 on p.Personkey = v.personkey
 inner join Employee.VehicleService vs
 on v.VehicleId=vs.VehicleID

 --same join with where clause syntax
 Select LastName, Firstname, Email, CustomerPassword,
 VehicleMake, VehicleYear, LicenseNumber, serviceDate
 From Person p, Customer.RegisteredCustomer rc, Customer.Vehicle v, 
 Employee.VehicleService vs
 Where p.Personkey=rc.PersonKey
 And v.PersonKey=p.Personkey
 And v.VehicleId=vs.VehicleID
 And LastName='Anderson'

 --insert to have an unmatched value
 Insert into Customer.Autoservice( ServiceName, ServicePrice)
 values ('Replacing Upholstry',900.50)

 --outer joins return all the records from one table
 --and only matching records from the other
 --in a left join the first table named returns all its records
 --while the second one only returns matching records
 --a right outer join it is just flipped
 --the first table returns only matching records and the
 --second table returns all, matched or unmatched
 Select Distinct ServiceName, ServicePrice, vsd.AutoServiceID
 From Customer.AutoService a 
 left outer join Employee.VehicleServiceDetail vsd
 on a.AutoServiceID=vsd.AutoServiceID

 --another outer join
 Select Distinct ServiceName, ServicePrice, vsd.AutoServiceID
 From Customer.AutoService a 
 join Employee.VehicleServiceDetail vsd
 on a.AutoServiceID=vsd.AutoServiceID

 --see only the nonmatching records
 --the null in vsd.autoserviceID 
 --is only in the result set
 Select Distinct ServiceName, ServicePrice, vsd.AutoServiceID
 From Customer.AutoService a 
 left outer join Employee.VehicleServiceDetail vsd
 on a.AutoServiceID=vsd.AutoServiceID
 Where vsd.AutoServiceID is null

 --another
 Select LastName, firstName, rc.Personkey
 From Person p
 left outer join Customer.RegisteredCustomer rc
 on p.Personkey=rc.PersonKey
 where rc.PersonKey is null

 --and another
 Select Distinct LocationName, vs.LocationId
 From Customer.Location loc
 left outer join Employee.VehicleService vs
 on loc.LocationID=vs.LocationID
 Where vs.LocationID is null

 --a full join returns all the records
 --from both tables whether they are 
 --matched or not
 Select LocationName, vs.LocationId
 From Customer.Location loc
 full join Employee.VehicleService vs
 on loc.LocationID=vs.LocationID

Select LocationName, Month(ServiceDate) as [Month], Count(VehicleServiceID)  as [Count]
From Customer.Location loc
inner join Employee.VehicleService vs
on loc.LocationID=vs.LocationID
Where LocationName='Spokane'
Group by LocationName, Month(ServiceDate)
having count(VehicleServiceID) > 2


Thursday, January 15, 2015

The Vehicle Example

package com.spconger.VehicleExample;

public class Program {

 public static void main(String[] args) {
  Display d = new Display();
  
  
 }

}


package com.spconger.VehicleExample;

public class Vehicle {
 /*
  * Class can contain methods
  * Constants and variables (class level fields)
  * constructor
  */
 //private fields
 private int passengers;
 private int fuelCapacity;
 private int mpg;
 
 //public getter and setters
 //accessors and mutators
 public int getPassengers(){
  return passengers;
 }
 
 public void setPassengers(int passengers){
  this.passengers=passengers;
 }

 public int getFuelCapacity() {
  return fuelCapacity;
 }

 public void setFuelCapacity(int fuelCapacity) {
  this.fuelCapacity = fuelCapacity;
 }

 public int getMpg() {
  return mpg;
 }

 public void setMpg(int mpg) {
  this.mpg = mpg;
 }
 //public method
 public int calculateRange(){
  return getFuelCapacity() * getMpg();
 }
 
}


package com.spconger.VehicleExample;

import java.util.Scanner;



public class Display {
 
 private Vehicle vehicle;
 Scanner scan;
 
 public Display(){
  vehicle = new Vehicle();
  scan = new Scanner(System.in);
  getInputs();
  getOutput();
 }
 
 
 private void getInputs(){
  System.out.println("Enter the seating capacity of the vehicle");
  vehicle.setPassengers(scan.nextInt());
  System.out.println("Enter the Fuel capacity");
  vehicle.setFuelCapacity(scan.nextInt());
  System.out.println("Enter the mpg");
  vehicle.setMpg(scan.nextInt());
 }
 
 private void getOutput(){
  System.out.println("Your vehicle can hold " 
 + vehicle.getPassengers() + 
 " Passenger and had a range of "
 + vehicle.calculateRange());
 }

}

Monday, January 12, 2015

Arrays and Loops, Random

Here is the code for the Loops and Arrays

package com.spconger.LoopsandArrays;

import java.util.Random;

public class Program {
 /*This class consists of examples
  * of arrays, ifs and loops
  * steve conger 1/7/2015
  */
 final int SIZE = 50;
 final int MAXRANDOM = 500;

 public static void main(String[] args) {
  Program p = new Program();
  p.createArrays();

 }//end main

 private int getRandom() {
  Random r = new Random();
  int number = r.nextInt(MAXRANDOM);
  return number;
 }//end random

 private void createArrays() {
  int[] smaller = new int[SIZE];
  int[] larger = new int[SIZE];
  populateArrays(smaller,larger);
 }//end createArrays

 private void populateArrays(int[] small, int[] large) {
  int smallCounter = 0, largeCounter = 0;

  for (int i = 0; i < SIZE; i++) {

   int num = getRandom();
            
   //this writes the numbers to
   //the large array if they are
   //greater than 250
   //otherwise it writes them to
   //the smaller array
   if (num > 250) {
    large[largeCounter] = num;
    largeCounter++;
   }//end if
   else {
    small[smallCounter] = num;
    smallCounter++;
   }//end else

  }//end for
  displayArrays(small, large);
 }//end populateArrays
 
 private void displayArrays(int[] small, int[] large){
  System.out.println("these are the values 250 or less");
  for(int i = 0; i<SIZE; i++){
   if(small[i] != 0){
    System.out.println(small[i]);
  }//end if
   
   
  }//end for
  System.out.println("these are values over 250");
  int x=0;
   while(x < large.length){
    if(large[x] != 0){
     System.out.println(large[x]);
     x++;
    }//end if
   }//end while
 }

}//end class

SQL Scalar Functions

--functions   in line  scalar
use Automart

Select * from Customer.autoservice

--doing math in SQL statements
Select ServiceName, ServicePrice, ServicePrice * .095 as Tax From Customer.AutoService

Select ServiceName, '$' + cast(ServicePrice as nvarchar(6)) as Price, 
'$' + cast (cast(ServicePrice * .095 as decimal(5,2)) as Nvarchar(10)) as Tax
From Customer.Autoservice

--date time functions
Select * From Employee.VehicleService
Select Distinct Month(ServiceDate) as [Month] From Employee.VehicleService
Select Distinct Datepart(M,ServiceDate) as [Month] from Employee.VehicleService
Select Distinct Day(ServiceDate) as [Day] from Employee.VehicleService
Select Distinct Month(ServiceDate) as [month], 
Day(ServiceDate) as [Day] from Employee.VehicleService
Select Distinct Datepart(dd,ServiceDate) [Day] from Employee.VehicleService
Select Distinct Year(ServiceDate) as [Year] from Employee.VehicleService
Select Distinct Datepart(yy,ServiceDate) [Year] from Employee.VehicleService
Select Distinct DatePart(hour,ServiceTime) as [Hour] From Employee.VehicleService
Select DateAdd(dd,150, GetDate())
Select DateAdd(mm,150, GetDate())
Select * from Employee order by HireDate
Select DateDiff(yy,'2/13/2000','4/25/2011')
Select DateDiff(dd,'2/13/2000','4/25/2011')
Select Distinct DateDiff(dd, (select min(HireDate) from Employee), (Select Max(HireDate) from Employee) ) as [difference] From Employee

Use CommunityAssist
Select * From Employee
--substrings to extract values from a character type
--takes three values, the string to parse
--the starting position and the number of characters
--to return
Select substring(EmployeeSSNumber,1,3) + '-' 
+ substring(EmployeeSSNumber, 4,2) + '-' +
substring(EmployeeSSNumber, 6,4) as [Social Security]
From  Employee

Select [GrantNeedExplanation] From ServiceGrant

--char index returns the position of a particular character
--in this case a blank space
Select substring(GrantNeedExplanation, 0, CHARINDEX(' ',GrantNeedExplanation,0 )) [first Word] From ServiceGrant

Select * From PersonAddress

--coalesce substitutes a value for a null--it has to
--be the same type--so if you wamt to substitute
--a word for a number you must first cast the 
--number to a character type like nvarchar
Select Street, Coalesce(Apartment, 'None') Apartment, City, [State]
From PersonAddress

use Automart

--you can do cases in sql
Select ServiceName, ServicePrice,
Case 
    when ServicePrice between 0 and 100
 Then 'Cheap'
 when ServicePrice between 101 and 300
 then 'Moderate'
 when ServicePrice > 300
 then 'Expensive'
end
as Comment
From Customer.AutoService



Wednesday, January 7, 2015

Statement of Work winter(2015)

Statement of Work

History

Several people have been putting book review on Amazon and other places, but would like to start putting them in the same place. They would like a database to track these reviews.

Scope

The database will track books and reviews. Reviewers must register to write reviews and add comments. All Reviews will rate the book on a scale of 1-5. Unregistered users will be able to seach books and reviews by title, author, and genre, but not able to comment or add reviews.

Constraints: This database will only track book reviews, not other media such as movies and music.

Objectives

Create a database to track book reviews

Create a database that allows people to register and give reviews

Time line and Deliverables

week 1: Determing and agree on the statement of work
Deliverable: Statement or Work

week 2: Gathering information and reviewing documents Deliverables: Questions and notes.

week 3: Defining Requirements and business rules Deliverable: list of Requirements and business rules

Week 4: Design the database. ERD model.
Deliverable: ERD

Week 5. Normalization (Refine the design)
Deliverable: revised ERD

Week 6: Create the physical database
Deliverable Database

Week 7: Add Sample data and test the database(SQL)
Week 8: Look at the Security needs

CommunityAssistDiagram

Monday, January 5, 2015

First Java Code

Here is the code from last night

To Start a new program go to the FILE menu, choose NEW/JAVA PROJECT. Give the project a name and click FINISH.

To add a new class. Right Click on the SRC folder in the project and choose NEW/CLASS. Name the Package and the class. If you want this class to have the main method click the check box to add static void main

package com.sponger.MileageCalculator;

import java.util.Scanner;

public class MileageCalc {
 @SuppressWarnings("unused")
 Scanner scan = new Scanner(System.in);
 public static void main(String[] args) {
 
  // Input: how many miles
  //Input:how many gallons
  //Output: MPG
  // MPG=Miles/Gallons
  
  MileageCalc m = new MileageCalc();
  m.calcuateMPG();

 }
 
 private double getTotalMiles(){
  System.out.println("Enter the total miles traveled");
  double miles = scan.nextDouble();
  return miles;
 }
 
 private double  getGallonsUsed(){
  System.out.println("Enter the gallons used.");
  double gallons = scan.nextDouble();
  return gallons;
 }
 
 private void calcuateMPG(){
  double mpg =getTotalMiles()/getGallonsUsed();
  displayMPG(mpg);
 }
 
 private void displayMPG(double mpg){
  System.out.println("You mpg is " + mpg);
 }

}

Saturday, January 3, 2015

Creating a Service Client

We created web services with the last assignment. Now we will create a client that consumes those services. Our web site will have a page to register, a page to log in, and a page to add a new review and optionally add a new book and author.

Designing the Web Forms

Start a new Empty Web site. Add a default page, which will contain the login form, a registration page and an add review page. The add review page should only be available if the user logs in. Here is the source code for each of the pages. You can cut and paste them into your project if you like, or better, you can recreate them on your own.

Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>BookReview Login</title>
    <link href="BookReviewAtLargeStyles.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Book Reviews At Large</h1>
        <hr />
        <p>To leave reviews you must log in.</p>
        <table class="login">
            <tr>
                <td class="login">User Name</td>
                <td class="login">
                    <asp:TextBox ID="txtUserName" runat="server">
</asp:TextBox></td>
            </tr>
                <tr>
                <td class="login">Password</td>
                <td class="login">
                    <asp:TextBox ID="txtPassword" runat="server" 
TextMode="Password">
                   </asp:TextBox></td>
            </tr>
                <tr>
                <td class="login">
                    <asp:Button ID="btnLogin" runat="server" Text="LogIn" />
                </td>
                <td class="login">
                    <asp:Label ID="lblMessage" runat="server" Text="">
</asp:Label> </td>
            </tr>
        </table>
        <asp:LinkButton ID="lbRegister" runat="server" 
            PostBackUrl="~/Register.aspx">Register</asp:LinkButton>
    
    </div>
    </form>
</body>
</html>

Register.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Registration</title>
    <link href="BookReviewAtLargeStyles.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Book Review at Large Registration</h1>
    <table>
        <tr>
            <td>Last Name</td>
            <td>
                <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>First Name</td>
            <td>
                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>Email</td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>User Name</td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>Password</td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password">
                </asp:TextBox></td>
        </tr>
         <tr>
            <td>Confirm Password</td>
            <td>
                <asp:TextBox ID="txtConfirm" runat="server" TextMode="Password">
                </asp:TextBox></td>
        </tr>
         <tr>
            <td><asp:Button ID="btnRegister" runat="server" Text="Register" /></td>
            <td>
                <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
                </td>
        </tr>
    </table>
        <asp:LinkButton ID="lbLogin" runat="server" PostBackURL="~/Default.aspx">Log in</asp:LinkButton>
    </div>
    </form>
</body>
</html>


NewReview.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewReview.aspx.cs" Inherits="NewReview" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create Review</title>
    <link href="BookReviewAtLargeStyles.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Book Reviews At Large</h1>
        <hr />
        <p>Add Your review</p>
    <table>
        <tr>
            <td>Choose an existing title or enter your own</td>
            <td>
                <asp:DropDownList ID="ddlTitles" runat="server"></asp:DropDownList></td>
            <td>
                <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox></td>
        </tr>
          <tr>
            <td>Choose an existing Author or enter your own</td>
            <td>
                <asp:DropDownList ID="ddlAuthor" runat="server"></asp:DropDownList></td>
            <td>
                <asp:TextBox ID="txtAuthor" runat="server"></asp:TextBox></td>
        </tr>
          <tr>
            <td>Choose a category</td>
            <td>
                <asp:DropDownList ID="ddlCategory" runat="server"></asp:DropDownList></td>
            <td>
                 </td>
        </tr>
          <tr>
            <td>Enter a title for your review</td>
            <td>
                <asp:TextBox ID="txtReviewTitle" runat="server"></asp:TextBox>  </td>
            <td>
                </td>
        </tr>
          <tr>
            <td>Rate the book 1 to 5</td>
            <td>
                <asp:DropDownList ID="ddlRating" runat="server">
                   
                </asp:DropDownList></td>
            <td>
                </td>

        </tr>
        
          <tr>
            <td>Enter your review</td>
            <td colspan="2">
                <asp:TextBox ID="txtReview" runat="server" 
                    TextMode="MultiLine" width="100%" Height="300"></asp:TextBox>  

            </td>
     
        </tr>
        
          <tr>
            <td>
                <asp:Button ID="btnSave" runat="server" Text="Save" /></td>
            <td>
                <asp:Label ID="lbResult" runat="server" Text=""></asp:Label> </td>
            <td>
                </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>


Here is the rather minimal style sheet BookReviewsAtLarge.css


body {
}
.login
{
    background-color:Navy;
    color:white;
    border:solid 2px black;
}
h1 {
    color:navy;
}

Here is what the pages look like in Design view

 

Adding The Code


Part one: Registering the services

For this part we will need three instances of Visual Studio Running: The Registration, log in service, and the Client app. This would not be necessary if we had registered the service with IIS proper rather than the built in IISExpress, but this version will work even if you don't have IIS installed and configured on your own computer. I will create another blog soon about how to register the service with IIS.

With the Client open, right click on the Visual studio Icon in the tray (at the bottom of the screen.) Open the two services. It is also important that you run them and leave them running.

Now we will register the services with the client. First we will do the Registration service. In the Test Client dialog for the running Registration Services, right click on the address and select Copy Address.

Now go the the Client Web Site. Choose Add and then Service Reference

In the dialog paste in the address and click GO. I have expanded the services to show the methods. I have named it "RegistrationLoginService."

Click OK to Add the Service. Go through the same steps to add the Review service. Name it "ReviewService."

The Code

Let's just do the pages in order. We will start with the login page. Double click the login button in design mode to get the click event for the button. Here is the code

Notice it is fairly simple. All the work is done by the service. You merely need to register the service and call the appropriate method. If the result is good we store the user's id in a Session variable and redirect them to the review page. If not we give them a message that the log in is invalid.

You should test the log in now. To make sure it works. It is always a good idea to test each section before moving on.

Now let's work on the Registration page. Double click the button in design mode to get the click event. In this method we will instantiate the service. Declare an instance of the ReviewLite class that we created in the service as a Data Contract, assign the contents of the textboxes to the ReviewLite properties and pass the class to the Register method in the service. It would be a very good idea to validate all the text boxes just as we did in assignment 3. Here is the code:

Again, test this before moving on. Register someone and then see if you can log in as them.

Now it is time to tackle the most complex part. Adding the review itself. First we will fill in the drop down boxes. To do this we will make a separate method for each drop down and then call them from the Page Load event. We want to register the service at class level so we can access it in all our methods. Here is the FillTitleList() method. All the others follow exactly the same pattern.

Here is the code for all the lists.

Here is the page load event

Notice a couple of points. One is the if statement that makes sure that the Session variable is not null, that it exists and has a value. This is to keep anyone who has not logged in from accessing this page. If the session object does not exist they are thrown back to the log in page. The second if is to make sure that the lists only repopulate on the initial load and not with every postback. This allows your selection to be preserved.

Now go back to design view and double click the Save button to get the click event. The code for this is a bit complex because we must determine if there are values in the text boxes. If there is then we need to add them rather than the values in the drop down lists.
1. Is the title an existing one (from the drop down list) or a new one (from the textbox)
2. If it is a new one
    A:add the book
    B:Is it a new author or an existing one
        a: If is new one add the author
    C: Add the author and category to the book
    D: Save the Book
3. If it is not a new title
    A:Get the bookKey from the drop down list
4.Add the review Assign the values to the review
5. Save the Review

I have commented the code and pasted it in so you can examine it.

protected void btnSave_Click(object sender, EventArgs e)
    {
            //get the session value (the users id)
            int key = (int)Session["Id"];

           //create a new instance of the Review class
        //we get to it through the ReviewService object
            ReviewService.Review rev = new ReviewService.Review();
        //if the text box is not empty use the text in the text box
            if (!txtTitle.Text.Equals(""))
            {
                //create new book and author objects
                ReviewService.Book b = new ReviewService.Book();
                ReviewService.Author a = new ReviewService.Author();
                string c = null;
                //assign some values to the book
                b.BookTitle = txtTitle.Text;
                b.BookEntryDate = DateTime.Now;

                //determine if the author text box has text
                if (!txtAuthor.Text.Equals(""))
                {

                    //if it does add the value to the author
                    //and call the add author method in the service
                    a.AuthorName = txtAuthor.Text;
                    rsc.AddAuthor(a);
                   
                }
                else
                {
                    //otherwise get the author's name
                    //from the drop down list
                    a.AuthorName = ddlAuthor.SelectedItem.Text.ToString();
 
                }
 
                //add the category
                c = ddlCategory.SelectedItem.Text;

                //call the add Book method of the service
                rsc.AddBook(b, a, c);
                rev.BookKey = b.BookKey;

            }

            else
            {
                //Otherwise get the bookkey from the drop down list
                rev.BookKey = int.Parse(ddlTitles.SelectedValue.ToString());

            }
        //add all the values to the review object
            rev.ReviewDate = DateTime.Now;
            rev.ReviewerKey = key;
            rev.ReviewTitle = txtReviewTitle.Text;
            rev.ReviewRating = int.Parse(ddlRating.SelectedItem.Text);
            rev.ReviewText = txtReview.Text;
            //pass the review to the AddReview method
            bool result = rsc.AddReview(rev);
        //check the result to see if it wrote.
            if (result)
            {
                lbResult.Text = "Review Added";
            }
            else
            {
                lbResult.Text = "Review failed to save";
            }
        
    }