Thursday, June 4, 2015

Service Query and client

Here is the service Interface for the service which queries Shows for a particular venue. It includes a data contract for for a class that allows us to combine fields from Show and ShowData.

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 "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
 [OperationContract]
 List<ShowInfo> GetShowsByVenue(string venueName);

}


[DataContract]
public class ShowInfo
{
    [DataMember]
    public string ArtistName { get; set; }
    [DataMember]
    public string ShowName { get; set; }
    [DataMember]
    public string ShowDate { get; set; }
    [DataMember]
    public string ShowTime { get; set; }

    [DataMember]
    public string TicketInfo { get; set; }
}

Here is the code for the query itself

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 "Service" in code, svc and config file together.
public class Service : IService
{
    ShowTrackerEntities db = new ShowTrackerEntities();

    public List<ShowInfo> GetShowsByVenue(string venueName)
    {
        var shws = from s in db.Shows
                   from d in s.ShowDetails
                   where s.Venue.VenueName.Equals(venueName)
                   select new
                   {
                       d.Artist.ArtistName,
                       s.ShowName,
                       s.ShowTime,
                       s.ShowDate,
                       s.ShowTicketInfo

                   };
        List<ShowInfo> shows = new List<ShowInfo>();

        foreach(var sh in shws)
        {
            ShowInfo sInfo = new ShowInfo();
            sInfo.ArtistName = sh.ArtistName;
            sInfo.ShowName = sh.ShowName;
            sInfo.ShowDate = sh.ShowDate.ToShortDateString();
            sInfo.ShowTime = sh.ShowTime.ToString();
            shows.Add(sInfo);
        }

        return shows;
    }
}

Now here is the ASP code for the simple web page client. We first had to make a reference to the service. Also we used a text box to enter the venue name. It should be a drop down list.

<%@ 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>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
        <asp:Button ID="Button1" runat="server" Text="Get Shows" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

And here is the code behind

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 Button1_Click(object sender, EventArgs e)
    {
        //Instantiate the service client so we have access to the serivce
        ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();
        //create an array and assign it the result of the service query
        ServiceReference1.ShowInfo[] shows = sc.GetShowsByVenue(TextBox1.Text);
        //bind the array to the DataGrid
        GridView1.DataSource = shows;
        GridView1.DataBind();

    }
}

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;
    }
}

Thursday, April 30, 2015

Class Reader Diagram

Here is the class diagram we did in class.

CardReader is an abstract class that cannot be instantiated except through its children.It containst all the fields and methods that are common to the busreaders--that is methods which have the same implementation.

TrainCardReader and BusCardReader inherit from CardReader.

CardReader has an aggregation relationship to Card. The CardReader class contains an instance of the Card Class, but the Card class has an existence separate from the container.

Card aggregates Trip (as do the readers)

TrainCardReader and BusCardReader implement the interface IReader which means they must provide a body for its abstract methods

Assignment 3 class Example

Here is the 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>Login</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>Enter User Name</td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server">
</asp:TextBox></td>
        </tr>
            <tr>
            <td>Enter Password</td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server">
</asp:TextBox></td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnSubmint" runat="server" Text="Log in" 
OnClick="btnSubmint_Click" /></td>
            <td>
                <asp:Label ID="lblResult" runat="server" Text="">
</asp:Label></td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>


Here is the 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 btnSubmint_Click(object sender, EventArgs e)
    {
        LoginClass lc = new LoginClass(txtPassword.Text, txtUserName.Text);
        int result = lc.ValidateLogin();
        if (result != 0)
        {
            
            Session["userKey"] = result;
            Response.Redirect("Welcome.aspx");
        }
        else
        {
            lblResult.Text = "Invalid login";
        }
    }
}

Here is the ReviewerRegistration.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>Login</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>Enter User Name</td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server">
</asp:TextBox></td>
        </tr>
            <tr><%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReviewerRegistration.aspx.cs" Inherits="ReviewerRegistration" %>

<!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>First Name</td>
            <td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>Last Name</td>
            <td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
        </tr>
         <tr>
            <td>Email</td>
            <td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
        </tr>
         <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>Confirm Password</td>
            <td><asp:TextBox ID="txtConfirm" runat="server" TextMode="Password"></asp:TextBox></td>
        </tr>
         <tr>
            <td>
                <asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" /></td>
            <td>
                <asp:Label ID="lblErrorSuccess" runat="server" Text=""></asp:Label></td>
        </tr>
       
    </table>
        <asp:LinkButton ID="LbLogin" runat="server" 
PostBackUrl="~/Default.aspx">Log in</asp:LinkButton>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtUserName" Display="None" ErrorMessage="User name required"></asp:RequiredFieldValidator>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtLastName" Display="None" ErrorMessage="Last name required"></asp:RequiredFieldValidator>
    </div>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail" Display="None" ErrorMessage="Invalid email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
    </form>
</body>
</html>

            <td>Enter Password</td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server">
</asp:TextBox></td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnSubmint" runat="server" Text="Log in" 
OnClick="btnSubmint_Click" /></td>
            <td>
                <asp:Label ID="lblResult" runat="server" Text="">
</asp:Label></td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>


And here is the ReviewerRegistration.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 ReviewerRegistration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {

        BookReviewDbEntities db = new BookReviewDbEntities();
        try
        {


            Reviewer r = new Reviewer();
            r.ReviewerFirstName = txtFirstName.Text;
            r.ReviewerLastName = txtLastName.Text;
            r.ReviewerEmail = txtEmail.Text;
            r.ReviewerUserName = txtUserName.Text;
            r.ReviewPlainPassword = txtPassword.Text;

            KeyCode kc = new KeyCode();
            int code = kc.GetKeyCode();

            r.ReviewerKeyCode = code;

            PasswordHash ph = new PasswordHash();

            Byte[] hashed = ph.HashIt(txtPassword.Text, code.ToString());
            r.ReviewerHashedPass = hashed;
            r.ReviewerDateEntered = DateTime.Now;
            db.Reviewers.Add(r);

            CheckinLog log = new CheckinLog();
            log.Reviewer = r;
            log.CheckinDateTime = DateTime.Now;
            db.CheckinLogs.Add(log);
            
            db.SaveChanges();
            lblErrorSuccess.Text = "Sucessfully Registered";
        }
        catch(Exception ex)
        {
            lblErrorSuccess.Text = ex.Message;
        }
    }
}

And here again is the LoginClass.cs though it is the same as in the other blog. I am not including the password hash class or the key code classes

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

/// 
/// This class takes in the user name and password
/// retrieves information from the database
/// and then hashes the password and key to
/// see if it matches the database hash
/// 
public class LoginClass
{
    //class level variables-fields
    private string pass;
    private string username;
    private int seed;
    private byte[] dbhash;
    private int key;
    private byte[] newHash;

    //constructor takes in password and username
    public LoginClass(string pass, string username)
    {
        this.pass = pass;
        this.username = username;
    }

    //gets the user info from the database
    private void GetUserInfo()
    {
        //declare the ADO Entities
        BookReviewDbEntities brde = new BookReviewDbEntities();
        //query the fields
        var info = from i in brde.Reviewers
                   where i.ReviewerUserName.Equals(username)
                   select new { i.ReviewerKey, i.ReviewerHashedPass, i.ReviewerKeyCode };

        //loop through the results and assign the
        //values to the field variables
        foreach (var u in info)
        {
            seed = u.ReviewerKeyCode;
            dbhash = u.ReviewerHashedPass;
            key = u.ReviewerKey;
        }
    }

    private void GetNewHash()
    {
        //get the new hash
        PasswordHash h = new PasswordHash();
        newHash = h.HashIt(pass, seed.ToString());
    }

    private bool CompareHash()
    {
        //compare the hashes
        bool goodLogin = false;

        //if the hash doesn't exist
        //because not a valid user
        //the return will be false
        if (dbhash != null)
        {
            //if the hashes do match return true
            if (newHash.SequenceEqual(dbhash))
                goodLogin = true;
        }

        return goodLogin;

    }

    public int ValidateLogin()
    {
        //call the methods
        GetUserInfo();
        GetNewHash();
        bool result = CompareHash();

        //if the result is not true
        //set the key to 0
        if (!result)
            key = 0;


        return key;
    }

}

Thursday, April 23, 2015

Activity diagrams

Here is the one with swim lanes