Saturday, March 15, 2014

MVC Controller to Show Donors and Emails

Here is the controller I created that shows the donors names and emails. This assumes that you have added the ADO Data Entity to model. It, oddly, also required me to create a new donor class to store the results of the query. It was the only way it would pass the results to the View

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;


namespace CommunityAssistMVCProject.Models
{
    public class DonorController : Controller
    {
        //
        // GET: /Donor/

        Donor d;
        CommunityAssistEntities cae = new CommunityAssistEntities();

             
        public ActionResult Index()
        {
            var don = (from p in cae.Donations
                      orderby p.Person.PersonLastName
                      where p.PersonKey == p.Person.PersonKey
                      select new { p.Person.PersonLastName, p.Person.PersonFirstName, p.Person.PersonUsername }).Distinct();

            List<Donor> donors = new List<Donor>();

            foreach (var x in don)
            {
                d = new Donor();
                d.LastName = x.PersonLastName;
                d.FirstName = x.PersonFirstName;
                d.Email = x.PersonUsername;
                donors.Add(d);
            }
                      
            return View(donors);
        }

    }

    public class Donor
    {
        public string PersonKey { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }

    }
}


Wednesday, March 5, 2014

SQL Part 1

Use TutorManagement
/* these are the basic
forms of the select statement
*/
Select * From Tutor
Select TutorLastName as [Last Name], TutorFirstName as [First Name], TutorEmail as Email
From Tutor

Select TutorLastName as [Last Name], TutorFirstName as [First Name], TutorEmail as Email
From Tutor
order by TutorLastName

Select TutorLastName as [Last Name], TutorFirstName as [First Name], TutorEmail as Email
From Tutor
order by TutorLastName desc

Select * From Tutor where tutorLastName='Brown'

--when searching for nulls use "is" or "is Not"
Select TutorLastName, TutorEmail from Tutor Where TutorEmail is not null

Select * from student where studentAge > 30
Select * from student where studentAge < 30
Select * from student where studentAge >= 30
Select * from student where studentAge <= 30

Select * From Student where StudentEmail Like '%hotmail%' or StudentEmail Like '%gmail%'

Select * from Session
Select Year(SessionDateKey) as [Year] From Session
Select Month(SessionDateKey) as [Month] From Session
Select Day(SessionDateKey) as [Day] from Session

Select cast(SessionTimeKey as Nvarchar(8)) from Session

Select DatePart(hour, SessiontimeKey) as [hour] from Session
Select DatePart(minute, SessionTimeKey) as [Minute] from Session

Select datediff(dd,GetDate(), '3/26/2014')
Select GetDate()
Select dateAdd(dd, 40, GetDate())

Select * From Student
Select Count(StudentKey) From Student
Select Count(StudentAge) From Student
Select Avg(StudentAge) From Student
Select max(StudentAge) From Student
Select Min (StudentAge) from Student
Select Sum(StudentAge) From Student

Admin commands and xml

Admin

--authentication
--Authorization

Use Master

Create Login EmployeeLogin with password='P@ssw0rd1', default_database=communityAssist

Use CommunityAssist

Create user EmployeeUser for Login EmployeeLogin

Create role EmployeeRole

Grant Select, Update on ServiceGrant to EmployeeRole
Grant Insert, Select, Update on GrantReview to EmployeeRole
Grant select on person to Employeerole

exec sp_addrolemember 'EmployeeRole', 'EmployeeUser'

XML

/* way to transfer and carry data
an element <element> </element> <element/>
unicode
nested properly
attributes 
root element   -- namespaces

<memo xmlns="http://spconger.com/memo">

Schema: xsd:
xslt */

use CommunityAssist

Select PersonLastname, PersonfirstName, 
PersonUserName from Person for xml raw('person'), elements, root('people')

Select PersonlastName, PersonfirstName, 
EmployeeHireDate, EmployeeStatus, EmployeeMonthlySalary
From Person 
inner join Employee 
on person.PersonKey=employee.PersonKey
for xml auto, elements, root('Employees')

Select * From GrantReview

Create xml Schema Collection meetingSchema
As 
'<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.communityassist.com/meetingnotes" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="meetingnotes">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="head">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="date" type="xs:string" />
              <xs:element name="topic" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="body">
          <xs:complexType>
            <xs:sequence>
              <xs:element maxOccurs="unbounded" name="p" type="xs:string" />
              <xs:element name="actions">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element maxOccurs="unbounded" name="item">
                      <xs:complexType>
                        <xs:attribute name="name" type="xs:string" use="required" />
                        <xs:attribute name="due" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>'


Create table Meeting
(
 MeetingKey int identity primary key,
 MeetingDate Date not null,
 MeetingNotes xml(meetingSchema)
)

Insert into Meeting (MeetingDate, MeetingNotes)
Values(GetDate(),
'<?xml version="1.0" encoding="utf-8"?>
<meetingnotes xmlns="http://www.communityassist.com/meetingnotes">
  <head>
    <date>3/5/2014</date>
    <topic>Xml</topic>
  </head>
  <body>
    <para>
     Xml is very useful. Very simple in concept. 
    </para>
    <para>
      But it can get complicated in practice
    </para>
    <actions>
      <item name="Create Schema" due="3/5/2014"/>
      <item name="Query" due="3/5/2014"/>
    </actions>
  </body>
</meetingnotes>')

select * from meeting

Select * from GrantReview

/*Select MeetingDate, MeetingTopic, 
meetingnotes.query('declare namespace mn="http://www.seattlecentral.edu/meetingnotes"; 
//mn:meetingnotes/mn:heading/mn:attending/mn:member') as Attending
From Meeting*/

Select GrantReviewDate, EmployeeKey, GrantReviewNote.query
('declare namespace rv="http://www.communityassist.org/reviewnotes"; //rv:reviewnote/rv:comment') 
From GrantReview
Where GrantReviewDate='8/11/2013'

Monday, March 3, 2014

Trigger

Use CommunityAssist
Go
Create trigger tr_MaxGrant on ServiceGrant
instead of Insert
As
Declare @amount money
Declare @max money
Declare @ServiceKey int

Select @ServiceKey=serviceKey, @Amount=GrantAmount
From Inserted 
Select @max=ServiceMaximum from CommunityService
Where ServiceKey = @ServiceKey
If @Amount <= @Max
Begin
Insert into ServiceGrant(
GrantAmount, GrantDate, PersonKey, ServiceKey)
Select GrantAmount, GrantDate, PersonKey, ServiceKey
From Inserted
End
Else
Begin
if not exists
 (Select name from sys.tables where name ='Rejects')
 Begin
  Create Table Rejects
  (
   PersonKey int,
   ServiceKey int,
   GrantDate Datetime,
   GrantAmount money,
   ServiceMaximum money,
   GrantDiff money
  )
 End
Insert into Rejects (PersonKey, ServiceKey, GrantDate, GrantAmount, 
ServiceMaximum, GrantDiff)
Select PersonKey, ServiceKey, GrantDate, GrantAmount, @max, GrantAmount-@max
From inserted

End

Select * from ServiceGrant

Select * from CommunityService

Insert into ServiceGrant([GrantAmount],[PersonKey],[GrantDate],[ServiceKey])
Values (300.00, 4, GetDate(), 4)

Select * From ServiceGrant where Personkey =4

Select * from Rejects

Wednesday, February 26, 2014

Stored Procedures Winter 2014

--insert a new customer into automart
--insert into person
--insert into vehicle
--insert into RegisteredCustomer
--transaction --all the inserts should happen or none of them
--should check to make sure the customer doesn't already exist

Use Automart
Go
--this version just does the inserts raw
--it is possible to insert into one or more tables
--even though it errors in another
Create proc usp_AddNewCustomer
--parameters 
@LastName nvarchar(255), 
@FirstName nvarchar(255),
@LicenseNumber nvarchar(10), 
@VehicleMake nvarchar(255), 
@VehicleYear nchar(4), 
@Email nvarchar(255),
@CustomerPassword nvarchar(20)
As
Insert into Person(Lastname, FirstName)
Values(@lastName, @firstName)

Declare @Personkey int
set @PersonKey=ident_Current('Person')

Insert into Customer.vehicle 
(LicenseNumber, VehicleMake, VehicleYear, personKey)
Values(@LicenseNumber, @VehicleMake, @VehicleYear, @PersonKey)

Insert into Customer.RegisteredCustomer
(Email, CustomerPassword, PersonKey)
Values(@Email, @CustomerPassword, @PersonKey)

Go
--test1
exec usp_AddNewCustomer
@LastName ='Nelson', 
@FirstName ='Admiral',
@LicenseNumber='FTW100' , 
@VehicleMake='Prius', 
@VehicleYear='2014', 
@Email='admiral@gmail.com',
@CustomerPassword = 'password'

Select * From Person
Select * From Customer.Vehicle
Select * From Customer.RegisteredCustomer

--version two
--this version adds a transaction and a
--try catch
Go

Alter proc usp_AddNewCustomer
--parameters 
@LastName nvarchar(255), 
@FirstName nvarchar(255),
@LicenseNumber nvarchar(10), 
@VehicleMake nvarchar(255), 
@VehicleYear nchar(4), 
@Email nvarchar(255),
@CustomerPassword nvarchar(20)
As
Begin Tran
Begin Try
Insert into Person(Lastname, FirstName)
Values(@lastName, @firstName)

Declare @Personkey int
set @PersonKey=ident_Current('Person')

Insert into Customer.vehicle 
(LicenseNumber, VehicleMake, VehicleYear, personKey)
Values(@LicenseNumber, @VehicleMake, @VehicleYear, @PersonKey)

Insert into Customer.RegisteredCustomer
(Email, CustomerPassword, PersonKey)
Values(@Email, @CustomerPassword, @PersonKey)
Commit tran
End try
Begin Catch
Rollback tran
print 'The transaction failed'
print error_message() 
end catch
Go

--version 3
--this version checks to see if the customer exists
--and then if the vehicle exists
--if the customer exists and the vehicle does not exist, insert it
--otherwise just end
--if the customer does not exist insert the person, 
--vehicle and registered customer
Alter proc usp_AddNewCustomer
--parameters 
@LastName nvarchar(255), 
@FirstName nvarchar(255),
@LicenseNumber nvarchar(10), 
@VehicleMake nvarchar(255), 
@VehicleYear nchar(4), 
@Email nvarchar(255),
@CustomerPassword nvarchar(20)
As

If exists
 (Select p.PersonKey from Person p
 inner Join Customer.Vehicle v
 on p.personkey=v.personkey
 inner join Customer.RegisteredCustomer r
 on r.PersonKey=p.Personkey
 Where lastname=@lastName
 and firstname=@firstName
 and Email = @Email)

Begin
 Declare @pKey int
 Select @pkey=p.PersonKey from Person p
 inner Join Customer.Vehicle v
 on p.personkey=v.personkey
 inner join Customer.RegisteredCustomer r
 on r.PersonKey=p.Personkey
 Where lastname=@lastName
 and firstname=@firstName
 and Email = @Email
 if not exists
  (Select LicenseNumber, VehicleMake, VehicleYear
    from Customer.Vehicle
    Where personkey=@pKey
    and LicenseNumber=@licenseNumber
    and vehicleMake=@VehicleMake
    and VehicleYear=@VehicleYear)
  Begin
  Begin try
   Insert into Customer.vehicle(LicenseNumber,VehicleMake, VehicleYear, Personkey)
   Values (@LicenseNumber, @VehicleMake, @VehicleYear, @pKey)
   return
  End Try
  Begin Catch
  print 'The license plate already exists'
  return
  End Catch
  end
  Else
  Begin
  print 'Already in the database'
  return
  end
End
Begin Tran
Begin Try
Insert into Person(Lastname, FirstName)
Values(@lastName, @firstName)

Declare @Personkey int
set @PersonKey=ident_Current('Person')

Insert into Customer.vehicle 
(LicenseNumber, VehicleMake, VehicleYear, personKey)
Values(@LicenseNumber, @VehicleMake, @VehicleYear, @PersonKey)

Insert into Customer.RegisteredCustomer
(Email, CustomerPassword, PersonKey)
Values(@Email, @CustomerPassword, @PersonKey)
Commit tran
End try
Begin Catch
Rollback tran
print 'The transaction failed'
print error_message() 
end catch

Go
exec usp_AddNewCustomer
@LastName ='Brown', 
@FirstName ='Susan',
@LicenseNumber='WEB100' , 
@VehicleMake='Tesla', 
@VehicleYear='2013', 
@Email='sb@gmail.com',
@CustomerPassword = 'password'

Select * From Customer.Vehicle

--this is a stored procedure for updating customer
--information
--it has a problem if the customer has more than
--one vehicle. I will let you solve that
Go
Create proc usp_UpdateCustomer
@LastName nvarchar(255), 
@FirstName nvarchar(255),
@LicenseNumber nvarchar(10), 
@VehicleMake nvarchar(255), 
@VehicleYear nchar(4), 
@Email nvarchar(255),
@CustomerPassword nvarchar(20),
@Personkey int
As
Begin tran
Begin try
Update Person
set LastName=@LastName,
FirstName=@firstName
Where Personkey=@personkey

--count the vehicles see if you are
--updating an existing vehicle
--or adding something entirely new
Update Customer.Vehicle
Set LicenseNumber=@LicenseNumber,
VehicleMake=@VehicleMake,
VehicleYear=@vehicleYear
Where PersonKey = @Personkey
And @licenseNumber=@LicenseNumber

Update Customer.RegisteredCustomer
set Email=@Email,
CustomerPassword=@CustomerPassword
Where personKey=@PersonKey
Commit tran
End Try
Begin Catch
Rollback tran
print 'sorry'
end catch

go
exec usp_UpdateCustomer
@LastName ='Brown-Meyers', 
@FirstName ='Susan',
@LicenseNumber='WEB100' , 
@VehicleMake='Tesla', 
@VehicleYear='2013', 
@Email='brown_meyers@gmail.com',
@CustomerPassword = 'password',
@personkey=74

Select * From Person
Select * From Customer.Vehicle
Select * from Customer.RegisteredCustomer where personkey=74

Monday, February 24, 2014

First Stored Procedure Example

Variable

Here is the work (mess) we made to show how to use variables

Use Automart

--these are the functions and queries we ended with last week
Select VehicleServiceID, ServiceName, ServicePrice, DiscountPercent, 
dbo.fx_Percentages(ServicePrice, DiscountPercent) as [Discount Price],
dbo.fx_GetPercent(ServicePrice, TaxPercent) as Tax
From Customer.AutoService a
inner join Employee.VehicleServiceDetail vsd
on a.AutoServiceID=vsd.AutoServiceID
Where VehicleServiceID=3

Select VehicleServiceID, 
Sum(dbo.fx_Percentages(ServicePrice, DiscountPercent)) as SubTotal,
Sum(dbo.fx_GetPercent(ServicePrice, TaxPercent)) as Tax,
Sum(dbo.fx_Percentages(ServicePrice, DiscountPercent) + 
 dbo.fx_GetPercent(ServicePrice, TaxPercent)) as Total
From Customer.AutoService a
inner join Employee.VehicleServiceDetail vsd
on a.AutoServiceID=vsd.AutoServiceID
Where VehicleServiceID=3
Group by VehicleServiceID

--this breaks up the above and divides it into variables
--it is a bit of a mess and much more work than the other way
--but does show the use of variables

--declare the variables
Declare @Subtotal decimal(10,2)
Declare @Tax decimal(10,2)
Declare @Total decimal(10,2)

--get the subtotal
Select @Subtotal=Sum(dbo.fx_Percentages(ServicePrice, DiscountPercent))
From Employee.VehicleServiceDetail sd
Inner Join Customer.AutoService a
on sd.AutoServiceID=a.AutoServiceID
Where VehicleServiceID=3
group by VehicleServiceID

--get the tax amount
Select @Tax=Sum(dbo.fx_GetPercent(ServicePrice, TaxPercent))
From Employee.VehicleServiceDetail sd
Inner Join Customer.AutoService a
on sd.AutoServiceID=a.AutoServiceID
Where VehicleServiceID=3
Group by vehicleServiceID

--get total
print 'subtotal ' + Cast(@Subtotal as nvarchar)
print 'Tax ' + Cast(@Tax as nvarchar)
Select @Total=@subtotal + @Tax

Select VehicleServiceID, @Subtotal as SubTotal, @Tax as Tax, @total as Total
From Employee.VehicleServiceDetail
Where VehicleServiceID=3
Group by VehicleServiceID

Simple Stored Procedure

Here is our first, simple stored procedure

--here is a stored procedure that uses the functions
--and queries above and creates a parameter for the 
--VehicleServiceID. This gives it the flexibility
--so you can use it with any Vehicle's service
Go
Create proc usp_GetReceipt
@VehicleServiceID int
AS

Select VehicleServiceID, ServiceName, ServicePrice, DiscountPercent, 
dbo.fx_Percentages(ServicePrice, DiscountPercent) as [Discount Price],
dbo.fx_GetPercent(ServicePrice, TaxPercent) as Tax
From Customer.AutoService a
inner join Employee.VehicleServiceDetail vsd
on a.AutoServiceID=vsd.AutoServiceID
Where VehicleServiceID=@vehicleServiceID

Select VehicleServiceID, 
Sum(dbo.fx_Percentages(ServicePrice, DiscountPercent)) as SubTotal,
Sum(dbo.fx_GetPercent(ServicePrice, TaxPercent)) as Tax,
Sum(dbo.fx_Percentages(ServicePrice, DiscountPercent) + 
 dbo.fx_GetPercent(ServicePrice, TaxPercent)) as Total
From Customer.AutoService a
inner join Employee.VehicleServiceDetail vsd
on a.AutoServiceID=vsd.AutoServiceID
Where VehicleServiceID=@VehicleServiceID
Group by VehicleServiceID

Go
--this is not part of the stored procedure. 
--these are using the stored procedure
--two versions with the same result
Execute usp_GetReceipt 4
Exec usp_GetReceipt @VehicleServiceID=7

Thursday, February 20, 2014