Thursday, April 26, 2012

New Donor ASP Net

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>
       <p><asp:Label ID="Label1" runat="server" 
Text="Enter First Name"></asp:Label>
           <asp:TextBox ID="txtFirstName" 
runat="server"></asp:TextBox>
       </p> 
             <p><asp:Label ID="Label2" 
runat="server" Text="Enter Last Name"></asp:Label>
           <asp:TextBox ID="txtLastName" 
runat="server"></asp:TextBox><asp:RequiredFieldValidator
               ID="RequiredFieldValidator1" 
runat="server" ErrorMessage="Last Name is required" 
                     ControlToValidate="txtLastName" 
Display="None" ForeColor="Red"></asp:RequiredFieldValidator>
       </p> 
        <p><asp:Label ID="Label3" 
runat="server" Text="Enter Street"></asp:Label>
           <asp:TextBox ID="txtStreet" runat="server"></asp:TextBox>
       </p> 
        <p><asp:Label ID="Label4" 
runat="server" Text="Enter City"></asp:Label>
           <asp:TextBox ID="txtCity" 
runat="server"></asp:TextBox>
       </p> 
        <p><asp:Label ID="Label5" 
runat="server" Text="Enter State"></asp:Label>
           <asp:TextBox ID="txtState" 
runat="server"></asp:TextBox>
       </p> 
        <p><asp:Label ID="Label6" 
runat="server" Text="Enter Zip Code"></asp:Label>
           <asp:TextBox ID="txtZipCode" 
runat="server"></asp:TextBox>
            <asp:RegularExpressionValidator 
ID="RegularExpressionValidator1" runat="server" 
                ControlToValidate="txtZipCode" 
Display="None" ErrorMessage="invalid zip code" 
                ForeColor="Red" 
ValidationExpression="\d{5}(-\d{4})?">
</asp:RegularExpressionValidator>
       </p> 
        <p><asp:Label ID="Label7" 
runat="server" Text="Enter home Phone"></asp:Label>
           <asp:TextBox ID="txtHomePhone" 
runat="server"></asp:TextBox></p> 
            <p><asp:Label ID="Label8" 
runat="server" Text="Enter Email"></asp:Label>
           <asp:TextBox ID="txtEmail" 
runat="server"></asp:TextBox>
       </p> 
        <p><asp:Label ID="Label9" 
runat="server" Text="Enter DonationAmount"></asp:Label>
           <asp:TextBox ID="txtDonation" r
unat="server"></asp:TextBox>
            <asp:CompareValidator ID="CompareValidator1" 
runat="server" 
                ControlToValidate="txtDonation" 
ErrorMessage="Be sure to enter a numeric value" 
                Operator="DataTypeCheck" 
Type="Double"></asp:CompareValidator>
       </p> 
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            onclick="btnSubmit_Click" />
            <asp:Label ID="lblResult" runat="server" 
Text="Label"></asp:Label>
    </div>
    <asp:ValidationSummary ID="ValidationSummary1" 
runat="server" ForeColor="Red" />
    </form>
</body>
</html>


Default.aspx

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)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //this method writes all the values from the text field
        //to the Donor class
        //it is in a try catch to catch errors, though you
        //should try to prevent errors by validating fields
        try
        {
            Donor d = new Donor();
            d.FirstName = txtFirstName.Text;
            d.LastName = txtLastName.Text;
            d.Street = txtStreet.Text;
            d.City = txtCity.Text;
            d.State = txtState.Text;
            d.ZipCode = txtZipCode.Text;
            d.HomePhone = txtHomePhone.Text;
            d.Email = txtEmail.Text;
            d.DonationAmount = double.Parse(txtDonation.Text);

            DonationManager dm = new DonationManager(d);

            lblResult.Text = "Your donation has been Processed";

            //Exception exc = new Exception("This is a new Error");
           // throw exc;
        }
        catch (Exception ex)
        {
            //this puts the error in a session and
            //redirects us to the error page
            Session["err"] = ex;
            Response.Redirect("error.aspx");
        }
    }
}

Donor.cs,/p>

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

/// 
/// this class just stores all the values
/// related to the donor and donation
/// 
public class Donor
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    private string firstName;

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    private string street;

    public string Street
    {
        get { return street; }
        set { street = value; }
    }
    private string city;

    public string City
    {
        get { return city; }
        set { city = value; }
    }
    private string state;

    public string State
    {
        get { return state; }
        set {
            //if (state.Length > 2)
            //{
            //    Exception e = new Exception("Must use 2 letter abreviation");
            //    throw e;
            //}
            state = value; }
    }
    private string zipCode;

    public string ZipCode
    {
        get { return zipCode; }
        set { zipCode = value; }
    }
    private string homePhone;

    public string HomePhone
    {
        get { return homePhone; }
        set { homePhone = value; }
    }
    private string email;

    public string Email
    {
        get { return email; }
        set { email = value; }
    }
    private double donationAmount;

    public double DonationAmount
    {
        get { return donationAmount; }
        set { donationAmount = value; }
    }

 public Donor()
 {
  

 }
}

DonorManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// 
/// this is the complex class. It uses ADO to write the
/// donation information to several different database
/// tables
/// 
public class DonationManager
{
    //declare the connection and donor
    //at class scope
    SqlConnection connect;
    Donor donor;

 public DonationManager(Donor d)
 {
        //in the constructor instantiate the connection 
        //assign the donor to the local variable
        //and call the WriteDonor() method
        //the actual connection string is in the 
        //web.config file
        connect = 
            new SqlConnection(ConfigurationManager.ConnectionStrings
["CommunityAssistConnection"].ToString());
        donor = d;
        WriteDonor();
 }

    //Write first and last name to person
    //get the personkey
    //write the address information to PersonAddress
    //write phone number and email to personContact
    //need write donation to donation
    private void WriteDonor()
    {
        try
        {
            connect.Open();
            //connect.BeginTransaction(); not working
            //the following lines call the methods
            //that configure the sqlCommand for inserts 
            //into each table
            SqlCommand cmdPerson = WritePerson();
            SqlCommand cmdAddress = WriteAddress();
            SqlCommand cmdPhone = WriteHomePhone();
            SqlCommand cmdEmail = WriteEmail();
            SqlCommand cmdDonation = WriteDonation();
            //execute the commands
            cmdPerson.ExecuteNonQuery();
            cmdAddress.ExecuteNonQuery();
            cmdPhone.ExecuteNonQuery();
            cmdEmail.ExecuteNonQuery();
            cmdDonation.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            connect.Close();
        }
    }

    private SqlCommand WritePerson()
    {
        //define the sql string
         string sql="Insert into Person(Lastname, Firstname) Values(@Last, @First)";
        //define the command
         SqlCommand cmd = new SqlCommand(sql, connect);
        //provide values for the parameters using the values
        //in the donor class which was passed through the constructor
         cmd.Parameters.AddWithValue("@Last", donor.LastName);
         cmd.Parameters.AddWithValue("@First", donor.FirstName);

         return cmd;
    }

    //all the other commands behave as the first one
    private SqlCommand WriteAddress()
    {
        string sql = "Insert into PersonAddress(Street, City, State, Zip, PersonKey)"
                           + " Values(@street, @city, @state, @zip, Ident_Current('Person'))";

        SqlCommand cmd = new SqlCommand(sql, connect);
        cmd.Parameters.AddWithValue("@street", donor.Street);
        cmd.Parameters.AddWithValue("@city", donor.City);
        cmd.Parameters.AddWithValue("@state", donor.State);
        cmd.Parameters.AddWithValue("@zip", donor.ZipCode);

        return cmd;
    }

    private SqlCommand WriteHomePhone()
    {
        string sql = "Insert into PersonContact(ContactInfo, ContactTypeKey, PersonKey) "
        + " Values(@info, 1, Ident_Current('Person'))";
        SqlCommand cmd = new SqlCommand(sql, connect);
        cmd.Parameters.AddWithValue("@info", donor.HomePhone);
        
        return cmd;
    }

    private SqlCommand WriteEmail()
    {
        string sql = "Insert into PersonContact(ContactInfo, ContactTypeKey, PersonKey) "
       + " Values(@info, 6, Ident_Current('Person'))";
        SqlCommand cmd = new SqlCommand(sql, connect);
        cmd.Parameters.AddWithValue("@info", donor.Email);

        return cmd;
    }

    private SqlCommand WriteDonation()
    {
        string sql = "Insert into Donation(DonationDate, DonationAmount, PersonKey, EmployeeKey) "
       + " Values(GetDate(), @Amount, Ident_Current('Person'), null)";
        SqlCommand cmd = new SqlCommand(sql, connect);
        cmd.Parameters.AddWithValue("@Amount", donor.DonationAmount);

        return cmd;
    }
}

error.aspx

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

<!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>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>



error.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 error : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //check to see if the session exists
        if (Session["err"] != null)
        {
            //cast the session to the type Exception
            Exception ex = (Exception)Session["err"];
            //view the message
            Label1.Text = ex.Message;
        }
            
    }
}

No comments:

Post a Comment