Tuesday, May 26, 2015

Unit Tests

First we created a couple of classes to test. A Grade Class to store grade information and a GPA class that stores grades in a list and has two methods one to calculate GPA and one to calculate a straight average.

Grade Class


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

namespace ConsoleApplication2
{
    public class Grade
    {
        public string ClassName { get; set; }
        public int Credits { get; set; }

        public double GradePoint { get; set; }
    }
}


GPA Class


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

namespace ConsoleApplication2
{
    public class GPA
    {
        public List Grades { get; set; }

        public GPA()
        {
            Grades = new List();
        }

        public void addGrade(Grade g)
        {
            Grades.Add(g);
        }

        public double CalculateGPA()
        {
            int totalCredits = 0;
            double totalWeight = 0;
            foreach(Grade g in Grades)
            {
                totalCredits += g.Credits;
                totalWeight += g.Credits * g.GradePoint;
            }
            return totalWeight / totalCredits;
        }

        public double StraightAverage()
        {
            double totalGrades = 0;
            foreach(Grade g in Grades)
            {
                totalGrades += g.GradePoint;
            }

            return totalGrades / Grades.Count();
        }

    }
}


Next we right clicked on the solution and added a new project. We chose Test and Unit Test. Next we added a reference to the GPA project so we could talk to its classes. (It is important that they be public.)

Here is the Test class


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ConsoleApplication2;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        GPA gpa = new GPA();
        [TestMethod]
        public void TestGPA()
        {
            
            AddSomeClasses();
            double g = gpa.CalculateGPA();

            Assert.AreEqual(39.5 / 13, g);
        }

        [TestMethod]
        public void TestStraightAverage()
        {
            
            AddSomeClasses();
            double avg = gpa.StraightAverage();

            Assert.AreEqual(9.5 / 3, avg);
        }

        private void AddSomeClasses()
        {
            
            Grade g1 = new Grade();
            g1.Credits = 5;
            g1.GradePoint = 2;
            gpa.addGrade(g1);

            Grade g2 = new Grade();
            g2.Credits = 3;
            g2.GradePoint = 4;
            gpa.addGrade(g2);

            Grade g3 = new Grade();
            g3.Credits = 5;
            g3.GradePoint = 3.5;
            gpa.addGrade(g3);
        }
    }
}

Assignment 5 Example Service Client

Default.aspx


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>User Name</td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Password</td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password">

                </asp:TextBox></td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnLogin" runat="server" Text="Log in" OnClick="btnLogin_Click" /></td>
            <td>
                <asp:Label ID="lblError" runat="server" Text=""></asp:Label></td>
        </tr>
    </table>
        <asp:LinkButton ID="LinkButton1" runat="server" 
            PostBackUrl="~/Registration.aspx">
            Register</asp:LinkButton>
    </div>
    </form>
</body>
</html>


Default.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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        RegistrationService.ReviewerRegistrationClient rrc
            = new RegistrationService.ReviewerRegistrationClient();
        int key=rrc.ReviewerLogin
            (txtUserName.Text, txtPassword.Text);
        if (key != 0)
        {
            Session["userKey"] = key;
            Response.Redirect("NewReview.aspx");
        }
        else
        {
            lblError.Text = "Invalid Login";
        }
    }
}

Registration.aspx


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p>First Name <br />
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
    </p>
 <p>Last Name <br />
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
    </p>
         <p>Email <br />
        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
    </p>
         <p>UserName <br />
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
    </p>
         <p>Password <br />
        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
    </p>
         <p><asp:Button runat="server" ID="btnRegister" Text="Register" OnClick="btnRegister_Click" /><br />
             <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
    </p>
        <asp:LinkButton ID="LinkButton1" runat="server" 
            PostBackUrl="~/Default.aspx">Log in</asp:LinkButton>
    </div>
    </form>
</body>
</html>


Registration.aspx.cs

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

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        Reviewer r = new Reviewer();
        r.ReviewerFirstName = txtFirstName.Text;
        r.ReviewerLastName = txtLastName.Text;
        r.ReviewerUserName = txtUserName.Text;
        r.ReviewerEmail = txtEmail.Text;
        r.ReviewPlainPassword = txtPassword.Text;

        ReviewerRegistrationClient rrc = new 
            ReviewerRegistrationClient();
     
            bool result=rrc.Register(r);
            if (result)
                lblError.Text = "Reviewer Registered";
            else
                lblError.Text = "Registration Failed";
        
    }
}

NewReview.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlBooks" runat="server"></asp:DropDownList>
        <p>Title<br />
            <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
        </p>
        <p>Rating
            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                <asp:ListItem Text="1" Value="1"></asp:ListItem>
                <asp:ListItem Text="2" Value="2"></asp:ListItem>
                <asp:ListItem Text="3" Value="3"></asp:ListItem>
                <asp:ListItem Text="4" Value="4"></asp:ListItem>
                <asp:ListItem Text="5" Value="5"></asp:ListItem>

            </asp:RadioButtonList>
        </p>
        <p>The Review<br />
            <asp:TextBox ID="txtReview" TextMode="MultiLine" 
                runat="server" Height="130px" Width="328px"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="btnAddReview" runat="server" Text="Add Review" 
                OnClick="btnAddReview_Click"></asp:Button> <br />
            <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>

NewReview.aspx.cs

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

public partial class NewReview : System.Web.UI.Page
{
    CreateReviewServiceClient crc = new CreateReviewServiceClient();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userKey"] != null)
        {
            if (!IsPostBack)
            {
                Book[] books = crc.GetBooks();
                ddlBooks.DataSource = books;
                ddlBooks.DataTextField = "BookTitle";
                ddlBooks.DataValueField = "BookKey";
                ddlBooks.DataBind();
            }
        }
        else
        {
            Response.Redirect("Default.aspx");
        }
    }
    protected void btnAddReview_Click(object sender, EventArgs e)
    {
        Review r = new Review();
        r.BookKey = int.Parse(ddlBooks.SelectedValue.ToString());
        r.ReviewerKey = (int)Session["userKey"];
        r.ReviewTitle = txtTitle.Text;
        r.ReviewRating = int.Parse(RadioButtonList1.SelectedValue.ToString());
        r.ReviewText = txtReview.Text;

        bool good = crc.WriteReview(r);
        if(good)
        {
            lblError.Text="review saved";
        }
        else
        {
            lblError.Text = "something went horribly wrong";
        }
    }
}

Thursday, May 14, 2015

Assignment 4 in class example

Here is the code for the Register and login service. I have not included the HashPass, LoginClass or SeedCode classes.

IReviewerRegistration

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;


[ServiceContract]
public interface IReviewerRegistration
{
 [OperationContract]
 bool Register(Reviewer reviewer);

    [OperationContract]
    int ReviewerLogin(string userName, string Password);
}


ReviewerRegistration the service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ReviewerRegistration" in code, svc and config file together.
public class ReviewerRegistration : IReviewerRegistration
{

    BookReviewDbEntities db = new BookReviewDbEntities();
    public bool Register(Reviewer reviewer)
    {
        bool good = true;

        try
        {

            KeyCode k = new KeyCode();
            int seed = k.GetKeyCode();
            PasswordHash hash = new PasswordHash();
            byte[] hashedpassword = hash.HashIt
                (reviewer.ReviewPlainPassword, seed.ToString());

           
            reviewer.ReviewerKeyCode = seed;
            reviewer.ReviewerHashedPass = hashedpassword;
            reviewer.ReviewerDateEntered = DateTime.Now;
            db.Reviewers.Add(reviewer);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            good = false;
        }


        return good;
    }

    public int ReviewerLogin(string userName, string Password)
    {
        LoginClass lc = new LoginClass(userName, Password);
        return lc.ValidateLogin();
    }
}


Now here is the code for the second service to Add a review

Here is the Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICreateReviewService" in both code and config file together.
[ServiceContract]
public interface ICreateReviewService
{
    [OperationContract]
    List GetBooks();

    [OperationContract]
    List GetAuthors();

    [OperationContract]
    List GetCategories();

    [OperationContract]
    bool WriteReview(Review r);
}


Here is the service code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CreateReviewService" in code, svc and config file together.
public class CreateReviewService : ICreateReviewService
{
    BookReviewDbEntities db = new BookReviewDbEntities();

    public List<Book> GetBooks()
    {
        var bks = from b in db.Books
                  orderby b.BookTitle
                  select b;

        List<Book> books = new List<Book>();
        foreach(Book b in bks)
        {
            Book bk = new Book();
            bk.BookTitle = b.BookTitle;
            bk.BookISBN = b.BookISBN;
            bk.BookKey = b.BookKey;

            books.Add(bk);
           
        }
        return books;
        
    }

    public List<Author> GetAuthors()
    {
        var auth = from a in db.Authors
                  orderby a.AuthorName
                  select a;

        List<Author> authors = new List<Author>();
        foreach (Author a in auth)
        {
            Author au = new Author();
            au.AuthorKey = a.AuthorKey;
            au.AuthorName = a.AuthorName;


            authors.Add(au);
        }
        return authors;
    }

    public List<Category> GetCategories()
    {
        var cats = from c in db.Categories
                  orderby c.CategoryName
                  select c;

        List<Category> categories = new List<Category>();
        foreach(Category c in cats)
        {
            Category bk = new Category();
            bk.CategoryName = c.CategoryName;
            bk.CategoryKey = c.CategoryKey;
           

            categories.Add(bk);
        }
        return categories;
           
    }

    public bool WriteReview(Review r)
    {
        bool result = true;
        try
        {

            r.ReviewDate = DateTime.Now;
            db.Reviews.Add(r);
            db.SaveChanges();
        }
        catch(Exception ex)
        {
            result = false;
        }
        return result;
    }
}