Thursday, August 19, 2010

Monday, August 16, 2010

Data Analysis

This excercise should develop a simple analysis cube.

Before beginning we need to add the local service user to the AdventureworksDW Database. Open the security folder for AdventureworksDW and right click on Users.
Select New User. In the login dialog box click on the button by logins and find the local service login. Give the user a name. In the database roles click on the datareader role. Click ok.

Creating a cube


1. Open the Business Intellegence studio
2. Choose FILE /New Project
3. Choose an Analysis Service Project
4. In the Solution Explorer right click on Data Sources
5. Choose New Data Source
6. Next
7. Click the New ...




8. configure the connection



9. Next. Choose Use Service Account



10. Next/Finish
11. In the Solution Explorer Right click on the Data Source View Folder.
12. Choose a new data source view
13. Next
14 Add all the tables and click next



15. Next. Review the tables. Finish
16. In the Solution Explorer right click on Cubes and choose New Cube
16. Next
17. Choose "Use existing tables"
18. Next. Select "FactInternetSales" Next
19. Accept what's there.
20. Next, Next, Next
21. Finish.
22. Right click the cube and select process.
23. A dialog says the cube seems out of date etc, say yes
24. Click Run
25. If all goes well and the cube deploys click close and close again
26. Click Browser
27. Drag fields onto the cube as shown in the illustration below



28. Feel free to add or subtract other fields from the cube

Windows Form

Here is a picture of the window's form we created



Here is the code: form1.h

#pragma once


namespace CalculateTips {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///

public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}

protected:
///
/// Clean up any resources being used.
///

~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Panel^ panel1;
private: System::Windows::Forms::RadioButton^ radioButton4;
private: System::Windows::Forms::RadioButton^ radioButton3;
private: System::Windows::Forms::RadioButton^ radioButton2;
private: System::Windows::Forms::RadioButton^ radioButton1;
private: System::Windows::Forms::TextBox^ txtOther;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::TextBox^ txtMeal;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::TextBox^ txtTaxPercent;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Label^ lblTotal;

protected:

private:
///
/// Required designer variable.
///

System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

void InitializeComponent(void)
{
this->label1 = (gcnew System::Windows::Forms::Label());
this->panel1 = (gcnew System::Windows::Forms::Panel());
this->radioButton1 = (gcnew System::Windows::Forms::RadioButton());
this->radioButton2 = (gcnew System::Windows::Forms::RadioButton());
this->radioButton3 = (gcnew System::Windows::Forms::RadioButton());
this->radioButton4 = (gcnew System::Windows::Forms::RadioButton());
this->txtOther = (gcnew System::Windows::Forms::TextBox());
this->label2 = (gcnew System::Windows::Forms::Label());
this->txtMeal = (gcnew System::Windows::Forms::TextBox());
this->label3 = (gcnew System::Windows::Forms::Label());
this->txtTaxPercent = (gcnew System::Windows::Forms::TextBox());
this->button1 = (gcnew System::Windows::Forms::Button());
this->lblTotal = (gcnew System::Windows::Forms::Label());
this->panel1->SuspendLayout();
this->SuspendLayout();
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 24, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->label1->ForeColor = System::Drawing::Color::FromArgb(static_cast(static_cast(0)), static_cast(static_cast(0)),
static_cast(static_cast(192)));
this->label1->Location = System::Drawing::Point(13, 13);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(191, 37);
this->label1->TabIndex = 0;
this->label1->Text = L"Tip Calcutor";
//
// panel1
//
this->panel1->Controls->Add(this->txtOther);
this->panel1->Controls->Add(this->radioButton4);
this->panel1->Controls->Add(this->radioButton3);
this->panel1->Controls->Add(this->radioButton2);
this->panel1->Controls->Add(this->radioButton1);
this->panel1->Location = System::Drawing::Point(20, 70);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(228, 151);
this->panel1->TabIndex = 1;
//
// radioButton1
//
this->radioButton1->AutoSize = true;
this->radioButton1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->radioButton1->Location = System::Drawing::Point(24, 21);
this->radioButton1->Name = L"radioButton1";
this->radioButton1->Size = System::Drawing::Size(118, 28);
this->radioButton1->TabIndex = 0;
this->radioButton1->TabStop = true;
this->radioButton1->Text = L"10 Percent";
this->radioButton1->UseVisualStyleBackColor = true;
//
// radioButton2
//
this->radioButton2->AutoSize = true;
this->radioButton2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->radioButton2->Location = System::Drawing::Point(24, 45);
this->radioButton2->Name = L"radioButton2";
this->radioButton2->Size = System::Drawing::Size(118, 28);
this->radioButton2->TabIndex = 1;
this->radioButton2->TabStop = true;
this->radioButton2->Text = L"15 Percent";
this->radioButton2->UseVisualStyleBackColor = true;
//
// radioButton3
//
this->radioButton3->AutoSize = true;
this->radioButton3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->radioButton3->Location = System::Drawing::Point(24, 68);
this->radioButton3->Name = L"radioButton3";
this->radioButton3->Size = System::Drawing::Size(118, 28);
this->radioButton3->TabIndex = 2;
this->radioButton3->TabStop = true;
this->radioButton3->Text = L"20 Percent";
this->radioButton3->UseVisualStyleBackColor = true;
//
// radioButton4
//
this->radioButton4->AutoSize = true;
this->radioButton4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->radioButton4->Location = System::Drawing::Point(24, 91);
this->radioButton4->Name = L"radioButton4";
this->radioButton4->Size = System::Drawing::Size(75, 28);
this->radioButton4->TabIndex = 3;
this->radioButton4->TabStop = true;
this->radioButton4->Text = L"Other";
this->radioButton4->UseVisualStyleBackColor = true;
//
// txtOther
//
this->txtOther->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->txtOther->Location = System::Drawing::Point(105, 98);
this->txtOther->Name = L"txtOther";
this->txtOther->Size = System::Drawing::Size(100, 29);
this->txtOther->TabIndex = 4;
//
// label2
//
this->label2->AutoSize = true;
this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->label2->Location = System::Drawing::Point(20, 248);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(172, 24);
this->label2->TabIndex = 2;
this->label2->Text = L"Enter Meal Amount";
//
// txtMeal
//
this->txtMeal->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->txtMeal->Location = System::Drawing::Point(198, 252);
this->txtMeal->Name = L"txtMeal";
this->txtMeal->Size = System::Drawing::Size(100, 29);
this->txtMeal->TabIndex = 3;
//
// label3
//
this->label3->AutoSize = true;
this->label3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->label3->Location = System::Drawing::Point(20, 294);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(112, 24);
this->label3->TabIndex = 4;
this->label3->Text = L"Tax Percent";
//
// txtTaxPercent
//
this->txtTaxPercent->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->txtTaxPercent->Location = System::Drawing::Point(198, 294);
this->txtTaxPercent->Name = L"txtTaxPercent";
this->txtTaxPercent->Size = System::Drawing::Size(100, 29);
this->txtTaxPercent->TabIndex = 5;
//
// button1
//
this->button1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->button1->Location = System::Drawing::Point(24, 352);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(108, 37);
this->button1->TabIndex = 6;
this->button1->Text = L"Calculate";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// lblTotal
//
this->lblTotal->AutoSize = true;
this->lblTotal->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->lblTotal->Location = System::Drawing::Point(194, 352);
this->lblTotal->Name = L"lblTotal";
this->lblTotal->Size = System::Drawing::Size(0, 24);
this->lblTotal->TabIndex = 7;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::Color::FromArgb(static_cast(static_cast(128)), static_cast(static_cast(128)),
static_cast(static_cast(255)));
this->ClientSize = System::Drawing::Size(551, 462);
this->Controls->Add(this->lblTotal);
this->Controls->Add(this->button1);
this->Controls->Add(this->txtTaxPercent);
this->Controls->Add(this->label3);
this->Controls->Add(this->txtMeal);
this->Controls->Add(this->label2);
this->Controls->Add(this->panel1);
this->Controls->Add(this->label1);
this->Name = L"Form1";
this->Text = L"Form1";
this->panel1->ResumeLayout(false);
this->panel1->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
double amount = double::Parse(txtMeal->Text);

double taxPercent=0;
if (double::Parse(txtTaxPercent->Text) > 1)
{
taxPercent=double::Parse(txtTaxPercent->Text)/100;
}
else
{
taxPercent=double::Parse(txtTaxPercent->Text);
}

double tipAmount=0;
double percent=0;

if (radioButton1->Checked)
{
percent=.1;
}
else if (radioButton2->Checked)
{
percent=.15;
}
else if (radioButton3->Checked)
{
percent =.2;
} //end of if
else
{
if (double::Parse(txtOther->Text)>1)
{
percent=double::Parse(txtOther->Text)/100;
}
else
{
percent=double::Parse(txtOther->Text);
} //end of embedded if


}//end of else
tipAmount=amount * percent;
double taxAmount=amount * taxPercent;
double total =amount + taxAmount + tipAmount;

lblTotal->Text="At " + percent.ToString() + " your tip will be "
+ tipAmount.ToString("$ #,##0.00") + "\n"
+ "Your tax is " + taxAmount.ToString("$ #,##0.00") + "\n"
+ "Your Total is " + total.ToString("$ #,##0.00");




}
};
}

Thursday, August 12, 2010

Link to SQL Server Agent Presentation

Here is the link to the SQL Server Agent Presentaion

http://www.4emphasis.com/demo/

Creating a Simple SSIS (SQL Server Integration Services) Project

this service imports a text file, donor.txt and imports the first and last names into the person table. Before you start make sure you save the Donot.txt file as unicode.
1. Start Visual Studio
2. Go to File, New Project, and then choose Integration Service Project.
3. Cancel the wizard.
4. In the Control Flow Designer window add a dataflow task object from the toolbox
5. Double click it, or click on the Data Flow Tab
6. Add a Flat file Data Source object from the tool box
7. Double click it to get the properties
8. Give the Flat file manager a name, "DonorFlatFileManager" or something
9. Browse to the file Donor.txt
10. Click the check box for first row contains headings
11. Check the preview to make sure you got all the data
12. Now add a new OLEDB Destination object from the toolbox
13. Click on the Flat File Source and connect the green arrow to the destination box
14. Double Click the OLEDB destination object to get the properties
15. Make a new connection manager. It will pop up a dailog
16. Set the server as Localhost, the database as CommunityAssist.
!7. From the drop down list for tables choose Person.
18. Check the column Mappings to make sure that they are correct
19. Run the pagage by going to the menu Debug and choosing run
20. The objects should turn green for success, red for failure
21. If they are red, look at the error messages and correct
22 If they are green, check the database to make sure that it added the records to Person

Wednesday, August 11, 2010

Inheritance

Employee.h

#pragma once
#include
using std::string;
class Employee
{
public:
Employee(void);
~Employee(void);
void SetName(string);
string GetName();
void SetHireDate(string);
string GetHireDate();
virtual double CalculateWeeklyPay();
private:
string name;
string hireDate;
};

Employee.cpp

#include "Employee.h"

Employee::Employee(void)
{
}

Employee::~Employee(void)
{
}

void Employee::SetName(string employeeName)
{
name=employeeName;
}

string Employee::GetName()
{
return name;
}

void Employee::SetHireDate(string date)
{
hireDate=date;
}

string Employee::GetHireDate()
{
return hireDate;
}

double Employee::CalculateWeeklyPay()
{
return 0;
}


HourlyEmployee.h

#pragma once
#include "employee.h"

class HourlyEmployee :
public Employee
{
public:
HourlyEmployee(void);
~HourlyEmployee(void);
void SetRate(double);
double GetRate();
void SetHours(double);
double GetHours();
double CalculateWeeklyPay();

private:
double rate;
double hours;
};

HourlyEmployee.cpp

#include "HourlyEmployee.h"

HourlyEmployee::HourlyEmployee(void)
{
}

HourlyEmployee::~HourlyEmployee(void)
{
}

void HourlyEmployee::SetRate(double payRate)
{
rate=payRate;
}

double HourlyEmployee::GetRate()
{
return rate;
}

void HourlyEmployee::SetHours(double hrs)
{
hours=hrs;
}

double HourlyEmployee::GetHours()
{
return hours;
}

double HourlyEmployee::CalculateWeeklyPay()
{
return hours * rate;
}

SalaryEmployee.h

#pragma once
#include "employee.h"

class SalaryEmployee :
public Employee
{
public:
SalaryEmployee(void);
~SalaryEmployee(void);
void SetSalary(double);
double GetSalary();
double CalculateWeeklyPay();
private:
double salary;

};

SalaryEmployee.cpp

#include "SalaryEmployee.h"

SalaryEmployee::SalaryEmployee(void)
{
}

SalaryEmployee::~SalaryEmployee(void)
{
}

double SalaryEmployee::GetSalary()
{
return salary;
}

void SalaryEmployee::SetSalary(double sal)
{
salary=sal;
}

double SalaryEmployee::CalculateWeeklyPay()
{
return salary/52;
}

Program.cpp

#include "HourlyEmployee.h"
#include "SalaryEmployee.h"
#include <iostream>
using namespace std;

int main()
{
HourlyEmployee he;
he.SetName("Bill Gates");
he.SetHireDate("1972");
he.SetRate(.01);
he.SetHours(80);


HourlyEmployee he2;
he2.SetName("Balmer");
he2.SetHireDate("1972");
he2.SetRate(.02);
he2.SetHours(80);


cout << he.GetName() << endl;
cout << he.GetHireDate() << endl;
cout<< he.GetRate() << endl;
cout << he.CalculateWeeklyPay();
cout << endl;

cout << he2.GetName() << endl;
cout << he2.GetHireDate() << endl;
cout<< he2.GetRate() << endl;
cout << he2.CalculateWeeklyPay();
cout << endl;

SalaryEmployee se;
se.SetName("George");
se.SetHireDate("1/1/2000");
se.SetSalary(80000.00);

cout << se.GetName() << endl;
cout << se.GetHireDate() << endl;
cout << se.CalculateWeeklyPay();
cout << endl;


cin.get();
cin.get();


}

Tuesday, August 10, 2010

Linq for DataRecovery Presentation

Presentation

DemoCode

LINQ with Stored Procedure ASP

Here is the code for the asp web page we did using linq. Remember you have to add the Link to SQL. Drag the person and donation tables onto the form and the usp_Mydonations onto the method part of the window.

here is 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>
<:asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<:/asp:DropDownList>
<:asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow"
BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"
GridLines="None">
<:FooterStyle BackColor="Tan" />
<:PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<:SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<:HeaderStyle BackColor="Tan" Font-Bold="True" />
<:AlternatingRowStyle BackColor="PaleGoldenrod" />
<:/asp:GridView>
<:/div>
<:/form>
<:/body>
<:/html>

Here is default.aspx.cs

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

public partial class _Default : System.Web.UI.Page
{
DataClassesDataContext dc = new DataClassesDataContext();

protected void Page_Load(object sender, EventArgs e)
{
var donors = (from d in dc.Donations
select new {d.Person.LastName, d.PersonKey }).Distinct();

if (!IsPostBack)
{

DropDownList1.DataSource = donors.ToList();
DropDownList1.DataTextField = "Lastname";
DropDownList1.DataValueField = "PersonKey";
DropDownList1.DataBind();

}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Response.Write(DropDownList1.SelectedValue.ToString());
//Response.Write(DropDownList1.SelectedItem.ToString());
GridView1.DataSource=dc.usp_myDonations(int.Parse(DropDownList1.SelectedValue.ToString())).ToList();
GridView1.DataBind();

}
}

Report Services

Here is the script I generated in class for creating a new report:

In the programs menu right click on Sql Server Business Intellegence services and start as adminstrator
Got to File/New project
Choose Business Intellegence Services
Report Service Project wizard
Name the project GrantsPerService, Next
In the Connection string dialog choose edit edit
type localhost for server/communityassist for database/windows authenication
Enter this SQL into the Query window:
Select ServiceName, MONTH(GrantDate) as [Month],
SUM(GrantAmount) as Total
From [Service] s
Inner join ServiceGrant sg
On s.ServiceKey=sg.ServiceKey
Group by ServiceName, Month(GrantDate)

Choose matrix for the report layout

Use month for column
servicename for row
total for detail

Choose you color

drag on pie chart from toolbox
service name for category
Total for data

Choose/build Deploy report

To view the report right click on the IE icon
Right click on Run as administrator
Type in the URL http://Itstudent-pc/reports
at home substitute your computer name for itcstudent-pc

Monday, August 9, 2010

Operator Overloading: Block Example

Here is Block.h

#pragma once
/***********************
this class lets you set the height and width
of a 2 dimensional block and then defines
four operators that can work with those blocks
**********************************/
class Block
{
public:
Block(void);
Block (int x, int y); //overloaded constructor
~Block(void);
//sets and gets for the private members
void SetX(int);
int GetX();
void SetY(int);
int GetY();
int CalculateArea();
//declare operator overload methods
//these tell the compiler how to apply
//these operators to the Block Class
Block operator+(const Block &b2);
Block operator-(const Block &b2);
bool operator==(const Block &b2);
bool operator!=(const Block &b2);

private:
int x,y;
};

Here is Block.cpp

#include "Block.h"

Block::Block(void)
{
//set default constructor
SetX(0);
SetY(0);
}

Block::~Block(void)
{
}

//overloaded constructor
Block::Block(int x, int y)
{
SetX(x);
SetY(y);
}

//Create sets and gets
//for the variables
void Block::SetX(int x)
{
//the this pointer points the the
//member of the current instance
this->x=x;
}

int Block::GetX()
{
return x;
}

void Block::SetY(int y)
{
this->y=y;
}

int Block::GetY()
{
return y;
}

//calculate the area
int Block::CalculateArea()
{
return GetX() * GetY();
}

//define what it means to add two blocks
Block Block::operator +(const Block &b2)
{
Block temp;
temp.SetX(this->x+b2.x);
temp.SetY(this->y+b2.y);
return temp;
}

//Define what subtraction means
Block Block::operator -(const Block &b2)
{
Block temp;
temp.SetX(this->x-b2.x);
temp.SetY(this->y-b2.y);
return temp;
}

//define what makes two blacks equal
bool Block::operator ==(const Block &b2)
{
bool isEqual =false;
if (this->x==b2.x && this->y==b2.y)
{
isEqual=true;
}
return isEqual;
}

//define not equal
bool Block::operator !=(const Block &b2)
{
bool isEqual =false;
if (this->x!=b2.x || this->y!=b2.y)
{
isEqual=true;
}
return isEqual;
}

Here is program.cpp

#include <iostream>
#include "Block.h"
using namespace std;

void PauseIt()
{
cout << "enter any character and press Enter to exit"
<<endl;
char c;
cin >> c;
}
int main()
{
cout << "Enter a block height: ";
int h, w;
cin>> h;
cout<<endl;
cout << "Enter a block width: ";
cin >> w;
cout << endl;
Block b1(h,w);
cout << "Enter a block height: ";
cin>> h;
cout<<endl;
cout << "Enter a block width: ";
cin >> w;
cout << endl;
Block b2(h,w);

cout << "The area of Block 1 is " << b1.CalculateArea()
<< " the area of Block 2 is " << b2.CalculateArea()
<< endl;

Block b3 = b1 + b2;

cout << "The area of block three (b1 + b2) is "
<< b3.CalculateArea() << endl;

Block b4= b1 - b2;

cout << "The area of Block 4 (b1-b2) "
<< b4.CalculateArea() << endl;

Block b5(5,5);
Block b6(6,5);

if (b5==b6)
cout << "block 5 and 6 are equal" << endl;
else
cout << "Block 5 and 6 are unequal" << endl;

PauseIt();

}

Friday, August 6, 2010

LINQ Insert Example

Here is the lINQ example I got it to work. It was fairly simple. We needed to Use the "InsertOnSubmit" method. Also to get the foreign key we just needed to point to the first person object. LINQ understands the relationships and gets the key for us.

Remember you have to make a connection to the database. You can use an existing one if you have it. Then you add a LINQ to SQL to the project and drag the tables from the connection in the Server Explorer onto the LINQ designer window.

Here is the XAML file. It may be somewhat different from what we did in class, because I recreated it at home:

<Window x:Class="ClientApForm.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="615" Width="536">
<Grid Height="563">
<Label Content="New Application" Height="41" HorizontalAlignment="Left" Margin="23,26,0,0" Name="label1" VerticalAlignment="Top" Width="200" FontSize="24" Foreground="#FF576B9A" />
<Label Content="Last Name" Height="28" HorizontalAlignment="Left" Margin="29,89,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="119,93,0,0" Name="txtLastName" VerticalAlignment="Top" Width="120" Background="BlanchedAlmond"/>
<Label Content="First Name" Height="28" HorizontalAlignment="Left" Margin="29,136,0,0" Name="label3" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,140,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="120" />
<Label Content="Street" Height="28" HorizontalAlignment="Left" Margin="29,178,0,0" Name="label4" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,182,0,0" Name="txtStreet" VerticalAlignment="Top" Width="194" />
<Label Content="City" Height="28" HorizontalAlignment="Left" Margin="29,221,0,0" Name="label5" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,225,0,0" Name="txtCity" VerticalAlignment="Top" Width="194" />
<Label Content="State" Height="28" HorizontalAlignment="Left" Margin="29,260,0,0" Name="label6" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,264,0,0" Name="txtState" VerticalAlignment="Top" Width="38" />
<Label Content="Zip Code" Height="28" HorizontalAlignment="Left" Margin="29,302,0,0" Name="label7" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,306,0,0" Name="txtZip" VerticalAlignment="Top" Width="70" />
<Label Content="home Phone" Height="28" HorizontalAlignment="Left" Margin="29,342,0,0" Name="label8" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,346,0,0" Name="txtHomePhone" VerticalAlignment="Top" Width="120" />
<Label Content="Email" Height="28" HorizontalAlignment="Left" Margin="29,384,0,0" Name="label9" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,388,0,0" Name="txtEmail" VerticalAlignment="Top" Width="237" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="119,436,0,0" Name="cboService" VerticalAlignment="Top" Width="120" />
<Label Content="Service" Height="28" HorizontalAlignment="Left" Margin="28,436,0,0" Name="label10" VerticalAlignment="Top" />
<Label Content="Request" Height="28" HorizontalAlignment="Left" Margin="29,481,0,0" Name="label11" VerticalAlignment="Top" />
<TextBox Background="BlanchedAlmond" Height="23" HorizontalAlignment="Left" Margin="119,485,0,0" Name="txtRequest" VerticalAlignment="Top" Width="84" />
<Button Content="Submit" Height="23" HorizontalAlignment="Left" Margin="31,528,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>

Now here is the C# code. I have commented it some:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ClientApForm
{
/// <summary>
/// This project uses LINQ to retrive the data from the database
/// and fill a combo box and then to insert data into the database
/// from an xaml form
/// Steve Conger, 8/6/2010
/// </summary>
public partial class MainWindow : Window
{
//I declare this at class level to give it
//class scope
//unlike on Thursday I used the default name
DataClasses1DataContext dc = new DataClasses1DataContext();

public MainWindow() //constructor
{
//this must run before anything else
//it creates the form
InitializeComponent();

FillCombo(); //call the fillCombo Method
}

private void FillCombo()
{
//this metho fills the cboService Box
//use the proxy classes create by link
//to get the serviceName and servicekey
//from the Service tale
var service = from s in dc.Services
select new { s.ServiceName, s.ServiceKey };

//assign the results to the combobox
//display the ServiceName
//but store the serviceKey
cboService.ItemsSource = service.ToList();
cboService.DisplayMemberPath = "ServiceName";
cboService.SelectedValuePath = "ServiceKey";
cboService.SelectedIndex = 0; //move to top of list
}

private void SubmitClient()
{
//this method insert into the various
//tables required to record a new client

//create a new person object
//assign the values from the textboxes
//to the properties of the person
Person p = new Person();
p.LastName = txtLastName.Text;
p.FirstName = txtFirstName.Text;

//pass the person object to the
//datacontext to hold it for
//insert when the submit is called
dc.Persons.InsertOnSubmit(p);


//Do the same for all the other
//tables required
PersonAddress pa = new PersonAddress();
pa.Street = txtStreet.Text;
pa.City = txtCity.Text;
pa.State = txtState.Text;
pa.Zip = txtZip.Text;
pa.Person = p; //get the personKey of the new Person

dc.PersonAddresses.InsertOnSubmit(pa);

PersonContact phone = new PersonContact();
phone.ContactInfo = txtHomePhone.Text;
phone.ContactTypeKey = 1;
phone.Person = p;

dc.PersonContacts.InsertOnSubmit(phone);

PersonContact email = new PersonContact();
email.ContactInfo = txtEmail.Text;
email.ContactTypeKey = 6;
email.Person = p;

dc.PersonContacts.InsertOnSubmit(email);

ServiceGrant sg = new ServiceGrant();
sg.EmployeeKey = 1;
sg.GrantDate = DateTime.Now;
sg.ServiceKey = int.Parse(cboService.SelectedValue.ToString());
sg.GrantAmount = decimal.Parse(txtRequest.Text);
sg.Person = p;

dc.ServiceGrants.InsertOnSubmit(sg);

//submit all the changes to the database

dc.SubmitChanges();

}

private void button1_Click(object sender, RoutedEventArgs e)
{
SubmitClient(); //call the submit client method
//show a message if success
MessageBox.Show("Your request has been submitted");
}

}
}

Wednesday, August 4, 2010

Operator Overloading: fraction class

Here is a fraction class that overloads operators to for manipulating fraction objects. It is minimal and could be improved. For one thing it doesn't use a header file interface. (I wrote the whole class in "Fraction.h"). I didn't overload the equality and non equality operators, which I should have.

#include
using namespace std;

class Fraction
{
/************************************
* This class enables a user to do fraction
* math. To do so it overloads several operators.
* It also introduces some error trapping
*******************************************/
//public members
public:
//default constructor
Fraction(){}
//overloaded constructor
Fraction(int numerator, int denominator)
{
SetNumerator(numerator);
SetDenominator(denominator);
}

//start overloaded operators
Fraction operator+ (const Fraction &F2)
{
//this overloads the + operator for two
//fraction objects. It returns the result
//as a fraction object. It gets the greatest
//common denominator--better would be a routine
//that returns the lowest common denominator
//the "this->" pointer points to elements of
//the current class

Fraction temp; //declare an object of the type Fraction
temp.den=this->den * F2.den;
temp.num=F2.den* this->num + this->den * F2.num;
return temp;
}

Fraction operator-(const Fraction &F2)
{
//does the same thing as + but with a -
Fraction temp; //declare an object of the type Fraction
temp.den=this->den * F2.den;
temp.num=F2.den* this->num - this->den * F2.num;
return temp;
}

Fraction operator* (const Fraction &F2)
{
Fraction temp;
temp.den=this->den * F2.den;
temp.num=this->num * F2.num;
return temp;
}

Fraction operator/ (const Fraction &F2)
{
Fraction temp;
temp.den=this->den * F2.num;
temp.num=this->num * F2.den;
return temp;
}

//these next operators are different because they change
//the current instance of Fraction, so they
//return not a third object but a pointer to the
//current instance using *this

Fraction& operator= (const Fraction &F2)
{
this->den=F2.den;
this->num=F2.num;
return *this;
}

Fraction& operator+=(const Fraction &F2)
{
//again we have to get the greatest common denominator
this->num=F2.den * this->num + this->den * F2.num;
this->den=this->den + F2.den;
return *this;
}

Fraction& operator-=(const Fraction F2)
{
this->num=F2.den * this->num - this->den * F2.num;
this->den=this->den * F2.den;
return *this;
}

Fraction& operator*=(const Fraction F2)
{
this->num = this->num * F2.num;
this->den=this->den * F2.den;
return *this;
}

Fraction& operator/=(const Fraction F2)
{
this->num = this->num * F2.den;
this->den=this->den * F2.num;
return *this;
}

//print out the fraction
void PrintFraction()
{
cout << num <<"/" << den << endl;
}

//private members
private:
int num;
int den;

//set functions with some error trapping
//these are private because I don't want
//the user directly access them
void SetNumerator(int n)
{

num = n;
}

void SetDenominator(int d)
{
if (d==0)
throw "Division by 0 error";
den=d;
}
};


Here is some code for testing the fraction. Notice it also uses a try catch black to catch errors thrown by the fraction class:

#include "Fraction.h"

int main()
{
try
{
//uncomment this to see the error thrown
//Fraction e(2,0);
//Declare 3 fractions
Fraction a(1,2);
Fraction b(1,3);
Fraction c; //uses default constructor

//show the current fractions
cout << "Fraction a " << endl;
a.PrintFraction();
cout <<"Fraction b " << endl;
b.PrintFraction();

cout << "\nfraction a + fraction b = ";
c = a + b;
c.PrintFraction();

cout << "\nfraction a - fraction b = ";
c = a - b;
c.PrintFraction();

cout << "\nfraction a * fraction b = ";
c = a * b;
c.PrintFraction();

cout << "\nfraction a / fraction b = ";
c = a / b;
c.PrintFraction();

cout <<"\nfraction a += fraction b = ";
a += b;
a.PrintFraction();

cout << "\nfraction a -= fraction b = ";
a -= b;
a.PrintFraction();

cout << "\nfraction a *= fraction b = ";
a *= b;
a.PrintFraction();

cout << "\nfraction a /= fraction b = ";
a /= b;
a.PrintFraction();


cout <<"Fraction a currently ";
a.PrintFraction();
cout << "\nFraction b currently ";
b.PrintFraction();
cout << "\nAssigning Fraction a = Fraction b. Fraction a = ";
a = b;
a.PrintFraction();

}
catch (char* s)
{
//the char* is a pointer to the strin
//thrown from the set functions
cout << s << endl;
}
char x;
cin >> x;
}

Tuesday, August 3, 2010

Monday, August 2, 2010

CLR Stored Procedure

It is possible in Sql Server to create a stored procedure in C# or Visual Basic. This is a tutorial/assignment in how to create a very simple procedure in C#:

1. Start a new project in Visual Studio.
2. Under C# choose Database as the kind of project.
3. Then Choose SQLServer Project.
4. If you have existing database connections, it will ask if you want to use one. If one to community assist exits use it. Other wise it will ask what kind of connection you want. Then it will open a new database connection dialog. Fill it in to look like the following:



5. Click OK. A dialog box will open telling you you need to enable clr/sql bugging:



6. Click Yes to continue.
7.Right click on the solution in the Solution Explorer and choose Add/Stored Procedure. Name it "ServiceSummary".



8. Enter this code:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void ServiceSummary()
{
using (SqlConnection connect = new SqlConnection("context connection=true"))
{
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandText=
"Select ServiceName, sum(GrantAmount) as Total "
+ "From [Service] s "
+ "Inner Join ServiceGrant sg "
+ "On s.ServiceKey=sg.ServiceKey "
+ "Group by ServiceName";
SqlContext.Pipe.ExecuteAndSend(cmd);
}


}
};


9. When you have the code in, build it.
10. Right click on the project in the Solution Explorer and choose "Deploy."
11. Open Sql Server Management Studio.
12. Look under stored procedures in CommunityAssist. You should see serviceSummary showing.
13. Before you can use the procedure, you must enable clr execution in Sql Server
to do that enter the following SQL:


sp_configure 'clr enabled", 1
Go
Reconfigure
Go


14.Execute the procedure by typing EXEC ServiceSummary in the query window

Class Object Example

Here is the header file BankAccount.h

#pragma once
#include <string>
using namespace std;
class BankAccount
{
/************************
* this class will take in an initial balance
* and then allow the user to add deposits
* or make withdrawls
* Steve conger 8/2/2010
*******************************/
public:
BankAccount(void);
BankAccount(double, string account, string name);
~BankAccount(void);
void SetInitialBalance(double);
double GetBalance();
void SetAccount(string);
string GetAccountNumber();
void SetCustomerName(string);
string GetCustomerName();

void MakeDeposit(double);
int MakeWithdrawl(double);

private:
string accountNumber;
string customerName;
double balance;
};

Here is the BankAccount.cpp

#include "BankAccount.h"

BankAccount::BankAccount(void)
{
}

BankAccount::BankAccount(double initialBal, string account, string name)
{
SetInitialBalance(initialBal);
SetAccount(account);
SetCustomerName(name);
}

BankAccount::~BankAccount(void)
{
}

void BankAccount::SetInitialBalance(double initialBalance)
{
balance=initialBalance;
}

double BankAccount::GetBalance()
{
return balance;
}

void BankAccount::SetAccount(string accNumber)
{
accountNumber=accNumber;
}

string BankAccount::GetAccountNumber()
{
return accountNumber;
}

void BankAccount::SetCustomerName(string custName)
{
customerName=custName;
}

string BankAccount::GetCustomerName()
{
return customerName;
}

void BankAccount::MakeDeposit(double deposit)
{
balance += deposit;
}

int BankAccount::MakeWithdrawl(double withdrawl)
{
int result=0;
if (balance <= withdrawl)
{
balance -= withdrawl;
result=1;

}
return result;
}

Here is the program.cpp file

#include <iostream>
#include "BankAccount.h"
using namespace std;

void PauseIt();

int main()
{
cout << "Enter account Number: ";
string acc;
getline(cin, acc);

cout << endl;

cout << "Enter account Name: ";
string n;
getline(cin, n);

cout << endl;

cout << "Enter initial Balance: ";
double ibal;
cin >> ibal;

cout << endl;

BankAccount bacc(ibal,acc,n);

cout << "make a Deposit ";
double dep;
cin >> dep;

bacc.MakeDeposit(dep);

cout << "make a withdrawl ";
double wd;
cin >> wd;
cout << endl;
int result=bacc.MakeWithdrawl(wd);

if (result ==0)
{
cout << "insufficient funds" << endl;

}

cout<<endl;
cout << bacc.GetAccountNumber()<< ", " <<
bacc.GetCustomerName()<< " Your balance is "
<< bacc.GetBalance() << endl;

PauseIt();
}

void PauseIt()
{
cout << "enter any character and press Enter to exit"
<<endl;
char c;
cin >> c;
}