Thursday, November 19, 2015

Classes and objects 2

Here is the Term class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TermDictionary
{
    public class Term
    {
        /*
        this class stores a term and its
        definition
        */
        private string word;
        private string definition;

        public string Word
        {
            get
            {
                return word;
            }

            set
            {
                word = value;
            }
        }

        public string Definition
        {
            get
            {
                return definition;
            }

            set
            {
                definition = value;
            }
        }//end property

        public override string ToString()
        {
            string termDef = Word + "--" + Definition;
            return termDef;
        }

    }//end class

    public class Class1
    {
    }
}//end namespace


Here is the TDictionary class that stores the terms

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TermDictionary
{
    public class TDictionary
    {
        /*
        this class stores Terms in a list
        and contains methods for Adding
        terms to the list
        and for searching the list for a particular
        term
        */
        private List<Term> terms;

        public TDictionary()
        {
            terms = new List<Term>();
        }

        public void AddTerm(Term t)
        {
            terms.Add(t);
        }

        public string Search(string word)
        {
            string def=null;
            foreach(Term t in terms)
            {
                if(t.Word.Equals(word))
                {
                    def = t.Definition;
                    break;
                }
            }
            if (def == null)
            {
                def = "definition not found";
            }
            return def;

        }


    }
}

Here is the display class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TermDictionary
{
    public class Display
    {
        /*
        gets the input to build the dictionary
        and allows the user to enter words to search for
        */
        TDictionary dictionary;

        public Display()
        {
            dictionary = new TDictionary();
            GetTerms();
            SearchDictionary();
        }

        private void GetTerms()
        {
            string done = "yes";
            while (done == "yes")
            {
                Term t = new Term();
                Console.WriteLine("add a word");
                t.Word = Console.ReadLine();
                Console.WriteLine("Add a definition");
                t.Definition = Console.ReadLine();
                dictionary.AddTerm(t);
                Console.WriteLine("Add another yes/no");
                done = Console.ReadLine();
            }

        }

        private void SearchDictionary()
        {
            Console.WriteLine
                ("Enter the word you want to search for");
            string word = Console.ReadLine();
            Console.WriteLine("The definition is {0}",
                dictionary.Search(word));

        }


    }
}

And here, finally, is the program class with Main()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TermDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            Display d = new Display();
            Console.ReadKey();
        }
    }
}

Tuesday, November 17, 2015

Objects part 1

Here is our Customer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectExample
{
    public class Customer
    {
        //private fields--a class level variable
        //the describes elements of the class
        private string name;
        private string phone;
        private string email;
        private int rewardPoints;

        //default constructor, no arguments
        //initializes everything to lowest possible value
        public Customer()
        {
        }

        //overloaded constructor takes parameters
        //the compiler chooses which constructor to use
        //based on the number and types of arguments
        //but only one constructor is used at a time
        public Customer(string name, string phone,
            string email, int points)
        {
            Name = name;
            Phone = phone;
            Email = email;
            RewardPoints = points;
        }

        //public properties--properties make the
        //private fields accessible
        //set allows the user to change the value of
        //a field. Get allows the use to see the value
        //of a field
        public string Name
        {
            set { name = value; }
            get { return name; }
        }

        public string Phone
        {
            get { return phone; }
            set { phone = value; }
        }

        public string Email
        {
            get
            {
                return email;
            }

            set
            {
                email = value;
            }
        }

        public int RewardPoints
        {
            get
            {
                return rewardPoints;
            }

            set
            {
                rewardPoints = value;
            }
        }

        //public metods
        public void AddRewards(decimal amount)
        {
            RewardPoints += (int)(amount * .1M);
        }

        public void SubtractPoints(int points)
        {
            RewardPoints =- points;
        }


    }
}

Here is the Program class were we instantiate and use the Customer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {

            //this instantiates an object of the customer type
            //and then uses the propeties set to assign the values
            Customer customer = new Customer();
            customer.Name = "John Lennon";
            customer.Phone = "(212)555-3132";
            customer.Email = "john@thebeatles.org";
            customer.RewardPoints = 20;

            //this instantiates another object of the customer type
            //and uses the overloaded constructor to pass in the values
            Customer customer2 = new Customer("Ringo Starr",
                "(212)555-1234", "ringo@beatles.com", 10);

            //the output uses the get element of the properties
            Console.WriteLine(customer.Name + "\n " +
                customer.Phone + "\n"
                + customer.Email + "   "
                + customer.RewardPoints);

            customer.AddRewards(60.89M);
            Console.WriteLine("*****************");

            Console.WriteLine(customer2.Name + "\n " +
               customer2.Phone + "\n"
               + customer2.Email + "   "
               + customer2.RewardPoints);

            Console.ReadKey();
         
        }
    }
}

Thursday, November 12, 2015

Thursday, November 5, 2015

Methods 2: the Tip Calculator

Here is the code with comments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TipCalculator
{
    class Program
    {
        /*
            Get the amount of the bill
            Get the tip percent
            Get the tax
            calculate the tax
            calculte the tip
            Get the total
            Display the amount, the tax and the total

    */
    //since every method uses this I set it at Class Scope
        double amount=0;
        static void Main(string[] args)
        {
            //initialize the class
            Program p = new Program();
            //call get amount
            p.GetAmount();
            //call calculate total which calls all the 
            //other methods
            p.CalculateTotal();
            p.PauseIt();
           

        }

        void GetAmount()
        {
            //this method gets the amount 
            Console.WriteLine("Enter the Amount");
            amount = double.Parse(Console.ReadLine());
        }

        double GetTipPercent()
        {
            //in this method we create a simple menu
            //to give the user a choice of tip options
            double tipPercent = 0;
            int choice = 0;
            Console.WriteLine("Choose your tip Percent");
            Console.WriteLine("1 for 10 Percent");
            Console.WriteLine("2 for 15 Percent");
            Console.WriteLine("3 for 20 Percent");
            Console.WriteLine("4 for other");
            choice = int.Parse(Console.ReadLine());
            //the switch analyses their choice and assigns
            //the appropriate tip
            switch (choice)
            {
                case 1:
                    tipPercent = .1;
                    break;
                case 2:
                    tipPercent = .15;
                    break;
                case 3:
                    tipPercent = .2;
                    break;
                case 4: 
                    //when choosing other we give them the 
                    //opportunity to enter their own tip amount
                    Console.WriteLine("Enter your alternate tip amount");
                    tipPercent = double.Parse(Console.ReadLine());
                    //make sure it is in decimal form
                    if (tipPercent > 1)
                    {
                        tipPercent =tipPercent/ 100;
                    }
            
                    break;
                default:
                    Console.WriteLine("Not a valid choice.");
                    break;
            }
            return tipPercent;

        }

        double GetTaxPercent()
        {
            //let the user enter the tax percent
            Console.WriteLine("Enter The tax Percent");
            double taxPercent = double.Parse(Console.ReadLine());
            if (taxPercent > 1)
            {
                taxPercent /= 100;
            }

            return taxPercent;
        }

        double CalculateTax()
        {
            //calculate the tax --calls
            //get Tax percent
              double tax=amount * GetTaxPercent();
               return tax;
        }

        double CalculateTip()
        {
            //calculate tip calls GetTipPercent
            return amount * GetTipPercent();
        }

        void CalculateTotal()
        {
            //CalculateTip calls GetTipPercent
            //CalculateTax call GetTaxPercent.
            //This method also calls Display,
            //so this is the only method besides
            //GetAmount that we need to call
            //From Main
            double tip = CalculateTip();
            double tax = CalculateTax();
            double total = amount + tax + tip;
            //call display and pass the values
            Display(tip, tax, total);

        }

        void Display(double tip, double tax, double total)
        {
            //display the results
            Console.WriteLine("Your amount is {0}", amount);
            Console.WriteLine("the tip is {0}", tip);
            Console.WriteLine("Your tax is {0}", tax);
            Console.WriteLine("the Total is {0}", total);
        }

        void PauseIt()
        {
            //pause the console
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

    }
}

Here is the diagram we drew of how the methods execute

Wednesday, November 4, 2015

SQL Part 2

use CommunityAssist
--another join of three tables
--the as Aliases a column giving it a temporary
--name for the result table
--the as key word is actually optional
Select p.Personkey, PersonLastName as "Last Name", 
   PersonFirstname as "First Name",
   [Street],[Apartment],[State],[City],[Zip],
 [DonationDate],[DonationAmount]
 From Person  p
 inner join PersonAddress pa
 on p.PersonKey=pa.PersonKey
 inner join donation d
 on p.PersonKey=d.PersonKey
 where DonationAmount > 1000
 order by DonationAmount desc

 --a cross join matches every value in the first table
 --to every value in the second table
 Select PersonLastName, DonationAmount
 From Person
 cross Join Donation

 --getdate is a function that returns the current date and time
 select GetDate() as Today

 Select * from Donation

 --some date functions
 Select Distinct Year(DonationDate) as [Year] from Donation
 Select Distinct Month(DonationDate) as [Month] from Donation
 Select Distinct Day(DonationDate) as [Day] from Donation

 --DateDiff is a function that subtracts one date from
 --another. You have to specify the unit, the one below
 --specifies days, yy is years, mm is month
 Select DonationDate, DonationConfirmDate, 
 DateDiff(dd,DonationDate, DonationConfirmDate) 
 as "Time to Confirmation"
 From Donation

 --these are the basic aggregate functions
 Select Sum(DonationAmount)From Donation
 Select Avg(DonationAmount)From Donation
 Select Count(DonationAmount)From Donation
 Select Max(DonationAmount)From Donation
 Select Min(DonationAmount)From Donation

 --any column that is not included in the aggregate function
 --in this case sum must be include in a group by statment
 --the group by prioritizes the grouping from left to right
 Select Year(DonationDate) as [year],
  Month(DonationDate) as [Month],
  Sum(donationAmount) as total
 From Donation
 group by Year(DonationDate), Month(DonationDate)

  Select Year(DonationDate) as [year],
  Month(DonationDate) as [Month],
  Avg(donationAmount) as Average
 From Donation
 group by Year(DonationDate), Month(DonationDate)

 --the having clause is like the where clause
 --but is used when the criteria includes
 --an aggregate function, in this case count
 Select Month(DonationDate) as [Month],
  Day(DonationDate) as [Day], 
  count(*) as [Count]
  From donation
  group by Month(DonationDate), Day(DonationDate)
  Having Count(DonationAmount) > 2

  --insert a new person and then a new donation
  Insert into Person(PersonLastName, PersonFirstName)
  values('Bird','Larry')
  --the ident_current function returns the last autonumber
  --created in the table listed--it only works with autonumbers
  --(identities)
  Insert into Donation([DonationDate],[DonationAmount],[PersonKey])
  Values(GetDate(), 5000.00,ident_Current('Person'))

  Select * from Person

  Select * From Donation

  --update changes existing data
  --it is crucial to have a where clause
  Update Person
  set PersonFirstname = 'Jason'
  where PersonKey=1

  --transition manually creates a transistion
  --this allows you the possiblity of a undo (Rollback)
  Begin tran

  update Person
  Set PersonLastName='Smith'

  --undo the above transaction
  rollback tran
  --or write it
  commit tran

  --won't work because person 3 has related records 
  --in other tables
  Delete from Person where personkey=3

  Begin tran

  --this however will delete eveything in donation
  Delete from Donation




Tuesday, November 3, 2015

Methods 1

Here is the code we did in class for Methods.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace methodsexample
{
    class Program
    {

        //this is a class level variable
        //a variable has the "scope" of the block
        //it is declared in--the class
        //That means age can be seen and accessed
        //by any method in the class
        int age = 0;
        static void Main(string[] args)
        {
            //because Main is static it is loaded into memory
            //immediately, but the rest of the class is not
            //this line loads the rest of the class into memory
            Program p = new Program();
            //this calls the method "Hello." To Call a method just
            //name it and pass any parameters
            //p is our variable standing for the class Program
            //p.Hello() means the method belongs to the Program class
            p.Hello();
            //call Pauseit
            p.PauseIt();
           
        }

        //void means it doesn't return anything
        //it just does its stuff and returns
        //to where it was called
        void Hello()
        {
            Console.WriteLine("Hello");
            //call the method GetName()
            GetName();
        }

        void GetName()
        {

            Console.WriteLine("What is your name?");
            string person=Console.ReadLine();
            //call the method getAge() and pass it the string parameter 
            //person
            GetAge(person);
        }

        //this method takes an argument or Parameter 
        //of the type string
        void GetAge(string nom)
        {
            Console.WriteLine("What is your age?");
            //age has class scope. It is important to not
            //re-declare it here by saying "int age"
            //if you do C# gives the local variable precidence
            //and the class level age will not get a value
            age = int.Parse(Console.ReadLine());
            //calls the Method HowIsItGoing() and passes
            //the parameter nom
            HowIsItGoing(nom);
        }

        //This method returns a value of the type int
        //Any method that returns something other than void
        //must have a return statment that returns
        //a value of the kind indicated
        int GetBirthYear()
        {
            int years = 0;
            //use the built in DateTime class to get the year
            int currentYear = DateTime.Now.Year;
            //subtract the age from the current year
            years = currentYear - age;
            //return the resulting value
            return years;

        }


        void HowIsItGoing(string name)
        {
            Console.WriteLine
                ("You are {0} years old. How's it going, {1}?",age, name);
            //this calls the GetBirthYear() function and store the value
            //it returns in the variable birthYear
            //if you don't assign the returned value to a variable
            //it just goes away
            int birthYear = GetBirthYear();
            Console.WriteLine("you were born in {0}", birthYear);
        }


        void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }


    }
}

Monday, November 2, 2015

SQL part 1

Here is the SQL we did in class so far

--this changes the context to the database communityAssist
use CommunityAssist;

--a select statement that choose fields
SELECT 
Personlastname, 
PersonfirstName, 
PersonUserName
FROM Person;

--the astric * is a wild card saying return all columns
--order by sorts, desc sorts in reverse
Select * from Person
order by PersonLastName desc, PersonFirstname desc;

--the where clause limits what "rows" are returned
Select * From Person
Where PersonLastName = 'Baker';

Select * From Person
Where PersonLastName Like '%B%';

Select * from PersonAddress;

Select * from PersonAddress
where Apartment is not null

Select * From ServiceGrant
Where GrantAllocation > 400

Select * From ServiceGrant
where GrantDate between '2013-08-09' and '2013-08-19'

--inner joins join data from two or more related tables
Select PersonLastName, PersonFirstname,
GrantDate, GrantAmount, ServiceName, GrantNeedExplanation
From Person
inner join ServiceGrant
on Person.PersonKey=ServiceGrant.PersonKey
inner Join CommunityService
on CommunityService.ServiceKey = ServiceGrant.ServiceKey
Where PersonLastName='Anderson'