Monday, July 2, 2012

Overview of Indexes

Overview

Indexes are used to speed up searches. Properly used indexes can greatly increase search speeds, but they can also slow updates and deletes. Whenever the values in the tables change the index must be recreated. This can take resources and time.

Kinds of Indexes

Clustered indexes

A clustered index physically organizes the data by the indexed fields. If it is a character type the records with be ordered A-Z, if numeric 123... etc. Consequently, there can only be one clustered index per table. By Default, the primary key is given a clustered index, but you can override this. Below is an example of creating a table with the social security number used as a clustered index and the primary key as a non clustered index:


CREATE TABLE Employee
(
  EmployeeID INT IDENTITYy(1,1),
  SocialSecurityNumber NCHAR(10) NOT NULL UNIQUE,
  EmployeeName NVARCHARr(255),
  HireDate Date
)

ALTER TABLE Employee
ADD CONSTRAINT pk_Employee 
  PRIMARY KEY NONCLUSTERED(EmployeeID)

CREATE CLUSTERED INDEX ix_SocialSecurity 
     ON Employee (SocialSecurityNumber)


Most indexes are non clustered. Non clustered indexes create a separate structure called a Balanced Tree or B-Tree. Below is an image of a B-Tree Cluster:

Below is the code for creating a non clustered index. "NONCLUSTERED" is optional. The second option is for an index with an included column.


CREATE NONCLUSTERED INDEX ix_EmployeeName ON Employee(EmployeeName)
CREATE NONCLUSTERED INDEX ix_NameDate ON Employee (EmployeeName) 
INCLUDE (HireDate)


Filtered Index

You can create an index which filters for certain conditions:


CREATE NONCLUSTERED INDEX ix_HireDate ON Employee (HireDate) 
WHERE Hiredate IS NOT NULL

Disabling, Rebuilding, and Dropping Indexes.

When loading bulk data or testing sometimes it is necessary to disable an index temporarily. When you are done you can rebuild it. You can also drop an index completely


ALTER INDEX ix_EmployeeName ON Employee DISABLE
ALTER INDEX ix_EmployeeName ON Employee REBUILD

DROP INDEX ix_EmployeeName ON Employee


Forcing an Index

Even if you make an index, the database engine may not use it. Generally it is faster to just sort through the records until a certain threshold (several thousand) records are present. For testing purposes you can force SQL Server to use an index with the following syntax


SELECT * FROM Employee 
WHERE EmployeeName='John Smith' 
ITH (NOLOCK, INDEX(ix_EmployeeName))

Computer Management Example (for assignment 2)

here are the classes for the Computer Management example

Here is the Computer.java class

package com.spconger.www;

public class Computer {
 /**
  * This class stores information 
  * about a computer
  * steve conger 7/2/2012
  */
 
 //private fields
 private int computerID;
 private int gigsOfRam;
 private  int hardDiskSize;
 private String brand;
 
 //constructors
 public Computer(int ID, int ram, int hd, String name){
  setComputerID(ID);
  setGigsOfRam(ram);
  setHardDiskSize(hd);
  setBrandName(name);
  
 }
 
 public Computer(int ID){
  setComputerID(ID);
  setGigsOfRam(0);
  setHardDiskSize(0);
  setBrandName("");
  
 }
 
 public Computer(){
  setComputerID(0);
  setGigsOfRam(0);
  setHardDiskSize(0);
  setBrandName("");
 }
 
 // gets and sets
 public void setComputerID(int ID){
  computerID=ID;
 }
 
 public int getComputerID(){
  return computerID;
 }
 
 public void setGigsOfRam(int ram){
  gigsOfRam=ram;
 }
 
 public int getGigsOfRam(){
  return gigsOfRam;
 }
 
 public void setHardDiskSize(int hdisk){
  hardDiskSize=hdisk;
 }
 
 public int getHardDiskSize(){
  return hardDiskSize;
 }
 
 public void setBrandName(String name){
  brand=name;
 }
 
 public String getBrandName(){
  return brand;
 }
 
 // public methods
 
 public String getComputerInfo(){
  return Integer.toString(computerID) + ", " 
   +  brand + ", "
   + Integer.toString(gigsOfRam) + ", " 
   + Integer.toString(hardDiskSize);
 }
 
}



Here is the ComputerManager.java class

package com.spconger.www;

import java.util.ArrayList;

public class ComputerManager {
 /**
  * This class manages computers
  * it uses an ArrayList to collect computer
  * information. The class can return information
  * about a particular computer or return
  * the average size of hard disks
  * the class could do a lot more
  * but this is enough for the example
  * Steve Conger 7/1/2012
  */
 
 //private fields
 private ArrayList<Computer> computers;
 
 //constructor
 public ComputerManager(){
  //initialize the ArrayList
  computers=new ArrayList<Computer>();
 }
 
 //public methods
 public void AddComputer(Computer c){
  //add a computer the the ArrayList
  computers.add(c);
 }
 
 
 public String GetComputerById(int ID){
  //get a computer by its ID
  
  String computerInfo="computer not found";
  
  for(Computer c: computers){
   if(c.getComputerID()==ID){
    
    computerInfo=c.getComputerInfo();
    break;
   }
   
  }

  return computerInfo;
 }
 
 public double getAverageHardDiskSize(){
  //get the average HardDisk size
  //initialize variables
  double average=0;
  int sum=0;
  
  //for each computer in the ArrayList computers
  for(Computer c: computers){
   sum += c.getHardDiskSize();
  }
  //cast sum to double and divide
  //size is the length of the array
  average=(double)sum/computers.size();
  
  return average;
  
 }

}


Here is the Display.java

package com.spconger.www;

import java.text.DecimalFormat;
import java.util.Scanner;

public class Display {
 /**
  * This class handles the input and output 
  * for the Computer and ComputerManager classes
  * Steve Conger 7/2/2012
  */
 //declare class level variables
 ComputerManager cm;
 Scanner scan;
 
 //constructor
 public Display(){
  //initialize classes
  scan = new Scanner(System.in);
  cm= new ComputerManager();
  //call methods
  getInputs();
  showOutputs();
 }

 private void getInputs(){
  int exit=1;
  
  //loop to enter as many computers as desired
  while(exit !=-1){

  //get the values
  System.out.println("Enter Computer ID");
  int id=scan.nextInt();
  
  System.out.println("Hard Disk Size");
  int hd=scan.nextInt();
  
  System.out.println("Enter Ram size");
  int ram=scan.nextInt();
  
  System.out.println("Enter Computer Brand");
  String brandName=scan.next();
  
  //create the computer object and pass it
  //the values through the constructor
  Computer c = new Computer(id, ram, hd, brandName);
  //call the method to add the computer
  //to the ArrayList
  cm.AddComputer(c);
  
  //prompt for exit
  System.out.println("-1 to exit, anything other int to continue");
  exit=scan.nextInt();
  
  }//end while
  
 }//end inputs
 
 private void showOutputs(){
  //get the outputs
  System.out.println("***************************");
  System.out.println("Enter a computer id to get Computer");
  int id = scan.nextInt();
  
  String info=cm.GetComputerById(id);
  
  System.out.println(info);
  
  System.out.println("the average hard disk space is");
  double space = cm.getAverageHardDiskSize();
  
  //Decimal format lets you format the output
  //it doesn't change the actual number
  DecimalFormat df = new DecimalFormat("#,###.##");
  
  System.out.println(df.format(space));
 
 }
}


Here is Program.java

package com.spconger.www;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
   Display d = new Display();
 }

}

Sunday, July 1, 2012

VenueTracker Database

Here is the SQL for the venue database

Use master
go
if exists
 (select name from sys.databases 
  where name = 'VenueTracker')
Begin
Drop Database VenueTracker
End
Go
Create Database VenueTracker

Use VenueTracker

Create table Venue
(
  VenueID int identity(1,1) primary key,
  VenueName nvarchar(255) not null,
  VenueAddress1 nvarchar(255),
  VenueAddress2 nvarchar(255) not null,
  VenueCity nvarchar(255) not null,
  VenueState nchar(2) not null,
  VenuePhone nchar(10) not null,
  VenueCapacity int,
  VenueAgeRestriction bit,
  VenueDescription xml,
  VenueURL nvarchar(255)
  
)

Go

Create Table Artist
(
   ArtistID int identity(1,1) primary key,
   ArtistName nvarchar(255) not null unique,
   ArtistBio xml,
   ArtistURL nvarchar(255)
)

Go
Create Table Show
(
 ShowID int identity(1,1) primary key,
 VenueID int foreign key references Venue(VenueID),
 ArtistID int foreign key references Artist(ArtistID),
 TourName nvarchar(255),
 ShowDate Date not null,
 ShowTime Time not null,
 ShowPosition nvarchar(255),
 ShowDescription nvarchar(max),
 Constraint ck_position check (ShowPosition in('Headline', 'Opening','festival'))
)

Go

Create table TicketOutlet
(
  TicketOutletID int identity(1,1),
  ShowID int foreign Key references Show(ShowID),
  constraint PK_Ticket primary Key (ticketOutletID, ShowID),
  TicketOutletURL nvarchar(255) not null,
  TicketPrice decimal(5,2) not null,
  TicketsRemaining int
  
)

Go

Create Table Genre
(
 GenreID int identity(1,1) primary key,
 GenreName nvarchar(255) unique
)

Go

Create Table ArtistGenre
(
 ArtistID int,
 GenreID int,
 Constraint pk_ArtistGenre Primary Key (artistID, GenreID)
)

Go

Create Table Customer
(
  CustomerID int identity(1,1) primary key,
  CustomerLastName nvarchar(255) not null,
  CustomerFirstName nvarchar(255),
  CustomerEmail nvarchar(255) not null unique,
  CustomerPassword nvarchar(255) not null unique
)

go

Create Table CustomerArtist
(
  CustomerID int foreign key references Customer(CustomerID),
  ArtistID int foreign Key references Artist(ArtistID),
  Constraint Pk_CustomerArtist primary key (CustomerID, ArtistID),
  ArtistAlert bit default 1
  
)

Thursday, June 28, 2012

Venue Artist Database

Here is our Entity Diagram.


here are our different users and their basic uses for the database

Venues: 
show what acts are coming
Login to add, edit events and edit their own info
A calendar of events
Display some information about venue capacity, doors open, age, cameras
Enter event information  Edit info, edit their own venue information

Artist
Show their dates and tour information
Edit their own information (Bio) add photos

Customer
View tour dates and places
View ticket places  and venues (day of sale or advance Price)
Customer register to receive info and band dates and recommendation
Login in to see their own info
Enter registration information and edit their own info
Add artists to follow and receive alerts from
Add own alert list

Admin—create, alter and drop objects,
Back and restore 
Security access

Business Admin –in charge of content
Keeping information current and accurate 
Manage security
Ability to view and update, insert any information in the database, k





Wednesday, June 27, 2012

Cubic Yard of Dirt Example

Here is the YardCalc.Java

package com.spconger.www;

public class YardCalc {
 /*
  * This class will calculate the cubic yards
  * of soil needed for a yard
  * Steve Conger
  * 6/27/2012
  */
 
 //fields
 
 private double length;
 private double width;
 private final double HEIGHT =.167;
 
 
 //constructor
 
 public YardCalc(){
  length=1;
  width=1;
 }
 
 public YardCalc(double l, double w)
 {
  length=l;
  width=w;
 }
 //Assessors/mutators (gets sets)
 
 public void setLength(double len){
  if (len >0){
  length=len;
  }
  else{
   length=1;
  }
  }
 

 public double getLength(){
  return length;
 }


 public double getWidth() {
  return width;
 }


 public void setWidth(double width) {
  this.width = width;
 }


 
 
 //class methods
 
 public double calcSquareFeet(){
  
  return getLength() * getWidth();
 }
 
 public double calcTotalYards(){
  return calcSquareFeet() /3;
 }
 
 public double calcCubicYards(){
  return calcTotalYards() * HEIGHT;
 }

}


Here is the Display.java

package com.spconger.www;

import java.util.Scanner;



public class Display {
 
 /**
  * This class gets the input and displays
  * the output
  * Steve Conger
  * 6/27/2012
  */
 private YardCalc yc;
 
 public Display()
 {
  getInput();
  showOutput();
 }
 //spconger@gmail.com
 
 private void getInput(){
  
  Scanner scan=new Scanner(System.in);
  
  System.out.println("Enter your yard's length");
  double length = scan.nextDouble();
  System.out.println("Enter your yard's width");
  double width= scan.nextDouble();
  yc=new YardCalc(length,width);
 }
 
 private void showOutput(){
  
  double squareFeet=yc.calcSquareFeet();
  double squareYards=yc.calcTotalYards();
  double cubicYards=yc.calcCubicYards();
  
  String strSquareYards = Double.toString(squareYards);
  String strCubicYards = Double.toString(cubicYards);
  
  System.out.println("the total square feet is" +Double.toString(yc.calcSquareFeet()));
  System.out.println("Your square yards are" + strSquareYards);
  System.out.println("You need " + strCubicYards + " yards of dirt");
  
  
 }

}


Here is the Program.java

package com.spconger.www;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Display d = new Display();

 }

}

Monday, June 25, 2012

First Java Class

//this is equivalent to a name space
//it is used to group related classes
package com.spconger.www;

//import java objects from the library
import java.util.ArrayList;
import java.util.Scanner;


public class FirstClass {

 /**
  * @param args
  */
 //all programs start with main
 public static void main(String[] args) {
  FirstClass fc = new FirstClass();
  //fc.method1();
  //fc.ifExample();
  fc.simpleForLoop();
  fc.simpleWhileLoop();
 }
 
 private void method1(){
  //prints a line out to the console
  System.out.println("This is a java program");
 }
 
 private void ifExample(){
  //the scanner is an object that reads input
  //from the console
  Scanner scan = new Scanner(System.in);
  
  
  System.out.println("Enter a number");
  int number = scan.nextInt();
 //if example
  if(number > 10){
   System.out.println("Take over the world");
   
  }
  else if(number > 5){
   System.out.println("oh well");
  }
  else {
   System.out.println("Stay in and have a beer");
  }
  
  
 }
 

 private void simpleForLoop(){
  
   for (int i=0;i<=10;i++){
    System.out.println(i);
   }
 }
 
 private void simpleWhileLoop(){
  
  int num = 0;
  
  while (num < 10){
   System.out.println(num);
   num ++;
  }
 }
 
 private void simpleDoLoop(){
  int num=10;
  
  do{
   System.out.println(num);
   num ++;
  }while(num<10);
 }
 
 private void simpleArray(){
  int myArray[] = new int[4] ;
  ArrayList mylist = new ArrayList();
  
  //java uses a wrapper class to provide conversions
  //between primative types like int. Integer has methods
  // to parse an integer from a string
  //or to convert an integer into a string 
  String myNumberString = "1234";
  int myInteger=Integer.parseInt(myNumberString);
  String intString=Integer.toString(myInteger);
 }

}

Tuesday, June 5, 2012

Web Services

For this assignment we use a master page, and on the first page did an Ajax panel. Ajax allows for a section to be updated rather than the whole page as usual. .Net makes Ajax easy. You add a script manager to the page, add an update panel, and then put your controls within them.

The other main point of the assignment was the consuming of web services. First locate a Web service then go to WebSite/Add Web Service. Paste the web service URL into the text box, give the service a name and add the service. Now you can treat it as a class in your program.

Master Page code

<%@ Master Language="C#" AutoEventWireup="true"  
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <h1>Service Examples</h1>
    <p>
        <asp:LinkButton ID="LinkButton1" runat="server" 
onclick="LinkButton1_Click">Mortgage</asp:LinkButton> </p>
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


here is the code behind the Master page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default2.aspx");
    }
}


Here is the source for default one which has the ajax and the weather web service

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" 
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>First Page</h2>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
   <p>
    <asp:Label ID="Label1" runat="server" Text="Enter City Name"></asp:Label>
    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox></p>
<p>
    <asp:Label ID="Label2" runat="server" Text="Enter Country Name"></asp:Label>
    <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox></p>
    <asp:Button ID="Button1" runat="server" Text="Get Weather" 
        onclick="Button1_Click" />
    <asp:Label ID="lblWeather" runat="server" Text="Label"></asp:Label>
   
   </ContentTemplate>
    </asp:UpdatePanel>



</asp:Content>

Here is the code behind Default.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using net.webservicex.www;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GlobalWeather gw = new GlobalWeather();
        string weather = gw.GetWeather(txtCity.Text, txtCountry.Text);
        lblWeather.Text = weather;
    }
}

here is the source for default2.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" 
AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <p> <asp:Label ID="Label1" runat="server" Text="Years"></asp:Label>
    <asp:TextBox ID="txtYears" runat="server"></asp:TextBox></p>
      <p><asp:Label ID="Label2" runat="server" Text="Interest"></asp:Label>
    <asp:TextBox ID="txtInterest" runat="server"></asp:TextBox></p>
      <p><asp:Label ID="Label3" runat="server" Text="LoanAmount"></asp:Label>
    <asp:TextBox ID="txtLoanAmount" runat="server"></asp:TextBox></p>
      <p><asp:Label ID="Label4" runat="server" Text="Annual Tax"></asp:Label>
    <asp:TextBox ID="txtTax" runat="server"></asp:TextBox></p>
      <p><asp:Label ID="Label5" runat="server" Text="Insurance"></asp:Label>
    <asp:TextBox ID="txtInsurance" runat="server"></asp:TextBox></p>
    <asp:Button ID="Button1" runat="server" Text="Get Mortage" 
    onclick="Button1_Click" />
    <hr />
    <p>
        <asp:Label ID="lblPandI" runat="server" Text="Label"></asp:Label> </p>
      <p>  <asp:Label ID="lblTax" runat="server" Text="Label"></asp:Label> </p>
       <p> <asp:Label ID="lblInsurance" runat="server" Text="Label"></asp:Label> </p>
       <p> <asp:Label ID="lblTotal" runat="server" Text="Label"></asp:Label> </p>

</asp:Content>


Here is the code behind Default1.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using net.mortgageinfo.www;
using System.Data;
using System.Xml;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Mortgage m = new Mortgage();
        int years = int.Parse(txtYears.Text);
        double interest=double.Parse(txtInterest.Text);
        double loan=double.Parse(txtLoanAmount.Text);
        double tax = double.Parse(txtTax.Text);
        double insurance=double.Parse(txtInsurance.Text);

        MortgageResults mr = m.GetMortgagePayment(years, interest, loan, tax, insurance);
        lblPandI.Text = mr.MonthlyPrincipalAndInterest.ToString("c");
        lblInsurance.Text = mr.MonthlyInsurance.ToString("c");
        lblTax.Text = mr.MonthlyTax.ToString("c");
        lblTotal.Text = mr.TotalPayment.ToString("c");
    }
}

Here is the style sheet, such as it is

body {
}

h1
{
    background-color:Navy;
    color:White;
    height:40px;
    text-align:center;
}