Monday, July 30, 2012

Simple check Box Example

Here is a picture of the form running

Here is the code for the Form1.java and panel


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

import javax.swing.*;
public class Form1 {
 JFrame frame= new JFrame("Checkbox test");
 JPanel panel = new JPanel(new FlowLayout());
 JCheckBox chk1 = new JCheckBox("0ne");
 JCheckBox chk2=new JCheckBox("Two");
 JButton button = new JButton("test");
 
 JLabel label = new JLabel();
 
 public Form1(){
 
 panel.add(chk1);
 panel.add(chk2);
 panel.add(button);
 button.addActionListener(new TestAction());
 panel.add(label);
 frame.add(panel);
 frame.setBounds(100,100,300,300);
 frame.setVisible(true);
 
 }
 
 private class TestAction implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent arg0) {
   String s = "";
  
   if(chk1.isSelected()){
    s+=chk1.getText() + " ";
   }
   
   if (chk2.isSelected()){
    s+=chk2.getText() + " ";
   
  }
   label.setText(s);
  
 }
 }
}
 




Here is Program.java



public class Program {

 public static void main(String[] args){
  Form1 f = new Form1();
  
 }
}

Thursday, July 26, 2012

XSLT and Reading XML from SQL Server

First we made sure there was a description for every Venue

Use VenueTracker



Select * From Venue

Update Venue
Set VenueDescription=
'<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
    <datelastupdated>7/26/2012</datelastupdated>
    <contactname>Robert Zimmerman</contactname>
  </header>
  <body>
    <description>
      A stadium venue for sports and concerts at Seattle Center.

    </description>
  </body>
</venuedescription>'
Where VenueID=1

Update Venue
Set VenueDescription=
'<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
    <datelastupdated>7/26/2012</datelastupdated>
    <contactname>Sara Smith</contactname>
  </header>
  <body>
    <description>
      A large Tavern in Ballard. Ideal for intimate concerts with the newest bands.

    </description>
  </body>
</venuedescription>'
Where VenueID=3

Update Venue
Set VenueDescription=
'<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
    <datelastupdated>7/26/2012</datelastupdated>
    <contactname>Joe Manning</contactname>
  </header>
  <body>
    <description>
     A classy dive ideal for music. Located on Capital Hill.

    </description>
  </body>
</venuedescription>'
Where VenueID=4


Update Venue
Set VenueDescription=
'<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
    <datelastupdated>7/26/2012</datelastupdated>
    <contactname>Sue Lewis</contactname>
  </header>
  <body>
    <description>
      Like the tractor but bigger. 

    </description>
  </body>
</venuedescription>'
Where VenueID=6

Delete From Venue Where VenueID = 7

Then we created an XSLT document to style and transform our venue description xml column


Here is the Venue.xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" 
xmlns="http://www.w3.org/1999/xhtml" 
xmlns:d ="http://www.venutracker.com/description"
>
    <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <h2>Venue Description</h2>
    <p>
      <strong>Date Last Updated:</strong>
      <xsl:value-of 
select ="d:venuedescription/d:header/d:datelastupdated"/>
    </p>
      <p>
        <strong>Contact Person: </strong>
        <xsl:value-of 
select="d:venuedescription/d:header/d:contactname"/>
      </p>
      <hr/>
      <p>
        <xsl:value-of 
select ="d:venuedescription/d:body/d:description"/>
      </p>
      
 
    
  </xsl:template>
   
</xsl:stylesheet>


Next we Created a web page. we added two controls, a GridView and an XML control. For the GridView we used the wizard to connect it to the database. We also styled it and added a select button. Here is the code for Default.aspx. Just copying the source will reproduce all the wizard did.

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

<!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>
    <link href="VenueDescriptionTest.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Venues</h1>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
            CellPadding="4" DataKeyNames="VenueID" DataSourceID="SqlDataSource1" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="VenueID" HeaderText="VenueID" InsertVisible="False" 
                    ReadOnly="True" SortExpression="VenueID" />
                <asp:BoundField DataField="VenueName" HeaderText="VenueName" 
                    SortExpression="VenueName" />
                <asp:BoundField DataField="VenueAddress2" HeaderText="VenueAddress2" 
                    SortExpression="VenueAddress2" />
                <asp:BoundField DataField="VenueCity" HeaderText="VenueCity" 
                    SortExpression="VenueCity" />
                <asp:BoundField DataField="VenueState" HeaderText="VenueState" 
                    SortExpression="VenueState" />
                <asp:BoundField DataField="VenuePhone" HeaderText="VenuePhone" 
                    SortExpression="VenuePhone" />
                <asp:BoundField DataField="VenueCapacity" HeaderText="VenueCapacity" 
                    SortExpression="VenueCapacity" />
                <asp:CheckBoxField DataField="VenueAgeRestriction" 
                    HeaderText="VenueAgeRestriction" SortExpression="VenueAgeRestriction" />
                <asp:BoundField DataField="VenueURL" HeaderText="VenueURL" 
                    SortExpression="VenueURL" />
            </Columns>
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <RowStyle BackColor="White" ForeColor="#003399" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <SortedAscendingCellStyle BackColor="#EDF6F6" />
            <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
            <SortedDescendingCellStyle BackColor="#D6DFDF" />
            <SortedDescendingHeaderStyle BackColor="#002876" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:VenueTrackerConnectionString %>" 
            SelectCommand="SELECT [VenueID], [VenueName], [VenueAddress2], [VenueCity], [VenueState], [VenuePhone], [VenueCapacity], [VenueAgeRestriction], [VenueURL] FROM [Venue]">
        </asp:SqlDataSource>
        <asp:Xml ID="Xml1" runat="server"></asp:Xml>
    </div>
    </form>
</body>
</html>


You will also need the web.config file. It contains the connection string


<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <connectionStrings>
        <add name="VenueTrackerConnectionString" connectionString="Data Source=localhost;Initial Catalog=VenueTracker;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>

</configuration>

Finally, here is the C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; //add these four libraries
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;

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

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["VenueTrackerConnectionString"].ToString());

        XmlDocument xDoc = new XmlDocument();
        string sql = "Select venueDescription from Venue where VenueID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connect);
        cmd.Parameters.AddWithValue("@ID", int.Parse(GridView1.SelectedRow.Cells[1].Text));

        XmlReader xreader = null;
        connect.Open();
        xreader = cmd.ExecuteXmlReader();
        xDoc.Load(xreader);
        xreader.Close();
        connect.Close();

        Xml1.Document = xDoc;
        Xml1.TransformSource = MapPath("Venue.xslt");
          
    }
}

Wednesday, July 25, 2012

Swing Example

Here is a picture of the form operating


Here is the Program.java class

package com.spconger.www;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  MainJFrame m = new MainJFrame();
  m.setTitle("tip Calculator");
  m.setBounds(200,200,350, 350);
  
  m.setVisible(true);
 }

}

Here is the MainJFrame.java class

package com.spconger.www;

import javax.swing.*;

public class MainJFrame extends JFrame{

 /**
  * this method creates the JFrame
  * and adds the panel
  */
 private static final long serialVersionUID = 1L;
 
 public MainJFrame(){
  //JFrame frame = new JFrame();
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JPanel mainPanel= new MealTipPanel();
  this.add(mainPanel);
  
  
 }
 
 

}


Here is the MealTipPanel.Java class

package com.spconger.www;

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.*;

public class MealTipPanel extends JPanel{

 /**
  * 
  */
 private static final long serialVersionUID = 1L;

 //declare all my objects
 JPanel panel;
 JPanel buttonPanel;
 JLabel lblAmount;
 JTextField txtAmount;
 JLabel lblChooseTipPercent;
 JRadioButton rbFifteenPercent;
 JRadioButton rbTenPercent;
 JRadioButton rbTwentyPercent;
 JLabel lblTaxPercent;
 JTextField txtTaxPercent;
 JLabel lblTipAmount;
 JLabel lblTaxAmount;
 JLabel lblTotalAmount;
 
 JButton btnCalculate;
 JButton btnExit;
 
 private Tip tip;
 
 
 public MealTipPanel(){
  createPanel();
 }
 
 private void createPanel(){
  panel = new JPanel();
  panel.setLayout(new GridLayout(10,2,5,5));
  
  lblAmount = new JLabel("Enter the Pre Tax Amount");
  txtAmount = new JTextField(10);
  
  lblChooseTipPercent = new JLabel("Choose the Tip Percent");
  rbTenPercent = new JRadioButton("Ten Percent");
  rbFifteenPercent = new JRadioButton("Fifteen Percent");
  rbTwentyPercent = new JRadioButton("Twenty Percent");
  
  ButtonGroup group = new ButtonGroup();
  group.add(rbTenPercent);
  group.add(rbFifteenPercent);
  group.add(rbTwentyPercent);
  
  lblTaxPercent=new JLabel("Enter Tax Percent");
  txtTaxPercent= new JTextField(10);
  
  lblTipAmount = new JLabel();
  lblTaxAmount= new JLabel();
  lblTotalAmount = new JLabel();
  
  panel.add(lblAmount);
  panel.add(txtAmount);
  panel.add(lblChooseTipPercent);
  panel.add(rbTenPercent);
  panel.add(rbFifteenPercent);
  panel.add(rbTwentyPercent);
  panel.add(lblTaxPercent);
  panel.add(txtTaxPercent);
  panel.add(lblTipAmount);
  panel.add(lblTaxAmount);
  panel.add(lblTotalAmount);
  
  buttonPanel = new JPanel();
  buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
  
  btnCalculate = new JButton("Calculate");
  btnCalculate.addActionListener(new CalculateListener());
  buttonPanel.add(btnCalculate);
  
  btnExit = new JButton("Exit");
  btnExit.addActionListener(new ExitListener());
  buttonPanel.add(btnExit);
  
  this.setLayout(new BorderLayout());
  this.add(panel, BorderLayout.CENTER);
  this.add(buttonPanel, BorderLayout.SOUTH);
  
 }//end create panel
 
 private class ExitListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   // TODO Auto-generated method stub
   System.exit(0);
  }
  
 }//end of ExitListenerClass
 
 private class CalculateListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent e) {
   tip = new Tip();
   //set the field values
   tip.setMealAmount(Double.parseDouble(txtAmount.getText()));
   
   double percent=0;
   if (rbTenPercent.isSelected()){
    percent=.1;
   }
   else if (rbFifteenPercent.isSelected()){
    percent=.15;
   }
   else if (rbTwentyPercent.isSelected())
   {
    percent=.2;
   }
    
   tip.setTipPercent(percent);
   tip.setTaxPercent(Double.parseDouble(txtTaxPercent.getText()));
   
   lblTipAmount.setText("The tip amount is " 
             + Double.toString(tip.calculateTip()));
   
   lblTaxAmount.setText("The tax amount is " +
            Double.toString(tip.calculateTax()));
   
   lblTotalAmount.setText("The Total is " +
     Double.toString(tip.calculateTotal()));
   
  }
  
 }
 
 
}//end class



Here is the Tip.java class

package com.spconger.www;

public class Tip {
 private double mealAmount;
 private double tipPercent;
 private double taxPercent;
 
 public double getMealAmount() {
  return mealAmount;
 }
 public void setMealAmount(double mealAmount) {
  this.mealAmount = mealAmount;
 }
 public double getTipPercent() {
  return tipPercent;
 }
 public void setTipPercent(double tipPercent) {
  if (tipPercent >=1){
   tipPercent=tipPercent/100;
  }
  this.tipPercent = tipPercent;
 }
 public double getTaxPercent() {
 
  return taxPercent;
 }
 public void setTaxPercent(double taxPercent) {
  if (taxPercent >= 1)
  {
   taxPercent=taxPercent /100;
  }
  this.taxPercent = taxPercent;
 }
 
 public double calculateTip(){
  return getMealAmount() * getTipPercent();
 }
 
 public double calculateTax(){
  return getMealAmount() * getTaxPercent();
 }
 
 public double calculateTotal(){
  return getMealAmount() + calculateTip() + calculateTax();
 }
 

}

Tuesday, July 24, 2012

XML in SQL Server

Use VenueTracker

Select * from Customer
for xml raw

Select * from Customer
for xml raw, elements, root('customers')

Select * from Customer
for xml raw('customer'), elements, root('customers')

Select Distinct CustomerLastName, customerEmail, ArtistName
From Customer cust
Inner join CustomerArtist custartist
on cust.CustomerID=custArtist.ArtistID
inner Join Artist art
on art.ArtistID=custartist.ArtistID
order by CustomerLastName
for xml auto, elements, root ('root')

Select * From customerArtist

Use Automart

Select * From Customer.AutoService

use VenueTracker
Create xml schema collection schema_VenueDescription
As
'<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
           targetNamespace="http://www.venutracker.com/description" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="venuedescription">
    <xs:complexType>
      <xs:sequence>
       <xs:element name="header">
         <xs:complexType>
            <xs:sequence>
              <xs:element name="datelastupdated" type="xs:string" />
              <xs:element name="contactname" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="body">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="description" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>'

Alter table Venue
Drop column VenueDescription

Alter Table Venue
Add VenueDescription Xml(schema_VenueDescription)

Select * From Venue

Update Venue
Set VenueDescription ='<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
     <contactname>John Doe</contactname> 
    <datelastupdated>2012-7-1</datelastupdated>

  </header>
  <body>
 
   <description>
      The Gorge Amphitheatre is located in the Columbia River in George, 
      Washington. It offers lawn-terrace seating. Administered by Live Nation, 
      it is considered one of the premier and most scenic concert locations 
      not just in North America, but the world.[1] 
      The venue has been a host to big name performers like The Who, 
      David Bowie, Coldplay, Tom Petty, Pearl Jam, Dave Matthews Band, 
      Phish, and Rush. The venue offers sweeping and 
      majestic views of the Columbia River as it skirts the foothills 
      of the Cascade Range southbound, as well as extreme eastern Kittitas 
      County and extreme western Grant County. It is also known for its spectacular 
      views of the Columbia gorge canyon (not to be confused with the 
      Columbia River Gorge proper, which begins several tens of miles 
      further downstream as the river turns west to cross through the 
      Cascades toward Portland and the Pacific Ocean).

    </description> 
    
  </body>
  
</venuedescription>'

Where VenueId=2

Insert into venue( VenueName, VenueAddress1, VenueAddress2, VenueCity, VenueState, VenuePhone, VenueCapacity, VenueAgeRestriction, VenueURL, VenueDescription)
Values ('jazz Alley', null, '2033 6th Ave South', 'Seattle','WA','2065553214', 200,1,'http://jazzalley.com','<?xml version="1.0" encoding="utf-8"?>
<venuedescription xmlns="http://www.venutracker.com/description">
  <header>
 <datelastupdated>2012-23-1</datelastupdated> 
    <contactname>Jane Doe</contactname> 
    

  </header>
  <body>
 
    <description>
      An intimate venue with food and drinks for viewing world renowned artists.
    </description> 
    
  </body>
  
</venuedescription>')

use Automart

Select * From customer.AutoService

Select ServiceName, Serviceprice, 
ServiceDescription.query('declare namespace d="http://www.automart.com/servicedescription"; d:servicedescription/d:parts/d:part/d:perpartprice') as parts
From Customer.AutoService
Where ServiceName='tune up'

Wednesday, July 18, 2012

Reading and Writing Text files

Here is the file for writing text files. We tried to make it as generic as possible so it can be reused in a variety of contexts. One weakness of the class is that it is up to the user to call the closeFile method. A text file cannot be read or used if it is not closed

WriteFile.java


package com.spconger.www;

import java.io.*;

public class WriteFile {
 
 
 private String path;
 private PrintWriter writer;
 
 public WriteFile(String path) throws IOException{
  this.path=path;
  createFile();
 }
 
 private void createFile() throws IOException{
  
  
  FileWriter outFile = new FileWriter(path, true);
  writer = new PrintWriter(outFile);
  
 }
 public void addText(String content){
  
  writer.println(content);
 
 }
 
 public void closeFile(){
  writer.close();
 }
 

}


Here is the ReadFile.Java

package com.spconger.www;

import java.io.*;

public class ReadFile {
 
 private String path;
 
 public ReadFile(String path){
  this.path=path;
 }
 
 public String getText() throws FileNotFoundException ,IOException{
  String content="";
  FileInputStream fstream = new FileInputStream(path);
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  while ((strLine=br.readLine()) != null){
   content += (strLine + "\n");
  }
  
  return content;
 }

}


Here is the Program.java where we test our classes


package com.spconger.www;

import java.io.IOException;



public class Program {

 /**
  * @param args
  * 
  */
 public static void main(String[] args) {
  
   try {
    WriteFile write = new WriteFile("email.txt");
    write.addText("Steve" + ", steven.conger@seattlecolleges.edu");
    write.addText("George" + ", george@gmail.com");
    write.closeFile();
    
    ReadFile read = new ReadFile("email.txt");
    System.out.println(read.getText());
    
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
  
   
  }
  

 }


Tuesday, July 17, 2012

Hashing, Snapshots, Full Text Indexes

Use Automart
--inserting non english characters
--into a table
--the N stands for unicode
--the underlying type must be Nvarchar not varchar
Insert into Person(LastName, FirstName)
Values(N'κονγεροσ',N'Στεφονοσ')

--unicode character set
--1st 255 8 bits Ascii
--32000 16 bit character
--   24 bit character
--   32 bit character
--   64 bit character

Select * From Person

Select * From Customer.RegisteredCustomer

--hashbytes is a function that "hashes"
--a value. You can use various hash methods
--MD5 is one
Declare @password  varbinary(500)
Set @password=Hashbytes('MD5','jpass')
Select @password

--uses shai hash method
Declare @password  varbinary(500)
Set @password=Hashbytes('sha1','jpass')
Select @password

--add a column to the Registered customer table
Alter table Customer.RegisteredCustomer
Add hashedPassword varbinary(500)

Select * from Customer.RegisteredCustomer

--add a hash for the first customer
Update Customer.RegisteredCustomer
Set hashedPassword=HASHBYTES('MD5','jpass')
Where RegisteredCustomerID=1

--simulate checking the hash as if
--for a login
Declare @Password Varbinary(500)
Set @password = HASHBYTES('MD5','jpass')
if Exists
 (Select Hashedpassword from Customer.RegisteredCustomer
   Where hashedPassword=@password)
Begin
 Print 'Login successful'
End
Else
Begin
   Print 'Login Failed'
End

--snapshots
--a snapshot takes a picture of a database
--at a moment in time
--it only physically stores the data if it has changed in 
--the underlying database. the original form is copied to
--the snapshot
Create Database Automart_Snapshot
On
(Name ='Automart', Filename='C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Automart_Snapshot.ds')
As 
Snapshot of Automart

Use Automart_Snapshot

Select * From Person

Use Automart
Delete From Person where Personkey=54
--make some changes in the underlying database and then 
--compare the two database
Update Person
Set FirstName='Jason'
where personkey=1

--in an emergancy you can recover
--a database from a snapshot
use Master
Restore Database Automart from Database_Snapshot='Automart_Snapshot'

--Full Text Catalog
use Master

--add a filegroup
Alter Database Automart
Add Filegroup FullTextCatalog

use Automart
--add a table with some text
Create Table TextTest
(
   TestId int identity (1,1) primary key,
   TestNotes Nvarchar(255)
)

--insert text
Insert into TextTest(TestNotes)
Values('For test to be successful we must have a lot of text'),
('The test was not successful. sad face'),
('there is more than one test that can try a man'),
('Success is a relative term'),
('It is a rare man that is always successful'),
('The root of satisfaction is sad'),
('men want success')

Select * From TextTest

--create full text catalog
Create FullText Catalog TestDescription
on Filegroup FullTextCatalog

--Create a full text index
Create FullText index on textTest(TestNotes)
Key Index PK__TextTest__8CC33160412EB0B6
on TestDescription
With Change_tracking auto

--run queries on the full text catalog

--find all instances that have the word "sad"
Select TestID, TestNotes 
From TextTest
Where FreeText(TestNotes, 'sad')

--do the same with successful
Select TestID, TestNotes 
From TextTest
Where FreeText(TestNotes, 'successful')

Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"success"')

--look for any words containing the letters "success"
--the * is a wildcard
Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"success*"')

--looks for all grammatical forms of a word
Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, ' Formsof (Inflectional, man)')

--finds words near another word
Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, ' not near successful')

Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, ' sad near successful')


Functions and A Trigger

Use VenueTracker



--to do
--artist take venue take Sellout

--Function for sellout
--function for Venue take
--function for Artist take

--trigger to make a list of people to notify about upcoming events
Go

--this function has some problems. It duplicates capacity and so gives a false
--amount for shows that have multiple ticket vendors
Alter Function Venue.func_SellOut
(@ticketPrice decimal(5,2),
@Capacity int) --these are user provided parmeters
returns Decimal(9,2) --the return type for the function
As --begin function
Begin--functions require a begin and end statement
Declare @Total Decimal(9,2) --declare a variable
Set @Total= @ticketPrice * @Capacity --set the value
return @Total --return it
End
GO

Select VenueName, s.ShowID, TicketPrice, VenueCapacity, 
Venue.func_SellOut(TicketPrice, VenueCapacity) as Total
From Venue v
inner Join Show s
on s.VenueID = v.VenueID
inner join TicketOutlet t
on t.ShowID=s.ShowID

Select VenueName, s.ShowID, VenueCapacity, 
Sum(Venue.func_SellOut(TicketPrice, VenueCapacity) )as Total
From Venue v
inner Join Show s
on s.VenueID = v.VenueID
inner join TicketOutlet t
on t.ShowID=s.ShowID
Group by VenueName, s.ShowID,  VenueCapacity

Select * From TicketOutlet

Alter Table TicketOutlet
Add TotalTickets int

Select * From TicketOutlet
Select * From Venue
Go
Create Function Venue.func_CurrentSales
(@Totaltickets int, @TicketsRemaining int, @TicketPrice Decimal(5,2))
Returns Decimal(9,2)
As
Begin
Declare @TicketsSold int
Set @TicketsSold=@Totaltickets-@TicketsRemaining
Return @TicketsSold * @TicketPrice

End
--test the function
Select VenueName, s.ShowID, 
Venue.func_CurrentSales(TotalTickets, TicketsRemaining, ticketPrice)
As TotalSale
From Venue v
inner Join Show s
On v.VenueID=s.VenueID
Inner Join TicketOutlet t
on s.ShowID=t.ShowID
Go
--this is a view using the function
--it also uses a sum to combine the revenues
--of more than one ticket outlet
Go
Create View Venue.CurrentSalesSummary
As
Select VenueName, s.ShowID, 
Sum(Venue.func_CurrentSales(TotalTickets, TicketsRemaining, ticketPrice))
As TotalSale
From Venue v
inner Join Show s
On v.VenueID=s.VenueID
Inner Join TicketOutlet t
on s.ShowID=t.ShowID
Group by VenueName, s.ShowID

Select * From Venue.CurrentSalesSummary 
Where VenueName='Key Arena'

go
--this does the same as the view
--but requires the name of a venue
Create Proc Venue.usp_SalesSummary
@VenueName nvarchar(255)
As
Select VenueName, s.ShowID, 
Sum(Venue.func_CurrentSales(TotalTickets, TicketsRemaining, ticketPrice))
As TotalSale
From Venue v
inner Join Show s
On v.VenueID=s.VenueID
Inner Join TicketOutlet t
on s.ShowID=t.ShowID
Where VenueName=@VenueName
Group by VenueName, s.ShowID

Exec Venue.usp_SalesSummary 'Columbia Gorge'

--lets do a trigger
--Trigger will be triggered whenever there is an insert on the show table
--and it will make a table of people to be notified of upcoming events
--check the artistid and see if it matches any artistid in CustomerArtist Table where the ArtistAlert is set to true
--create a table of people to be alterted which will consist of the customer email, the artist name and the showvenue and date

Go
Create trigger tr_NotifyCustomers
on Show --the table the trigger applies to
For Insert  -- the even
As
Declare @ArtistID int
--inserted is a table that exists in the temp database
--it only exists for the duration of the transaction
--about a millesecond
Select @ArtistID=ArtistID from inserted
--check to see if someone wants to be alerted
--about the artist
If Exists
 (Select ArtistID from CustomerArtist
  Where ArtistID=@ArtistID 
  And ArtistAlert=1) 
Begin --if someone does
--check to see if our alert table exists
 If  not Exists
  (Select Name from sys.tables
   Where name='CustomersToAlert')
 Begin --if it doesn't create the table
  Create Table CustomersToAlert
  (
   CustomerEmail nvarchar(255),
   ArtistName nvarchar(255),
   VenueName nvarchar(255),
   ShowDate date,
   ShowTime Time
  )
 End --end if table doesn't exist
 --declare the variable we will need to
 --insert into our table
Declare @CustomerEmail nvarchar(255)
Declare @ArtistName nvarchar(255)
Declare @VenueName nvarchar(255)
Declare @ShowDate date
Declare @ShowTime time

--assign values to each of the variables
Select @ArtistName=ArtistName from Artist
Where ArtistID = @ArtistID

Select @CustomerEmail = CustomerEmail
From Customer c
Inner join CustomerArtist  ca
On c.CustomerID=ca.CustomerID
where ca.ArtistID=@ArtistID
And ca.ArtistAlert=1

Select @VenueName=VenueName
From Venue v
inner Join Inserted i
on v.VenueID=i.VenueID


Select @ShowDate = ShowDate, @ShowTime = ShowTime
From Inserted
--insert into our new alert table

Insert into CustomersToAlert(CustomerEmail, ArtistName, VenueName, ShowDate, ShowTime)
Values (@CustomerEmail, @ArtistName, @VenueName, @ShowDate, @ShowTime)

End
--/////this is the end of the trigger///---

--Test the trigger with an insert
Insert into Show(VenueID, ArtistID, TourName, ShowDate, ShowTime, ShowPosition, ShowDescription)
Values(3,1,'Some Kind of tour','8/12/2012','20:00:00','Headline',null)

Select * from CustomersToAlert

--it only inserted one value--we need to alter the trigger 
--to create a loop and a cursor 
--which will go through all the available records