28 November 2016

CST438 Week 5

This week we discussed code review.


Basically a successful peer review strategy for code review requires a balance between the strictly documented processes and a non-threatening collaborative environment. Strictly regulated peer reviews can hinder productivity, yet careless processes are often ineffective. Ideally a middle ground can be found where peer review can be both efficient and effective while promoting open communication and knowledge sharing among teammates.

20 November 2016

CST438 Week 4

This week we covered the vulnerabilities exploited in the Sony Corp and Target Department Store security breaches, steps that can be taken in program design and code for better security, principles of software security and we took the mid-term exam.

Of particular interest was the article on Secure Programming. I was already familiar with validating input and restricting operations, but found the other design suggestions fascinating.

15 November 2016

CST438 Week 3

List and use common design patterns such as Publish-Subscribe, Proxy, Visitor for developing high quality modular object oriented code.
Use CRC (Class Responsibility Collaboration) cards as an object-oriented design tool.
Use UML class and sequence diagrams to create higher level abstract models of a software system.
Complete iteration #2 of your team project using Agile.

08 November 2016

CST438 Week 2



We covered:
  • Black box testing – Internal system design is not considered in this type of testing. Tests are based on requirements and functionality;
  • White box testing – This testing is based on knowledge of the internal logic of an application’s code. Also known as Glass box Testing. Internal software and code working should be known for this type of testing. Tests are based on coverage of code statements, branches, paths, conditions;
  • Unit testing – Testing of individual software components or modules. Typically done by the programmer and not by testers, as it requires detailed knowledge of the internal program design and code. may require developing test driver modules or test harnesses;
  • System testing – Entire system is tested as per the requirements. Black-box type testing that is based on overall requirements specifications, covers all combined parts of a system.
  • Code coverage – A measure used to describe the degree to which the source code of a program is executed when a particular test suite runs;
  • Mutation testing – A structural testing technique, which uses the structure of the code to guide the testing process. On a very high level, it is the process of rewriting the source code in small ways in order to remove the redundancies in the source code;
  • Fuzz testing – A software testing technique used to discover coding errors and security loopholes in software, operating systems or networks by inputting massive amounts of random data, called fuzz, to the system in an attempt to make it crash.
  • JUnit – A unit testing framework for the Java programming language.

The idea of TDD (Test Driven Development) is new for me, I had not even heard of this before. I will be attempting it with the J2EE iteration of the Hangman Game. I have been very limited on time the last couple of weeks (due to work), so have had difficulty completing the assignments thus far. The weekend that I am writing this (11/12-11/13) I am working to catch up.

01 November 2016

CST438 Week 1

This week we discussed software trends like the consolidated language movement (HTML+CSS+JavaScript), NoSQL Databases, RESTful APIs and SaaS (like Google Maps, IBM Watson and Microsoft Office 365).

We also introduced the standard methodologies of WaterFall, Agile and Formal Methods. I am already very familiar with WaterFall, as I use it at work for managing store opening projects. I am also already familiar with Agile (albeit less familiar), as we use a version of Agile called SDDM at my work for software development projects.

We also covered version control systems, but focused in particular on Git and GitHub. I have used GitHub in the past to collaborate on small software packages and here as CSUMB to coordinate with students on group projects.

I have been very limited on time the last couple of weeks (due to work), so have had difficulty completing the assignments thus far. The weekend that I am writing this (11/12-11/13) I am working to catch up.

25 October 2016

CST338 Week 8

This class is done, my final grade was a 'B'. Need to get back to entries for the Learning Journal.

This week we worked on:
Final Project
  1. Design and write a spec sheet including UML diagrams
  2. Then choose one:
    • Create a video 10-15 minutes long
    • Code the program you designed (Android Studio quit on me during this stage, so opted for video)

18 October 2016

CST338 Week 7

A week was not nearly enough time for the subject matter, but:
By the end of this module you will be able to:
android
  1. Do basic Android Programming

11 October 2016

CST338 Week 6

By the end of this module you will be able to:
  1. Design and code Java Multi-threading into a project
  2. Apply a Design Pattern in a programming project
Design patterns

04 October 2016

CST338 Week 5

By the end of this module you will be able to:
GUI example
  1. Use Swing and Event-Driven Programming
  2. Analyze Layout Managers
  3. Make use of Menus, Buttons, Text Fields, and Text Areas in GUI programs
  4. Work with User Interface Design

27 September 2016

CST338 Week 4

By the end of this module you will be able to:polymorphism example
  1. Understand how to use Polymorphism and Abstract classes
  2. Identify the Software Life-Cycle and Processes
  3. Work with Interfaces and Inner classes
  4. Analyze and create UML diagrams

20 September 2016

CST338 Week 3

By the end of this module you will be able to:
bart simpson writing "I will not reuse code through inheritance"
  1. Work with Wrapper classes
  2. Understand References and class parameters
  3. Use Arrays and references
  4. Design and implement Inheritance

13 September 2016

CST338 Week 2

OOP is not in all languages.  Have you used one that does not?
I have used Perl (professionally), C++ (p), Python (academically), PHP (a) and Java (a) which are all object oriented.
What was your experience? How extensively have you used OOP outside of the classroom?
When programming for Perl I rarely (if ever) used the object-oriented aspects of the language. While using C++, on the other hand, I used objects constantly as the tremendous need for reusing code across multiple applications and data stores. These were used for very different purposes and to very different scales. Often OOP is oversold as a solve-all solution - to the extent that Java forces you to think of everything in terms of objects.
Are you experience with UML diagrams and do they help?
UMLs are essential for any application. I have worked with UMLs ranging from sketches on napkins from late night meetings at bars to multi-level digital UMLs including responsibilities, interfaces and class diagrams. The UML is your road map to building any application, it's importance only grows as the workload of developing a larger application is shared among more than one person.
Update your learning journal from what you experienced this week with class.
We created an OOP class, used constructors & overload methods, used arrays & ArrayList and implemented static methods & static variables.

06 September 2016

CST338 Week 1

Have you used Eclipse before?
Use it all the time.

What languages are you proficient in at this point?
C++, Visual Basic and Perl.

What is your desired field of Computer Science at this point?
It remains networking which is closely related to my existing field of work.

Update your learning journal from what you experienced this week with class.
Was quick and simple. This was a good thing as I was travelling for work this week.


30 August 2016

CST361S Week 8

No posting - travelling for work.

23 August 2016

16 August 2016

CST361S Week 6

No posting - travelling for work.

09 August 2016

CST361S Week 5

This week we covered Community and Social Justice, more Project Management basics and continued investigating ideas for our final Capstone. I have been excited for this final Capstone project since we started this adventure almost a year ago.

For my 4 main capstone ideas I am interested in (in order of interest):
  1. Security Guard Reporting App (actually have a client that might pay for this)
    • Android User Interface
    • Using web facing database
    • Requires use of GPS and possibly voice & phone integration
  2. An open source online small business accounting package.
    • Downside is there are hundreds of these out there
    • Scale could be a problem, this is an extensive project
    • Upside is that it often touches on so many disciplines
    • May require bringing in an accountant to validate backend
  3. Open Source Electronic Lab Notebook (could be useful at my work)
    • Custom Android OS build required
    • Using intranet facing database
    • Requires extensive audit trail (21 CFR Part 11 compliance)
  4. Restaurant Menu/Ordering System (like Ziosk but for small restaurants)
    • Custom Android OS build required (possible custom hardware)
    • Integrated system to not just take orders, but to also show them to kitchen
    • Using intranet facing database
I still like the idea of open source textbooks, but time and manpower would be extensive. Also requires a marketing budget. Also many have attempted it, but failed.


01 August 2016

CST361S Week 4

This week we covered Service and Social Responsibility & Project Management. As a New Store IT Project Manager, this is obviously a subject near and dear to my heart. It was nice to review some of the basics that you take for granted after awhile.
Officially a project is "a temporary endeavor undertaken to create a unique product, service or result. A project is temporary in that it has a defined beginning and end in time, and therefore defined scope and resources." So project management is "the application of knowledge, skills, tools, and techniques to project activities to meet the project requirements." As the instructor for the Coursera unit mentioned in one of his lectures, people will often manage projects without realizing that is what they are doing. Almost any time you have a temporary endeavor it can be managed like a project. Take for example your summer vacation - you have everything from planning and budgeting to implementation there, without even realizing it. Project management is really a structured methodology used to complete any project.

26 July 2016

CST361S Week 3

I spent the last few days working at my service learning location - Community Youth Center (CYC). For this service I taught 2 days of a weeklong science camp for kids. For day one we discussed algorithms - what they are and how we use them every day. Then we moved into discussing additional basic programming concepts like loops. We finished the day by working on Hour of Code exercises and making Bristle Bots.


     
For day two we covered Physics. We started by introducing the Scientific Method and introduced electricity using my Van De Graff Generator.
* Stock Photo

19 July 2016

CST361S Week 2

No posting - performing volunteer time.

12 July 2016

CST361S Week 1

No posting - due to new job.

18 June 2016

CST311 Week 8

This was a short week due to the Final. We finished up the Link Layer, in particular ARP and switches.

The address resolution protocol (ARP) is a protocol used by IPv4 to map IP network addresses to the hardware addresses used by a data link protocol. The protocol operates below the network layer as a part of the interface between the network and link layers.

Ethernet switches are a link layer device that takes an active role in storing and forwarding Ethernet frames by examining incoming frames MAC address and selectively forwarding frame to one or more outgoing links when frame is to be forwarded on segment. Uses CSMA/CD to access segment.


14 June 2016

CST311 Week 7

This week we continued the Network Layer and introduced the Link Layer. For the network layer we covered Routing and Forwarding, Dijkstra's Algorithm, Distance Vector Algorithm and for the link layer we covered Error Detection and Correction & MAC Protocols.

Routing answers the question of what next hop IP to send a packet based on the destination prefix while forwarding functions determine which exit interface to use to send the packet to its next hop.
Parity Checking of Error Detection is the simplest technique for detecting and correcting errors. The MSB of an 8-bits word is used as the parity bit and the remaining 7 bits are used as data or message bits. The parity of an 8-bit transmitted word can be either even or odd parity.

The Medium Access Control (MAC) protocol is used to provide the data link layer of the Ethernet LAN system.

07 June 2016

CST311 Week 6

This week we covered the Network Layer, including IP datagram format, IP Addressing, ICMP and Traceroute and DHCP.
An Internet Protocol address (IP address) is a numerical label assigned to each node participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. In the IPv4 scheme addresses are 32 bits.

Traceroute, by default, sends a sequence of User Datagram Protocol (UDP) packets addressed to a destination host; ICMP Echo Request or TCP SYN packets can also be used. The time-to-live (TTL) value, also known as hop limit, is used in determining the intermediate routers being traversed towards the destination.

Dynamic Host Configuration Protocol (DHCP) is a client/server protocol that automatically provides an Internet Protocol (IP) host with its IP address and other related configuration information such as the subnet mask and default gateway.

31 May 2016

CST311 Week 5

This week we continued to cover the Transport Layer including TCP segment structure, reliable data transfer, TCP flow control and TCP congestion control.
TCP segment structure. Transmission Control Protocol accepts data from a data stream, divides it into chunks, and adds a TCP header creating a TCP segment. The TCP segment is then encapsulated into an Internet Protocol (IP) datagram, and exchanged with peers.

For connection-oriented service provided by TCP, it is necessary to have a reliable data transfer (RDT) protocol to ensure delivery of all packets and to enable the receiver to deliver the packets in order to its application layer. A simple alternating bit RDT protocol can be designed using some basic tools.

TCP uses an end-to-end flow control protocol to avoid having the sender send data too fast for the TCP receiver to receive and process it reliably. Having a mechanism for flow control is essential in an environment where machines of diverse network speeds communicate. For example, if a PC sends data to a smartphone that is slowly processing received data, the smartphone must regulate the data flow so as not to be overwhelmed.

TCP uses a multi-faceted congestion-control strategy. For each connection, TCP maintains a congestion window, limiting the total number of unacknowledged packets that may be in transit end-to-end. TCP uses a mechanism called slow start to increase the congestion window after a connection is initialized and after a timeout. It starts with a window of two times the maximum segment size (MSS). Although the initial rate is low, the rate of increase is very rapid: for every packet acknowledged, the congestion window increases by 1 MSS so that the congestion window effectively doubles for every round-trip time (RTT). When the congestion window exceeds the ssthresh threshold, the algorithm enters a new state, called congestion avoidance.

24 May 2016

CST311 Week 4

This week we began covering the transport layer. This was a light week since homework, quiz and lab were due after just 2 days (due to midterm).

Multiplexing:


UDP:

17 May 2016

CST311 Week 3

This week we covered more of the application layer.

SMTP:


DNS:


Caching:

10 May 2016

CST311 Week 2

This week we we covered protocol layers, history and the application layer.

HTTP:


Cookies:


FTP:

03 May 2016

CST311 Week 1

We covered a lot this week, including what is the Internet, the network core vs edge, packet switching vs circuit switching, throughput and delay. Reminds me of the OSI model:


We really only covered parts of this briefly, but this is the basis of network communications - so I'm sure there's a lot more of it to come. About a year ago I took a good quality refresher video course that covered the same materials from Engineering Mentor.

25 April 2016

CST363 Week 8

This week was all about the final project. Our group (BITsoft) built a database system for "Fish and Friends" which is America’s premiere aquarium supply store. Our database keeps track of important
business information as well as general store information like inventory levels and the status of fish tanks in our store.

Most interesting was the SQL menu system:

SET define on
SET verify off
SET heading off
SET echo off

PROMPT 'Welcome to Fish and Friends';
PROMPT
PROMPT '1: Product Lookup           | 2: Employee Lookup';
PROMPT '3: Sales Order Lookup       | 4: Customer Lookup';
PROMPT '5: Vendor Lookup            | 6: Tank Water Alerts';
PROMPT '7: Tank Water Quality Input | 8: Create Invoice';

ACCEPT input PROMPT 'Enter selection:';

col menu new_val menuVar

SET term off
SELECT
   CASE '&input'
      WHEN '1' THEN '@productLookup.sql' 
      WHEN '2' THEN '@employeeLookup.sql'
      WHEN '3' THEN '@salesLookup.sql'
      WHEN '4' THEN '@customerLookup.sql'
      WHEN '5' THEN '@vendorLookup.sql'
      WHEN '6' THEN '@tankstatusLookup.sql'
      WHEN '7' THEN '@tankstatusInput.sql'
      WHEN '8' THEN '@createInvoice.sql'
      ELSE '@queryFishStore.sql'
   END AS menu 
FROM DUAL;
SET term on

@&menuVar

17 April 2016

CST363 Week 7

This week we covered sequences (such as used as primary key), alias (temporary name for table or column), text processing (such as concatenation, lower, upper, initcap, ltrim, rtrim, lpad, rpad and substr) and date & time (to_char and sysdate).

For the assignment we built on last weeks lookup script:

set echo off
set verify off
set heading off
set feedback off
accept OtterIDT prompt 'Please enter the OtterID:';
prompt 'Thank you!';
SELECT 'Student OtterID: ', substr(OtterID, 0, 3) || '-' || substr(OtterID, 3, 2) || '-' || substr(OtterID, 5, 4) FROM student WHERE OtterID='&OtterIDT';
SELECT 'Name: ', upper(Name) FROM student WHERE OtterID='&OtterIDT';

11 April 2016

CST363 Week 6

We covered additional SQL and SQLPlus commands including grouping and subqueries. The GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. An example of this command is:

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

A subquery is a query within another query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. An example of this command is:

SELECT column_name [, column_name ]
FROM   table1 [, table2 ]
WHERE  column_name OPERATOR
      (SELECT column_name [, column_name ]
      FROM table1 [, table2 ]
      [WHERE])

We also touched on SQL I/O. As a side note, it would be helpful if the class covered more troubleshooting commands like DESCRIBE as well.

04 April 2016

CST363 Week 5

EDIT: This week we learned about ERD (Entity Relationship Diagrams). This is very useful for designing and documenting databases. The first is the Chen diagram, like so:


The next was the Crows Feet diagram, like so:



Both are obviously useful and I hope to put them into practice soon.

I have been saying that far worse than the possibility of loss of classified information is her blatant attempt to side-step the Freedom of Information Act. An editorial from the Milwaukee Journal Sentinel titled “Clinton’s abysmal record on open government” explains the probable political motive regarding Clinton’s unconventional email practices:
"The issue immediately at hand — and under investigation by the FBI — is Clinton’s use of a private email server for State Department communications. Clinton may have violated national security laws by making top secret documents vulnerable to hackers and available to people without proper security clearance…
In addition, regardless of Clinton’s excuses, the only believable reason for the private server in her basement was to keep her emails out of the public eye by willfully avoiding freedom of information laws. No president, no secretary of state, no public official at any level is above the law. She chose to ignore it, and must face the consequences…
And donations to the foundation from foreign governments have raised conflict of interest questions for Clinton as secretary of state, an office with power over foreign affairs and favors second only to the president’s."


29 March 2016

CST363 Week 4

Been very busy with work and have fallen behind in class (not good). This week we learned about database normalization. When I learned about databases I just took these items for granted, and since I have not had to work with large databases it has not made a difference. This was more about why we make the decisions in database design.


Best Sci-Fi Movies to re-watch:
15) Sphere
14) Titan AE
13) Enemy Mine
12) Pitch Black
11) Stalker (79)
10) 2010 - The Year We Make Contact
09) Primer
08) Heavy Metal
07) Mr Nobody
06) Silent Running
05) Equilibrium
04) Strange Days
03) eXistenZ
02) Sunshine
01) Moon

23 March 2016

CST363 Week 3

This week we covered the basics of SQL.

SQL for creation of tables:

set echo on

DROP TABLE truck;
DROP TABLE type;
DROP TABLE base;
CREATE TABLE base (
 base_code char(3) PRIMARY KEY,
 base_city varchar2(15),
 base_state char(2),
 base_area_code char(3),
 base_phone varchar2(10),
 base_manager varchar2(20)
);
INSERT INTO base VALUES('501', 'Mulfreesboro', 'TN', '615', '123-4567', 'Andrea D Gallager');
INSERT INTO base VALUES('502', 'Lexington', 'KY', '568', '234-5678', 'George H. Delarosa');
INSERT INTO base VALUES('503', 'Cape Girardeau', 'MO', '456', '345-6789', 'Maria J. Talindo');
INSERT INTO base VALUES('504', 'Dalton', 'GA', '901', '456-7890', 'Peter F. McAvee');
CREATE TABLE type (
 type_code char(1) PRIMARY KEY,
 type_description varchar2(30)
);
INSERT INTO type VALUES('1', 'Single box, double-axle');
INSERT INTO type VALUES('2', 'Single box, single-axle');
INSERT INTO type VALUES('3', 'Tandem trailer, single-axle');
CREATE TABLE truck (
 truck_num char(4) PRIMARY KEY,
 base_code char(3),
 type_code char(1),
 truck_miles number(7,1),
 truck_buy_date date,
 truck_serial_num varchar2(20),
 CONSTRAINT fk_base_code FOREIGN KEY (base_code) REFERENCES base(base_code),
 CONSTRAINT fk_type_code FOREIGN KEY (type_code) REFERENCES type(type_code)
);
INSERT INTO truck VALUES('1001', '501', '1', 32123.5, '23-Sep-2007', 'AA-322-12212-W11');
INSERT INTO truck VALUES('1002', '502', '1', 76984.3, '05-Feb-2006', 'AC-342-22134-Q23');
INSERT INTO truck VALUES('1003', '501', '2', 12346.6, '11-Nov-2006', 'AC-445-78656-Z99');
INSERT INTO truck VALUES('1004', null, '1', 2894.3, '06-Jan-2007', 'WQ-112-23144-T34');
INSERT INTO truck VALUES('1005', '503', '2', 45673.1, '01-Mar-2006', 'FR-998-32245-W12');
INSERT INTO truck VALUES('1006', '501', '2', 193245.7, '15-Jul-2003', 'AD-456-00845-R45');
INSERT INTO truck VALUES('1007', '502', '3', 32012.3, '17-Oct-2004', 'AA-341-96573-Z84');
INSERT INTO truck VALUES('1008', '502', '3', 44213.6, '07-Aug-2005', 'DR-559-22189-D33');
INSERT INTO truck VALUES('1009', '503', '2', 10932.9, '12-Feb-2008', 'DE-887-98456-E94');

15 March 2016

CST363 Week 2

During this week we delved into Relational Algebra (a procedural query language, which takes instances of relations as input and yields instances of relations as output. It uses operators to perform queries. An operator can be either unary or binary. They accept relations as their input and yield relations as their output.) and how it relates to SQL (Structured Query Language). We were also introduced to SQL commands and installed a local Oracle database.

07 March 2016

CST363 Week 1

Installed Oracle Linux/Database virtual machine.


What is Information Technology? It's the technology that helps the organization collect, store, retrieve and apply knowledge to solve problems; IT converts the raw material of information into usable knowledge. IT refers to all forms of technology applied to processing, storing and transmitting information in electronic form.


01 March 2016

CST363 Week 0

We covered the concepts behind database design, in particular the various keys. I have always had a problem understanding the conceptual keys, but I did find a helpful video at https://youtu.be/dYNw9Va7AtM.

  • A Super key is any combination of fields within a table that uniquely identifies each record within that table.
  • A Candidate key is a subset of a super key. A candidate key is a single field or the least combination of fields that uniquely identifies each record in the table. The least combination of fields distinguishes a candidate key from a super key. Every table must have at least one candidate key but at the same time can have several.
  • A Primary key is a candidate key that is most appropriate to be the main reference key for the table. As its name suggests, it is the primary key of reference for the table and is used throughout the database to help establish relationships with other tables. As with any candidate key the primary key must contain unique values, must never be null and uniquely identify each record in the table.
  • A Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.
  • A table may have one or more choices for the primary key. Collectively these are known as candidate keys. One is selected as the primary key. Those not selected are known as Secondary keys or alternative keys.
  • A Compound key consists of more than one field to uniquely identify a record. A compound key is distinguished from a composite key because each field, which makes up the primary key, is also a simple key in its own right.
  • A Composite key consists of more than one field to uniquely identify a record. This differs from a compound key in that one or more of the attributes, which make up the key, are not simple keys in their own right.
If that makes your brain hurt, don't worry, it makes mine hurt as well. Luckily practice makes this easier to understand than just explaining it.

Continued on Week 1

22 February 2016

CST336 Week 8

Finals week! Final went well - quite challenging. The best part was the programming portion (almost half the grade and over 2/3 the total time). I was especially glad I paid attention to the SQL portion ;) . Since I like to post code, but don't think it's a good idea to post the final, here is what I got for lab 8. Note that the hardest part of this assignment was figuring out the permissions necessary to copy the file elsewhere in the filesystem. The assignment completed in class that used the database was much easier to implement.


<?php
/* STEP 2 *******************/
session_start();

 if (!isset ( $_SESSION['username']))  {
     if (isset ($_POST['loginForm'])) {
        require '../db_connection.php'; 
        $sql = "SELECT * 
                FROM lab9_user
                WHERE username = :username
                AND password = :password";
        $stmt = $dbConn -> prepare($sql);
        $stmt -> execute( array(":username" => $_POST['username'],
                                ":password" => sha1($_POST['password'])));
        $record = $stmt->fetch();
        if (!empty($record)) {
            $_SESSION['username'] = $record['username'];
            $_SESSION['profilePic'] = $record['profilePic'];
            echo "<h2> Welcome  " . $record['realName'] . "!</h2>";
            $location = "/var/www/johnlester.rocks/cst336/labs/lab8Images/" . $record['username'];
   $uold = umask(0);
   if (!file_exists($location)) {
    mkdir($location,0777,true);
    umask($uold);
      //mkdir("/var/www/johnlester.rocks/cst336/labs/lab8Images/" . $record['username'], 0777, true);
            }
        } else {
            $error = " Wrong username / password";
            header("Location: lab8.html");
        }
     }  
 }
 
 
/* STEP 3 *******************/
  if (isset($_FILES['fileName'])) {
     $_SESSION['profilePic'] = $_FILES['fileName']['name'];
     move_uploaded_file($_FILES['fileName']['tmp_name'], "lab8Images/" . $_SESSION['username'] . "/" . $_FILES['fileName']['name'] );
    //Syntax move_uploaded_file ( string $filename , string $destination )
  }
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Profile</title>
  <link rel="shortcut icon" href="/favicon.ico">
</head>

<body id="wrapper">
  <div>
<?php
   if (empty($_SESSION['profilePic'])) {
           echo "<img class='profilepic' src='lab8Default.png'><br/>";
   } else {
            echo "<h2> Welcome  " . $_SESSION['realName'] . "!</h2>";           
           echo "<img class='profilepic' src='./lab8Images/" . $_SESSION['username'] . "/" . $_SESSION['profilePic'] . "'><br/>";
   }
?>
  
  </div>
  <!--- Step 1 ****************-->
  <div align="left" class="upload">
  <form method="post" enctype="multipart/form-data">
      <br/>
      
      Select File to update profile picture:
      <br />
      <input type="file" name="fileName" />
      <br/>
      <input type="submit" name="loginForm">
      
  </form>
  
   </div>
</body>
</html>

16 February 2016

CST336 Week 7

Some great new content this week including AJAX, XML and JSON (mostly new to me). Using what we learned this week I began improving a web site of mine. For assignment 7 I began work on http://www.diablofirearms.com/classSignup.php. This courses content has given me all kinds of ideas on using databases more throughout this site. For this page I used the following code to require a log in (or creation of user account):

<?php
session_start();

if(!isset($_SESSION['username'])) {
 header("Location: userLogin.php");
}
?>

Then for the login/account creation page I used the following:
<?php
session_start();

if (isset($_POST['loginname'])) {
 require 'db_connection.php';

 $sql = "SELECT *
 FROM students
 WHERE username = :username
 AND password = :password";

 $stmt = $dbConn -> prepare($sql);
 $stmt -> execute(array(":username" => $_POST['loginname'], ":password" => hash("sha1", $_POST['password'])));
 $record = $stmt -> fetch();
 if (!empty($record)) {
  $_SESSION['username'] = $record['username'];
  $_SESSION['name'] = $record['name'];
  header("Location: classSignup.php");
 }
}
?>
<html>
<head>
  <meta content="text/html; charset=utf-8" http-equiv="content-type">
  <title>Diablo Firearms Training - Student Login</title>

<!-- Extra code removed for size -->

  <u><font color="red" size="5"><strong>Account Log In</strong></font></u>
      <form method=post>
        <table border="0">
          <tbody>
            <tr>
              <td style="text-align: right;">Username: </td>
              <td><input tabindex="1" name="loginname"></td>
            </tr>
            <tr>
              <td style="text-align: right;">Password: </td>
              <td><input tabindex="2" name="password" type="password"></td>
            </tr>
            <tr>
              <td style="text-align: center;" colspan="2"><input tabindex="3" value="Log In" type="submit"><input value="Reset" type="reset"></td>
            </tr>
          </tbody>
        </table>
      </form>

      <div align="center"><u><font color="red" size="5"><strong>New Account
Creation</strong></font></u></div>
      <form method=post action=createUser.php>
        <table border="0">
          <tbody>
            <tr>
              <td style="text-align: right;">New Username: </td>
              <td><input id="username" name="username" type=text required><span id="checkUsername"></span></td>
            </tr>
            <tr>
              <td style="text-align: right;">Password: </td>
              <td><input id=newPassword name="newPassword" type="password" required><span id="checkPassword"></span></td>
            </tr>
            <tr>
              <td style="text-align: right;">Repeat Password: <br>
              </td>
              <td><input id=newPasswordRepeat name="newPasswordRepeat" type="password" required></td>
            </tr>
            <tr>
              <td style="text-align: right;">Full Name: <br>
              </td>
              <td><input type=text name="realName" required><br>
              </td>
            </tr>
            <tr>
              <td style="text-align: right;">Email: <br>
              </td>
              <td><input type=text name="email" required><br>
              </td>
            </tr>
<tr>
              <td style="text-align: center;" colspan="2"><input value="Create Account" type="submit"><input value="Reset" type="reset"></td>
            </tr>
          </tbody>
        </table>
      </form>
      </center>

<!-- Extra code removed for size -->
<script> $("#username").change( function newUser() { $.ajax({ type: "post", url: "userLookup.php", dataType: "json", data: { "username": $("#username").val() }, success: function(data,status) { if (data['exists'] == "true") { $("#checkUsername").html("<br>Username is already taken."); $("#checkUsername").css("color","red"); $("#username").css("background-color","LightCoral"); $("#username").focus(); } else if (document.getElementById("username").value.length < 5) { $("#checkUsername").html("<br>Username is too short."); $("#checkUsername").css("color","red"); $("#username").css("background-color","LightCoral"); $("#username").focus(); } else { $("#checkUsername").html(""); $("#username").css("background-color","White"); } }, }); }); $("#newPassword").change( function newPass() { if (document.getElementById("newPassword").value.length < 7) { $("#checkPassword").html("<br>Password is too short."); $("#checkPassword").css("color","red"); $("#newPassword").css("background-color","LightCoral"); $("#newPassword").focus(); } else { $("#checkPassword").html(""); $("#newPassword").css("background-color","White"); } }); $("#newPasswordRepeat").change( function newPassRepeat() { if (document.getElementById("newPasswordRepeat").value.length < 7) { $("#checkPassword").html("<br>Password is still too short."); $("#checkPassword").css("color","red"); $("#newPasswordRepeat").css("background-color","LightCoral"); $("#newPassword").focus(); } else if (document.getElementById("newPassword").value != document.getElementById("newPasswordRepeat").value) { $("#checkPassword").html("<br>Passwords do not match"); $("#checkPassword").css("color","red"); $("#newPassword").css("background-color","LightCoral"); $("#newPasswordRepeat").css("background-color","LightCoral"); $("#newPasswordRepeat").focus(); } else { $("#checkPassword").html(""); $("#newPassword").css("background-color","White"); $("#newPasswordRepeat").css("background-color","White"); } }); </script> </body> </html>