Wednesday, August 15, 2012

Add JList Data on Selecting a Radio Button

Here is some code displays a different JList content depending on which radio button is selected.

First here are the forms


here is the code. It uses validate() and repaint() methods on the JFrame to refresh the form

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class mainForm extends JFrame implements ItemListener{
 private JPanel panel;
 private JPanel listPanel;
 private JPanel borderPanel;
 private JRadioButton one;
 private JRadioButton two;
 private JList list;
 private String[] arrayOne= new String[]{"Monday", "Tuesday", "Wednesday"};
 private String[] arrayTwo=new String[]{"Thursday", "Friday", "Saturday"};
 
 public mainForm(){
  CreatePanel();
  this.add(borderPanel);
  this.setBounds(100, 100, 200, 200);
  this.setVisible(true);
 }
 
 private void CreatePanel(){
  panel=new JPanel();
  borderPanel=new JPanel(new BorderLayout());
  
  one=new JRadioButton("one");
  one.addItemListener(this);
  two=new JRadioButton("two");
  two.addItemListener(this);
  list=new JList();
  
  ButtonGroup group = new ButtonGroup();
  group.add(one);
  group.add(two);
  
  panel.add(one);
  panel.add(two);
  listPanel=new JPanel();
  listPanel.add(list);
  
  borderPanel.add(panel, BorderLayout.CENTER);
  borderPanel.add(listPanel, BorderLayout.SOUTH);
  
 }

 @Override
 public void itemStateChanged(ItemEvent arg0) {

  
  Object source = arg0.getSource();
  if(source.equals(one)){
   
   list.removeAll();
   list.setListData(arrayOne);
   
   
  }
  else{
   list.removeAll();
   list.setListData(arrayTwo);
  }
  
  //borderPanel.add(listPanel, BorderLayout.SOUTH);
  //this.add(borderPanel);
  this.validate();
  this.repaint(); 
 }
 
 
}


Tuesday, August 14, 2012

Final Version of VenueAdmin

I am linking to a zip file of the VenueAdmin Application. The application uses LINQ to log in to the VenueTracker database with the VenueLogin and using the VenueRole. The login page gets the venue name and password. the password is hashed to not be in plain text. If the login is successful the venueid is stored in a Session variable, and the user is redirected to a second web page that retrieves and displays the information about their particular venue on the page using a datalist and an xml control.

There is a button on this web page that allows them to add a show. This redirects them to the add show form. On this form they can enter the show information and submit it. If the artist is not in the dropdown list they can click the add artist button and be directed to the form for entering a new artist. when the artist is submitted it returns them to the show page so that they can complete that form

Before I could get it to run I needed to suspend the trigger we had made earlier. That was the source of the no create table permission error. I also had to grant execute on the schema dbo. Here is the SQL for doing that

Use VenueTracker
Go
disable trigger tr_NotifyCustomers on Show
Go
Select * from Show

Grant exec on schema::dbo to VenueRole

It is also quite possible that you will need to edit the webconfig file to change the connection string. I mistyped "venulogin" for "VenueLogin" when I created the database login. Also substitute your password for mine and change the server name if you are not using localhost.

Here are pictures of the site running





Thursday, August 9, 2012

SQL Injection Attack

Here is an example of SQL injection attack. It takes a set of fairly foolish mistakes--connecting as admin, not validating the textbox, concatenating the text box directly into the SQL string etc. The key is to meet any critera of the query with something like "or 1=1", then do your command and end with a "--" or "/*" which comments out the rest of the SQL code. Our example takes an update statement. It provides a value, provides a closing quote and then comments out the remainder of the SQL. The result is that every field in the table will have the same value for that field.

Here is the c# for the example

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //or 1 =1; Drop table student /*
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection connect = new SqlConnection("Data Source=localhost;initial catalog=InjectionTest; Integrated Security=true");
        string sql = "Update tblPerson set Firstname='" + TextBox1.Text + "' where PersonKey=1"; 
        SqlCommand cmd = new SqlCommand(sql, connect);
        connect.Open();
        cmd.ExecuteNonQuery();
        connect.Close();
        Label1.Text = "thank you";

    }
}

Here is a picture of the form running


Here is a picture of the results

Tuesday, August 7, 2012

Creating a Login using LinQ

First we Reviewed some of the requirements for the Venue user


/*
Venue
Login and get their information
Edit own information
Add a show-- choose or add an Artist
Edit add tickets
See their own profits (stored procedure)
----
we have usp_venuShows
usp_AddVenue
usp_ShowList
Usp_UpdateVenue
veiw CurrentSalesSummary

-- 
add some privledges to venuerole
--select and insert on Artist, ArtistGenre
--Select and insert on show
--Select and insert on ticketoutlet
--add a password field to the Venue
*/

Here is the code for creating a login. First we had to make some changes in SQL Server. We added a password field to the Venue Table


Use VenueTracker 

Alter Table Venue
add VenuePassword varbinary(500)

Then we added passwords for each of the venues. Your VenueIDs may be different than mine


Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'arena')
update Venue 
Set VenuePassword=@password
where VenueID=1
go
Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'gorge')
update Venue 
Set VenuePassword=@password
where VenueID=2
go
Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'tractor')
update Venue 
Set VenuePassword=@password
where VenueID=3

go
Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'comet')
update Venue 
Set VenuePassword=@password
where VenueID=4

go
Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'nuemos')
update Venue 
Set VenuePassword=@password
where VenueID=6

go
Declare @password varbinary(500)
Set @password = HASHBYTES('MD5', 'jazz alley')
update Venue 
Set VenuePassword=@password
where VenueID=9

Next we added some permissions to the VenueRole


Grant Select on Artist to VenueRole
Grant Insert on Artist to VenueRole
Grant Select on Show to VenueRole
Grant Insert on show to VenueRole
Grant Select on TicketOutlet to VenueRole
Grant Insert on TicketOutlet to Venuerole
Grant Select on Venue to VenueRole
Grant Update on Venue to VenueRole
Grant Select on ArtistGenre to VenueRole
Grant Insert on ArtistGenre to Venuerole


Next we went to Visual Studio 2010 and started an empty web site. We added a web page and then added a LINQ to SQL Classes. Then we added a new data connection using SQL server Authentication and the VenueLogin. We dragged on all the tables and stored procedures available in that login.


Next we added a new item, a class called PasswordHash. The purpose is to take the password entered into the login control and convert it to a MD5 hash


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

/// 
/// Summary description for PasswordHash
/// 
public class PasswordHash
{
    
 public PasswordHash()
 {
  
 }

    //I changed this to return a Byte array instead of a string
    //that makes it work
    public Byte[] hashedpassword(string pass)
    {
        Byte[] originalBytes;
        Byte[] encodedBytes;
        MD5 md5=MD5.Create(); //this is also a change

      
        originalBytes = ASCIIEncoding.Default.GetBytes(pass);
        encodedBytes = md5.ComputeHash(originalBytes);
        //string hashstr = ConvertBytes(encodedBytes);
        return encodedBytes;

    }

    //No longer need this method though it is a neat
    //use of Regular expressions

    //private string ConvertBytes(Byte[] encodedBytes)
    //{
    //    string x = BitConverter.ToString(encodedBytes);
    //    Regex rgx = new Regex("[^a-zA-Z0-9]");
    //    x = rgx.Replace(x, "");
    //    return "0x" + x;
    //   // return x;
       
    //}

}

Here is the login class


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

/// 
/// Summary description for LoginClass
/// 
public class LoginClass
{
    string name, pass;
 public LoginClass(string name, string pass)
 {
        this.name = name;
        this.pass = pass;
 }

    public int ValidateLogin()
    {
        int vID = 0;
        PasswordHash ph = new PasswordHash();
        Byte[] hashed = ph.hashedpassword(pass);

        VenueClassesDataContext context = new VenueClassesDataContext();

        var log = from l in context.Venues
                  where l.VenueName == name && l.VenuePassword == hashed
                  select new { l.VenueID, l.VenueName, l.VenuePassword };
        //match it as byte[] instead of string
       //&& l.VenuePassword.ToString() == hashed

        if (log != null)
        {
            foreach (var i in log)
            {
                Console.WriteLine(i.VenuePassword);
                vID = i.VenueID;
  
            }
        }
            


        return vID;
    }
}

Here is the code behind for Default.aspx.cs


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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //PasswordHash ph = new PasswordHash();
        //string passwrd = ph.hashedpassword("arena");
        //Response.Write(passwrd);
    }
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        LoginClass lc = new LoginClass(Login1.UserName, Login1.Password);
        int id = lc.ValidateLogin();
        Response.Write(id.ToString());
        if (id != 0)
        {
            Session["venueid"] = id;
            
            e.Authenticated = true;
            Response.Redirect("Default2.aspx");
        }
        else
        {
            e.Authenticated = false;
        }
    }
}

Here is the source for Default.aspx


<%@ 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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Venue Login</h1>
        <asp:Login ID="Login1" runat="server" BackColor="#EFF3FB" BorderColor="#B5C7DE" 
            BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" 
            Font-Size="0.8em" ForeColor="#333333" onauthenticate="Login1_Authenticate">
            <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
            <LoginButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" 
                BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" />
            <TextBoxStyle Font-Size="0.8em" />
            <TitleTextStyle BackColor="#507CD1" Font-Bold="True" Font-Size="0.9em" 
                ForeColor="White" />
        </asp:Login>
    </div>
    </form>
</body>
</html>


Here is the source code for Default2.aspx


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

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Welcome</h1>
    </div>
    </form>
</body>
</html>

Wednesday, August 1, 2012

Dynamically generating Checkboxes and accessing their content

Here is code which automatically generates checkboxes based on an arraylist of strings. The trick to accessing the checkboxes afterwards is to also store them in a an arraylist. Here is the code for CheckboxTest.java


package com.spconger.www;
/*
 * This class creates two arrays
 * one for a list of titles
 * and one to store dynamically created
 * checkboxes
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.*;

public class CheckboxTestForm {
 
 //declare private fields
 private ArrayList titles; //arraylist for titles
 private JFrame frame;
 private ArrayListchecks; //array of checkboxes
 private JPanel panel;
 private JButton button;
 private JLabel result;
 private JCheckBox chk;
 
 //constructor that calls the methods
 //and initializes the checkbox array
 public CheckboxTestForm(){
  fillArray();
  checks = new ArrayList();
  createCheckBoxes();
 }
 
 private void fillArray(){
  //this method populates the array
  //manually--you could do this
  //dynamically with user input
  titles=new ArrayList();
  titles.add("Foundation Trilogy");
  titles.add("lord of the Rings");
  titles.add("1@84");
  titles.add("The Martian Chronicles");
 }
 
 private void createCheckBoxes(){
  //set up the frame
  JFrame frame=new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  //call the method to create the panel
  createPanel();
  //add the panel to the frame and make it visible
  frame.add(panel);
  frame.setBounds(100,100,300,300);
  frame.setVisible(true);
 }
 
 private void createPanel(){
  //initialize the panel
  panel = new JPanel();
  panel.setLayout(new GridLayout(0,1,5,5));
  //loop through the title array
  for (String s:titles){
    //create a new checkbox 
   //for each string in the array
    chk=new JCheckBox(s);
    //add the checkbox to the panel
    panel.add(chk);
    //add the checkbox to the array
    //of checkboxes
    checks.add(chk);
  }
  
  //add a button
  button=new JButton("Test");
  //assign a listener
  button.addActionListener(new buttonListener());
  //add it to the panel
  panel.add(button);
  
  //add a label to show the results
  result = new JLabel();
  panel.add(result);
  
  
 }
 
 private class buttonListener implements ActionListener{
  /*
   * (non-Javadoc)
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   * This class responds to the button click
   */
  @Override
  public void actionPerformed(ActionEvent arg0) {
   String s="";
   //loop through the array of checkboxes
   //and get the text of each checkbox
   //that is checked
   for (JCheckBox ck:checks){
    if(ck.isSelected()){
    s += ck.getText() + ", ";
    }
   }
   //display the results
   result.setText(s);
  }
  
 }

}


Here is the code for Program.java


package com.spconger.www;

public class Program {

 /**
  * this program is an example of 
  * creating checkboxes dynamically
  * on the fly. You can use this in
  * a todo list. Add your tasks to an 
  * Array List and then dynamically display them
  * The main merely calls the class
  */
 public static void main(String[] args) {
  CheckboxTestForm c= new CheckboxTestForm();

 }

}