public void CastToByte()
        {
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.Query.Select((esByte)emp.Query.Age.As("CastColumn"));
            emp.Query.Where(emp.Query.EmployeeID == 1);

            switch (emp.es.Connection.ProviderSignature.DataProviderName)
            {
                case "EntitySpaces.MSAccessProvider":
                case "EntitySpaces.MySqlClientProvider":
                case "EntitySpaces.OracleClientProvider":
                case "EntitySpaces.NpgsqlProvider":
                case "EntitySpaces.Npgsql2Provider":
                case "EntitySpaces.SQLiteProvider":
                //case "EntitySpaces.SqlServerCeProvider":
                    Assert.Ignore("Not supported.");
                    break;
                default:
                    Assert.IsTrue(emp.Query.Load());

                    byte value = 30;
                    object obj = emp.GetColumn("CastColumn");
                    Assert.AreEqual("System.Byte", obj.GetType().ToString());
                    Assert.AreEqual(value, obj);
                    break;
            }
        }
        public void updateEvent(string status)
        {
            checkLogin();
            //retrieve logged in user info
            //create new event
            //update new event to reflect submitted changes
            BusinessObjects.Employee loggedInEmployee = (BusinessObjects.Employee)Session["loggedInUser"];
            try
            {
                int selectedEventID = (int)Session["selectedEventID"];

                BusinessObjects.ExEvent originalExEvent = _myExEventManager.FetchEvent(selectedEventID);
                BusinessObjects.ExEvent updatedExEvent  = new BusinessObjects.ExEvent();

                updatedExEvent.eventID        = originalExEvent.eventID;
                updatedExEvent.eventDate      = originalExEvent.eventDate;
                updatedExEvent.employeeID     = originalExEvent.employeeID;
                updatedExEvent.submissionDate = originalExEvent.submissionDate;
                updatedExEvent.activityName   = originalExEvent.activityName;
                updatedExEvent.startTime      = originalExEvent.startTime;
                updatedExEvent.endTime        = originalExEvent.endTime;
                updatedExEvent.statusName     = status;
                updatedExEvent.activityNote   = originalExEvent.activityNote;

                updatedExEvent.completedBy   = loggedInEmployee.FirstName + " " + loggedInEmployee.LastName;
                updatedExEvent.completedDate = DateTime.Now;
                _myExEventManager.UpdateExEvent(originalExEvent, updatedExEvent);
            }
            catch (Exception)
            {
            }
        }
		public void TestSelfReference()
		{
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.LoadByPrimaryKey(1);
            Assert.AreEqual(2, emp.EmployeeCollectionBySupervisor.Count);
		}
		public void TestNullReferences()
		{
			Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.LoadByPrimaryKey(5);
			Assert.AreEqual(0, emp.CustomerCollectionByManager.Count);
			Assert.AreEqual(0, emp.CustomerCollectionByStaffAssigned.Count);
		}
        public void DisableLazyLoad()
        {
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";
            emp.es.IsLazyLoadDisabled = true;

            emp.LoadByPrimaryKey(1);
            Assert.AreEqual(0, emp.CustomerCollectionByManager.Count);
            Assert.AreEqual(0, emp.CustomerCollectionByStaffAssigned.Count);
            Assert.AreEqual(0, emp.EmployeeCollectionBySupervisor.Count);
            Assert.AreEqual(0, emp.EmployeeTerritoryCollectionByEmpID.Count);
            Assert.AreEqual(0, emp.OrderCollectionByEmployeeID.Count);
            Assert.AreEqual(0, emp.ReferredEmployeeCollectionByEmployeeID.Count);
            Assert.AreEqual(0, emp.ReferredEmployeeCollectionByReferredID.Count);
            Assert.IsNull(emp.UpToEmployeeBySupervisor);
            Assert.AreEqual(0, emp.UpToTerritoryCollection.Count);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //checkLogin();
            if (!IsPostBack)
            {
            }

            if (Session["selectedEmployeeID"] != null)
            {
                if (!IsPostBack)
                {
                    //extract current event id from session variable
                    int selectedEmployeeID = (int)Session["selectedEmployeeID"];
                    //lblName.Text = selectedEmployeeID.ToString();

                    BusinessObjects.Employee selectedEmployee = _myEmployeeManager.FindSingleEmployee(selectedEmployeeID);



                    List <Department> deptList = _myEmployeeManager.FetchDepartmentList();
                    ddlDepartment.DataTextField  = "departmentName";
                    ddlDepartment.DataValueField = "departmentName";
                    ddlDepartment.DataSource     = deptList;
                    ddlDepartment.DataBind();

                    ddlDepartment.SelectedValue = selectedEmployee.DepartmentName;

                    //search db for event by event id

                    lblNameField.Text = selectedEmployee.FirstName + " " + selectedEmployee.LastName;
                    lblRoleField.Text = selectedEmployee.RoleName;

                    List <Employee> supList       = _myEmployeeManager.SelectSupsByDept(ddlDepartment.SelectedValue);
                    List <Employee> sortedSupList = supList.OrderBy(o => o.LastName).ToList();
                    ddlSupervisor.DataTextField  = "FullName";
                    ddlSupervisor.DataValueField = "FullName";
                    ddlSupervisor.DataSource     = sortedSupList;
                    ddlSupervisor.DataBind();
                    string supName = selectedEmployee.SupervisorLastName + ", " + selectedEmployee.SupervisorFirstName;
                    selectedEmployee.FullSupName = supName;
                    ddlSupervisor.SelectedValue  = selectedEmployee.FullSupName;
                    //lblSupervisor.Text = selectedEmployee.FullSupName;
                }
            }
        }
        protected void submitResetPassword_Click(object sender, EventArgs e)
        {
            tbResetPassword.Visible   = false;
            lblResetSubmitted.Visible = true;

            string username = txtUsername.Text;

            try
            {
                //retrieve emmployee account info
                BusinessObjects.Employee origEmployee  = _myEmployeeManager.FindEmployee(username);
                BusinessObjects.Employee checkUsername = _myEmployeeManager.FindEmployee(username);
                if (checkUsername.Username != null)
                {
                    //confirm that email address matches address entered into form
                    if (checkUsername.EmailAddress == txtEmailAddress.Text)
                    {
                        //generate ranndom hash for password reset
                        string resetLinkHash = createResetLinkHash(username);
                        //generate new expiration date for reset request
                        DateTime passExpire = DateTime.Now.AddDays(3);

                        checkUsername.NewPassExpire = passExpire;
                        checkUsername.NewPassID     = resetLinkHash;

                        try
                        {
                            //update employee with new reset hash and exp date
                            _myEmployeeManager.UpdateEmployee(origEmployee, checkUsername);
                        }
                        catch (Exception)
                        {
                        }
                        //create reset password with random hash included in query string
                        string resetLink = "http://nimbusguild.com/ResetPassword.aspx?resetid=" + resetLinkHash;
                        //send reset email
                        SendMail(checkUsername.FirstName, checkUsername.LastName, resetLink);
                    }
                }
            }
            catch (Exception)
            {
            }
        }
        public void updateEvent(string status)
        {
            //create employee object from stored sessoin variable
            BusinessObjects.Employee loggedInEmployee = (BusinessObjects.Employee)Session["loggedInUser"];
            try
            {
                int selectedEventID = (int)Session["selectedEventID"];

                BusinessObjects.ExEvent originalExEvent = _myExEventManager.FetchEvent(selectedEventID);
                BusinessObjects.ExEvent updatedExEvent  = new BusinessObjects.ExEvent();

                updatedExEvent.eventID        = originalExEvent.eventID;
                updatedExEvent.eventDate      = Convert.ToDateTime(txtEventDate.Text);
                updatedExEvent.employeeID     = originalExEvent.employeeID;
                updatedExEvent.submissionDate = originalExEvent.submissionDate;
                updatedExEvent.activityName   = listActivity.SelectedItem.Value;
                updatedExEvent.startTime      = startHour.SelectedItem.Value + ":" + startMinute.SelectedItem.Value + " " + startAMPM.SelectedItem.Value;
                updatedExEvent.endTime        = endHour.SelectedItem.Value + ":" + endMinute.SelectedItem.Value + " " + endAMPM.SelectedItem.Value;
                updatedExEvent.statusName     = status;
                updatedExEvent.activityNote   = txtActivityNote.Text;

                //if the new event status is completed or rejected, capture and update info for completed on and completed by
                if (status != "Pending")
                {
                    updatedExEvent.completedBy   = loggedInEmployee.FirstName + " " + loggedInEmployee.LastName;
                    updatedExEvent.completedDate = DateTime.Now;
                    _myExEventManager.UpdateExEvent(originalExEvent, updatedExEvent);
                }
                else
                {
                    updatedExEvent.completedDate = originalExEvent.completedDate;
                    updatedExEvent.completedBy   = originalExEvent.completedBy;
                    _myExEventManager.UpdateExEventToPending(originalExEvent, updatedExEvent);
                }
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", "window.close()", true);
                //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Submission Updated Successfully');", true);
                //Response.End();
            }
            catch (Exception)
            {
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            checkLogin();
            //retrieve current activity list from db
            //bind activity list to drop down list
            List <Activity> activitiesToList = _myExEventManager.FetchActivityList();

            if (!IsPostBack)
            {
                listActivity.DataTextField  = "activityName";
                listActivity.DataValueField = "activityName";
                listActivity.DataSource     = activitiesToList;
                listActivity.DataBind();
                listActivity.SelectedValue = "Huddle";
                txtEventDate.Text          = DateTime.Today.Date.ToShortDateString();
            }
            //assign loggedInEmployee to session variable
            if (Session["loggedInUser"] != null)
            {
                loggedInEmployee = (BusinessObjects.Employee)Session["loggedInUser"];
            }
        }
        public void TestJSONSerialization()
        {
            //---------------------------------------------------------------
            // Server Side
            //---------------------------------------------------------------
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.Query.es.Top = 1;
            emp.Query.Select
            (
                emp.Query.EmployeeID,
                emp.Query.FirstName,
                emp.Query.LastName,
                emp.Query.Age,
                (emp.Query.LastName + ", " + emp.Query.FirstName).As("Fullname")
            );
            emp.Query.Load();

            // Modifiy the first name ...
            emp.FirstName = "Freddy";

            //=======================

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmployeeProxyStub));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, (EmployeeProxyStub)emp);

            string json = Encoding.Default.GetString(ms.ToArray());
            ms.Close();

            ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            ser = new DataContractJsonSerializer(typeof(EmployeeProxyStub));
            EmployeeProxyStub empProxy = ser.ReadObject(ms) as EmployeeProxyStub;
            ms.Close();

            Employee emp2 = empProxy.Entity;
        }
        public void ErrorsWithContinueDefaultFalse()
        {
            EmployeeCollection coll = new EmployeeCollection();
            coll.es.Connection.Name = "ForeignKeyTest";
            coll.LoadAll();
            Assert.AreEqual(5, coll.Count, "Initial Load");

            using (esTransactionScope scope = new esTransactionScope())
            {
                try
                {
                    // INSERT would succeed
                    // but should rollback by default
                    Employee emp1 = coll.AddNew();
                    emp1.FirstName = "asdf";
                    emp1.LastName = "adf";

                    // INSERT will fail - LastName required
                    Employee emp2 = coll.AddNew();

                    // UPDATE will fail - LastName required
                    Employee emp3 = coll.FindByPrimaryKey(1);
                    emp3.LastName = null;

                    // DELETE will fail - FK constraint
                    Employee emp4 = coll.FindByPrimaryKey(2);
                    emp4.MarkAsDeleted();

                    coll.Save(false);
                }
                catch (Exception ex)
                {
                    // Save() throws exception on first error encountered
                    Assert.AreEqual(1, coll.Errors.Count(), "ExceptionCount");
                    Assert.IsTrue(ex.ToString().Length > 0, "ExceptionLength");
                }
                finally
                {
                    // Confirm nothing got INSERTed
                    EmployeeCollection coll2 = new EmployeeCollection();
                    coll2.es.Connection.Name = "ForeignKeyTest";
                    coll2.LoadAll();
                    Assert.AreEqual(5, coll2.Count, "LoadInFinally");

                    // Confirm nothing got UPDATEd
                    Employee empUpd = coll2.FindByPrimaryKey(1);
                    Assert.AreEqual("Smith", empUpd.LastName, "Update");

                    // Confirm nothing got DELETEd
                    Employee empDel = new Employee();
                    empDel.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsTrue(empDel.LoadByPrimaryKey(2), "Delete");
                }
            }
        }
		public void TestSaveSelfReference()
		{
            int empKey = -1;
            int supvKey = -1;
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";
            Employee supv = new Employee();
            supv.es.Connection.Name = "ForeignKeyTest";

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    emp.LastName = "LastName";
                    emp.FirstName = "FirstName";

                    supv = emp.EmployeeCollectionBySupervisor.AddNew();
                    supv.LastName = "SupvLast";
                    supv.FirstName = "SupvFirst";

                    emp.Save();
                    empKey = emp.EmployeeID.Value;
                    supvKey = supv.EmployeeID.Value;

                    Assert.AreEqual(1, emp.EmployeeCollectionBySupervisor.Count);
                    Assert.AreEqual(emp.EmployeeID.Value, supv.Supervisor.Value);
                }
            }
            finally
            {
                // Clean up
                emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                if (emp.LoadByPrimaryKey(empKey))
                {
                    EmployeeCollection empColl = emp.EmployeeCollectionBySupervisor;
                    empColl.MarkAllAsDeleted();
                    emp.MarkAsDeleted();
                    emp.Save();
                }
            }
		}
        protected void btnViewReport_Click(object sender, EventArgs e)
        {
            checkLogin();
            try
            {
                Employee loggedInEmployee = (Employee)Session["loggedInUser"];
            }
            catch (Exception)
            {
                Response.Redirect("AgentView.aspx");
            }

            //grab user input data from form and set to var
            DateTime startDate      = Convert.ToDateTime(txtStartDate.Text);
            DateTime endDate        = Convert.ToDateTime(txtEndDate.Text);
            string   role           = listTopLevel.SelectedItem.Value;
            string   department     = listDepartment.SelectedItem.Value;
            int      representative = Convert.ToInt32(listRepresentative.SelectedItem.Value);
            string   status         = listStatus.SelectedItem.Value;

            lblNoData.Text      = "No records to display.";
            lblNoData.ForeColor = System.Drawing.Color.Red;

            //check selected role
            if (role == "Supervisor")
            {
                try
                {
                    //create employee object from supervisor selected
                    BusinessObjects.Employee repSelected = _myEmployeeManager.FindSingleEmployee(representative);

                    //create list of team leaders that report to this supervisor
                    List <BusinessObjects.Employee> _myEmployeeList = _myEmployeeManager.FindSupAgents(repSelected.FirstName, repSelected.LastName);

                    //iterate through and create a new list of all employees that report to each team leader that reports to this supervisor
                    foreach (BusinessObjects.Employee emp in _myEmployeeList)
                    {
                        try
                        {
                            //iterate through and create a new list of all requests submitted by each employee, that reports to each lead, that reports to this supervisor
                            _myExEventList = _myExEventManager.FetchEventsByAgent(emp.EmployeeID, status, startDate, endDate);
                            foreach (BusinessObjects.ExEvent ev in _myExEventList)
                            {
                                _completeSupEventList.Add(ev);
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
                catch (Exception)
                {
                    //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('No exceptions to display.');", true);
                }

                if (_completeSupEventList.Count() != 0)
                {
                    //statement added to page load that checks for edit/submit interaction causes gridview to duplicate events due to addl page load from view report button click event firing
                    //***will address logic bug later***
                    //for now, capture duplicate listings and filter
                    //var distinctItems = _completeSupEventList.GroupBy(x => x.eventID).Select(y => y.First());
                    lblNoData.Visible           = false;
                    gvExEvent.Visible           = true;
                    Session["currentEventList"] = _completeSupEventList;
                    Session["SortDirection"]    = "ASC";
                    gvExEvent.DataSource        = _completeSupEventList.OrderBy(o => o.agentName).ToList();
                    gvExEvent.DataBind();
                }
                //if event list is empty, hide gridview and display 'no records' message
                else
                {
                    lblNoData.Visible = true;
                    gvExEvent.Visible = false;
                }
            }
            else if (role == "Lead")
            {
                try
                {
                    //find selected lead employee
                    Employee repSelected = _myEmployeeManager.FindSingleEmployee(representative);

                    //create list of employees that report directly to selected lead
                    List <Employee> _myEmployeeList = _myEmployeeManager.FindLeadReports(repSelected.FirstName, repSelected.LastName);

                    //iterate through employee list and create combined list of all events submitted by each employee
                    foreach (Employee emp in _myEmployeeList)
                    {
                        try
                        {
                            _myExEventList = _myExEventManager.FetchEventsByAgent(emp.EmployeeID, status, startDate, endDate);
                            for (int i = 0; i < _myExEventList.Count; i++)
                            {
                                _completeLeadEventList.Add(_myExEventList[i]);
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
                catch (Exception)
                {
                    //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('No exceptions to display.');", true);
                }

                //populate gridview with results
                if (_completeLeadEventList.Count() != 0)
                {
                    lblNoData.Visible           = false;
                    gvExEvent.Visible           = true;
                    Session["currentEventList"] = _completeLeadEventList;
                    Session["SortDirection"]    = "ASC";
                    gvExEvent.DataSource        = _completeLeadEventList.OrderBy(o => o.agentName).ToList();
                    gvExEvent.DataBind();
                }
                else
                {
                    lblNoData.Visible = true;
                    gvExEvent.Visible = false;
                }
            }
            else if (role == "Agent")
            {
                //retrieve all events submitted by selected agent by status and start/end dates
                try
                {
                    _completeAgentEventList = _myExEventManager.FetchEventsByAgent(representative, status, startDate, endDate);
                }
                catch (Exception)
                {
                    //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('No exceptions to display.');", true);
                }

                //populate gridview with results
                if (_completeAgentEventList.Count != 0)
                {
                    lblNoData.Visible           = false;
                    gvExEvent.Visible           = true;
                    Session["currentEventList"] = _completeAgentEventList;
                    Session["SortDirection"]    = "ASC";
                    gvExEvent.DataSource        = _completeAgentEventList;
                    gvExEvent.DataBind();
                }
                else
                {
                    lblNoData.Visible = true;
                    gvExEvent.Visible = false;
                }
            }
        }
        public void SerializeDeserializeProxyStubEntity()
        {
            if (aggTest.es.Connection.Name == "SqlCe")
            {
                Assert.Ignore("Not tested for SqlCe.");
            }
            else
            {
                // Load an Employee
                Employee emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                emp.LoadByPrimaryKey(1);

                // Create a Proxy and Serialize into a string named "Packet"
                EmployeeProxyStub proxy =
                    new EmployeeProxyStub(emp);

                XmlSerializer sf =
                    new XmlSerializer(typeof(EmployeeProxyStub));
                StringWriter sw = new StringWriter();
                sf.Serialize(sw, proxy);

                string packet = sw.ToString();

                // Now let's DeSerialize it
                XmlSerializer xs =
                    new XmlSerializer(typeof(EmployeeProxyStub));
                StringReader sr = new StringReader(packet);

                proxy = xs.Deserialize(sr) as EmployeeProxyStub;

                Assert.AreEqual("Unchanged", proxy.Entity.es.RowState.ToString());
                Assert.AreEqual("Smith", proxy.Entity.LastName);
            }
        }
        public void SerializeDeserializeProxyStubEntityQuery()
        {
            if (aggTest.es.Connection.Name == "SqlCe")
            {
                Assert.Ignore("Not tested for SqlCe.");
            }
            else
            {
                // Client-side query to load an Employee
                Employee emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                emp.Query.Where(emp.Query.EmployeeID == 1);

                // Use binary serialization to include the query
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                bf.Serialize(ms, emp);
                byte[] query = ms.ToArray();

                // Send it to the server over the wire

                // Server-side deserialize
                bf = new BinaryFormatter();
                ms = new MemoryStream(query);
                Employee newEmp = bf.Deserialize(ms) as Employee;
                newEmp.es.Connection.Name = "ForeignKeyTest";
                newEmp.Query.es2.Connection.Name = "ForeignKeyTest";

                // Now load it 
                Assert.IsTrue(newEmp.Query.Load());
                Assert.AreEqual(1, newEmp.EmployeeID.Value);

                //  Server-side Create a Proxy and Serialize to XML string
                EmployeeProxyStub proxy =
                    new EmployeeProxyStub(newEmp);

                XmlSerializer sf =
                    new XmlSerializer(typeof(EmployeeProxyStub));
                StringWriter sw = new StringWriter();
                sf.Serialize(sw, proxy);

                string packet = sw.ToString();

                // Send it back to the client over the wire

                // Client-side Proxy XML string deserialize
                XmlSerializer xs =
                    new XmlSerializer(typeof(EmployeeProxyStub));
                StringReader sr = new StringReader(packet);

                proxy = xs.Deserialize(sr) as EmployeeProxyStub;
                emp = proxy.Entity;

                Assert.AreEqual("Unchanged", emp.es.RowState.ToString());
                Assert.AreEqual(1, emp.EmployeeID.Value);
            }
        }
        public void ErrorsWithContinueTrueDel()
        {
            EmployeeCollection coll = new EmployeeCollection();
            coll.es.Connection.Name = "ForeignKeyTest";
            coll.LoadAll();
            Assert.AreEqual(5, coll.Count, "Initial Load");

            using (esTransactionScope scope = new esTransactionScope())
            {
                // SQLite does not enforce FK constraints
                // So force a concurrency failure instead
                if (coll.es.Connection.ProviderSignature.DataProviderName
                    == "EntitySpaces.SQLiteProvider")
                {
                    Employee empConcurr = new Employee();
                    empConcurr.es.Connection.Name = "ForeignKeyTest";
                    empConcurr.LoadByPrimaryKey(2);
                    empConcurr.MarkAsDeleted();
                    empConcurr.Save();
                }

                // DELETE will fail - FK constraint
                Employee emp4 = coll.FindByPrimaryKey(2);
                emp4.MarkAsDeleted();

                coll.Save(true);

                Assert.AreEqual(1, coll.Errors.Count(), "ErrorsCount");
                Assert.IsNotNull(coll.es.DeletedEntities, "DeletedErrors");

                foreach (Employee e in coll.Errors)
                {
                    Assert.IsTrue(e.es.RowError.Length > 0);
                }

                if (coll.es.Connection.ProviderSignature.DataProviderName
                    != "EntitySpaces.SQLiteProvider")
                {
                    // Confirm same table row count
                    EmployeeCollection coll2 = new EmployeeCollection();
                    coll2.es.Connection.Name = "ForeignKeyTest";
                    coll2.LoadAll();
                    Assert.AreEqual(5, coll2.Count, "Load");

                    // Confirm nothing got DELETEd
                    Employee empDel = new Employee();
                    empDel.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsTrue(empDel.LoadByPrimaryKey(2), "Delete");
                }
            }
        }
        public void CastToChar()
        {
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.Query.Where(emp.Query.EmployeeID == 1);

            switch (emp.es.Connection.ProviderSignature.DataProviderName)
            {
                //case "EntitySpaces.MySqlClientProvider":
                //case "EntitySpaces.NpgsqlProvider":
                //case "EntitySpaces.Npgsql2Provider":
                //case "EntitySpaces.VistaDBProvider":
                //case "EntitySpaces.SQLiteProvider":
                case "EntitySpaces.MSAccessProvider":
                case "EntitySpaces.SqlServerCeProvider":
                case "EntitySpaces.SqlServerCe4Provider":
                    Assert.Ignore("Not supported.");
                    break;
                case "EntitySpaces.OracleClientProvider":
                    emp.Query.Select(emp.Query.FirstName.Cast(esCastType.Char, 25).As("CastColumn"));
                    Assert.IsTrue(emp.Query.Load());

                    //string value = "John";
                    object obj = emp.GetColumn("CastColumn");
                    Assert.AreEqual("System.String", obj.GetType().ToString());
                    //Assert.AreEqual(value, obj);
                    break;
                default:
                    emp.Query.Select((esChar)emp.Query.FirstName.As("CastColumn"));
                    Assert.IsTrue(emp.Query.Load());

                    //string value = "John";
                    obj = emp.GetColumn("CastColumn");
                    Assert.AreEqual("System.String", obj.GetType().ToString());
                    //Assert.AreEqual(value, obj);
                    break;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            checkLogin();
            if (!IsPostBack)
            {
                //find current list of activities and bind to activity drop down list
                List <Activity> activitiesToList = _myExEventManager.FetchActivityList();
                listActivity.DataTextField  = "activityName";
                listActivity.DataValueField = "activityName";
                listActivity.DataSource     = activitiesToList;
                listActivity.DataBind();
            }
            //disable form fields by default on page load
            lblCompletedOn.Visible   = false;
            txtCompletedOn.Visible   = false;
            lblCompletedBy.Visible   = false;
            txtCompletedBy.Visible   = false;
            btnSave.Visible          = false;
            btnMarkCompleted.Visible = false;
            btnMarkRejected.Visible  = false;
            btnMarkPending.Visible   = false;
            btnPurgeEvent.Visible    = false;

            if (Session["selectedEventID"] != null)
            {
                if (!IsPostBack)
                {
                    //extract current event id from session variable
                    int selectedEventID = (int)Session["selectedEventID"];
                    txtEventDate.Text = selectedEventID.ToString();

                    try
                    {
                        //search db for event by event id
                        BusinessObjects.ExEvent selectedExEvent = _myExEventManager.FetchEvent(selectedEventID);
                        try
                        {
                            //search db for employee that event belongs to, then populate form field with employee full name
                            BusinessObjects.Employee selectedEmployee = new BusinessObjects.Employee();
                            selectedEmployee = _myEmployeeManager.FindSingleEmployee(selectedExEvent.employeeID);
                            txtAgent.Text    = selectedEmployee.FirstName + " " + selectedEmployee.LastName;
                        }
                        catch (Exception)
                        {
                        }
                        //obtain info for logged in user
                        //populate remaining form fields with user/event info
                        Employee loggedInEmployee = (Employee)Session["loggedInUser"];
                        txtStatus.Text             = selectedExEvent.statusName;
                        txtSubmissionDate.Text     = selectedExEvent.submissionDate.ToShortDateString();
                        txtEventDate.Text          = (selectedExEvent.eventDate).ToShortDateString();
                        listActivity.SelectedValue = selectedExEvent.activityName;
                        string   eventStartTime = selectedExEvent.startTime;
                        string[] splitStartTime = eventStartTime.Split(delimiterChars);
                        startHour.SelectedValue   = splitStartTime[0];
                        startMinute.SelectedValue = splitStartTime[1];
                        startAMPM.SelectedValue   = splitStartTime[2];

                        string   eventEndTime = selectedExEvent.endTime;
                        string[] splitEndTime = eventEndTime.Split(delimiterChars);
                        endHour.SelectedValue   = splitEndTime[0];
                        endMinute.SelectedValue = splitEndTime[1];
                        endAMPM.SelectedValue   = splitEndTime[2];

                        txtActivityNote.Text = selectedExEvent.activityNote;

                        //if event is completed, show info for completed by user and completed on date
                        if (selectedExEvent.statusName == "Completed")
                        {
                            lblCompletedOn.Visible = true;
                            txtCompletedOn.Visible = true;
                            lblCompletedBy.Visible = true;
                            txtCompletedBy.Visible = true;
                            txtCompletedOn.Text    = (selectedExEvent.completedDate).ToShortDateString();
                            txtCompletedBy.Text    = selectedExEvent.completedBy;
                        }
                        //if the event is pending, and the logged in user is a supervisor or lead, display buttons to complete or reject the event
                        else if (selectedExEvent.statusName == "Pending" && loggedInEmployee.RoleName != "Agent")
                        {
                            btnSave.Visible          = true;
                            btnMarkCompleted.Visible = true;
                            btnMarkRejected.Visible  = true;
                        }
                        //if the event is rejected, and the logged in user is a supervisor or lead, display buttons to purge the event or revert the status back to pending
                        else if (selectedExEvent.statusName == "Rejected" && loggedInEmployee.RoleName != "Agent")
                        {
                            lblCompletedOn.Visible = true;
                            txtCompletedOn.Visible = true;
                            lblCompletedBy.Visible = true;
                            txtCompletedBy.Visible = true;
                            btnMarkPending.Visible = true;
                            btnPurgeEvent.Visible  = true;
                            txtCompletedOn.Text    = (selectedExEvent.completedDate).ToShortDateString();
                            txtCompletedBy.Text    = selectedExEvent.completedBy;
                        }
                        //if the event is pending, and the user is not a supervisor or lead, only display button to save changes to the event
                        else if (selectedExEvent.statusName == "Pending")
                        {
                            btnSave.Visible = true;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        public void TestSaveSimpleCollection()
        {
            int empKey = -1;
            EmployeeCollection empColl = new EmployeeCollection();
            empColl.es.Connection.Name = "ForeignKeyTest";
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    empColl.LoadAll();
                    emp = empColl.AddNew();
                    emp.LastName = "LastName";
                    emp.FirstName = "FirstName";

                    Order ord = emp.OrderCollectionByEmployeeID.AddNew();
                    ord.CustID = "10001";
                    ord.CustSub = "001";
                    ord.str().OrderDate = "2007-01-01 00:00:00";

                    empColl.Save();
                    empKey = emp.EmployeeID.Value;

                    Assert.AreEqual(1, emp.OrderCollectionByEmployeeID.Count);
                    Assert.AreEqual(emp.EmployeeID.Value, ord.EmployeeID.Value);
                }
            }
            finally
            {
                // Clean up
                emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                if (emp.LoadByPrimaryKey(empKey))
                {
                    OrderCollection ordColl = emp.OrderCollectionByEmployeeID;
                    ordColl.MarkAllAsDeleted();
                    emp.MarkAsDeleted();
                    emp.Save();
                }
            }
        }
        public void CollectionMixedInsUpdDel()
        {
            using (esTransactionScope scope = new esTransactionScope())
            {
                // Setup
                Employee newEmp = new Employee();
                newEmp.es.Connection.Name = "ForeignKeyTest";
                newEmp.LastName = "new";
                newEmp.FirstName = "new";
                newEmp.Save();

                EmployeeCollection coll = new EmployeeCollection();
                coll.es.Connection.Name = "ForeignKeyTest";
                coll.LoadAll();
                Assert.AreEqual(6, coll.Count, "Initial Load");

                // Insert
                Employee emp1 = coll.AddNew();
                emp1.FirstName = "emp1";
                emp1.LastName = "emp1";

                // Update
                Employee emp3 = coll.FindByPrimaryKey(1);
                emp3.LastName = "emp3";

                // Delete
                Employee emp4 = coll.FindByPrimaryKey(newEmp.EmployeeID.Value);
                emp4.MarkAsDeleted();

                coll.Save();

                // Confirm INSERT
                Employee empIns = new Employee();
                empIns.es.Connection.Name = "ForeignKeyTest";
                Assert.IsTrue(empIns.LoadByPrimaryKey(emp1.EmployeeID.Value), "Insert");

                // Confirm UPDATE
                Employee empUpd = new Employee();
                empUpd.es.Connection.Name = "ForeignKeyTest";
                Assert.IsTrue(empUpd.LoadByPrimaryKey(1), "Update");
                Assert.AreEqual("emp3", empUpd.LastName, "UpdateValue");

                // Confirm DELETE
                Employee empDel = new Employee();
                empDel.es.Connection.Name = "ForeignKeyTest";
                Assert.IsFalse(empDel.LoadByPrimaryKey(newEmp.EmployeeID.Value), "Delete");
            }
        }
        public void ErrorsWithContinueTrueNoFailures()
        {
            EmployeeCollection coll = new EmployeeCollection();
            coll.es.Connection.Name = "ForeignKeyTest";
            coll.LoadAll();
            Assert.AreEqual(5, coll.Count, "Initial Load");

            using (esTransactionScope scope = new esTransactionScope())
            {
                // INSERT will succeed
                Employee emp5 = coll.AddNew();
                emp5.FirstName = "First5";
                emp5.LastName = "Last5";

                coll.Save(true);

                Assert.AreEqual(0, coll.Errors.Count(), "ErrorsCount");
                Assert.IsNull(coll.es.DeletedEntities, "DeletedErrors");

                // Confirm only 1 row got INSERTed
                EmployeeCollection coll2 = new EmployeeCollection();
                coll2.es.Connection.Name = "ForeignKeyTest";
                coll2.LoadAll();
                Assert.AreEqual(6, coll2.Count, "Load");

                // Confirm auto-incremeting PKs are brought back
                // and delete the successfully inserted row
                int emp5Id = emp5.EmployeeID.Value;
                Employee emp5Ins = new Employee();
                emp5Ins.es.Connection.Name = "ForeignKeyTest";

                Assert.IsTrue(emp5Ins.LoadByPrimaryKey(emp5Id), "LoadByPK2");
                emp5Ins.MarkAsDeleted();
                emp5Ins.Save();
            }
        }
        public void NestedZeroToManyEntity2()
        {
            //The main Employee
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";
            emp.Query.Where(emp.Query.EmployeeID == 1);

            // Prefetch Employee Customers by Manager
            CustomerQuery cq1 = emp.Query.Prefetch<CustomerQuery>(
                Employee.Prefetch_CustomerCollectionByManager);
            EmployeeQuery eq1 = cq1.GetQuery<EmployeeQuery>();
            cq1.Where(eq1.EmployeeID == 1);

            // Prefetch Employee Customers Orders (composite FK)
            OrderQuery oq1 = emp.Query.Prefetch<OrderQuery>(
                Employee.Prefetch_CustomerCollectionByManager,
                Customer.Prefetch_OrderCollectionByCustID);
            EmployeeQuery eq2 = oq1.GetQuery<EmployeeQuery>();
            oq1.Where(eq2.EmployeeID == 1);

            // Prefetch Employee Customers Orders OrderItems
            OrderItemQuery oiq1 = emp.Query.Prefetch<OrderItemQuery>(
                Employee.Prefetch_CustomerCollectionByManager,
                Customer.Prefetch_OrderCollectionByCustID,
                Order.Prefetch_OrderItemCollectionByOrderID);
            EmployeeQuery eq3 = oiq1.GetQuery<EmployeeQuery>();
            oiq1.Where(eq3.EmployeeID == 1);

            // Prefetch Employee Customers by StaffAssigned
            CustomerQuery cq2 = emp.Query.Prefetch<CustomerQuery>(
                Employee.Prefetch_CustomerCollectionByStaffAssigned);
            EmployeeQuery eq4 = cq2.GetQuery<EmployeeQuery>();
            cq2.Where(eq4.EmployeeID == 1);

            emp.Query.Load();

            Assert.AreEqual(1, emp.EmployeeID.Value);
            Assert.AreEqual(35, emp.CustomerCollectionByManager.Count);
            Assert.AreEqual(2, emp.CustomerCollectionByStaffAssigned.Count);
            Assert.AreEqual(0, emp.EmployeeCollectionBySupervisor.Count, "These 2 are not Prefetched");

            foreach (Customer c in emp.CustomerCollectionByManager)
            {
                if (c.CustomerID == "01001" && c.CustomerSub == "001")
                {
                    Assert.AreEqual(3, c.OrderCollectionByCustID.Count);

                    foreach (Order o in c.OrderCollectionByCustID)
                    {
                        if (o.OrderID == 1)
                        {
                            Assert.AreEqual(3, o.OrderItemCollectionByOrderID.Count);
                        }
                    }
                }
            }
        }
		public void TestSave()
		{
            int empKey = -1;
            CustomerGroup custGroup = new CustomerGroup();
            custGroup.es.Connection.Name = "ForeignKeyTest";
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";
            Customer cust = new Customer();
            cust.es.Connection.Name = "ForeignKeyTest";

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    custGroup.GroupID = "XXXXX";
                    custGroup.GroupName = "Test";
                    custGroup.Save();

                    emp.LastName = "LastName";
                    emp.FirstName = "FirstName";

                    cust = emp.CustomerCollectionByStaffAssigned.AddNew();
                    cust.CustomerID = "XXXXX";
                    cust.CustomerSub = "XXX";
                    cust.CustomerName = "Test";
                    cust.str().DateAdded = "2007-01-01 00:00:00";
                    cust.Active = true;
                    cust.Manager = 1;

                    emp.Save();
                    empKey = emp.EmployeeID.Value;

                    Assert.AreEqual(1, emp.CustomerCollectionByStaffAssigned.Count);
                    Assert.AreEqual(emp.EmployeeID.Value, cust.StaffAssigned.Value);
                }
            }
            finally
            {
                // Clean up
                emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                if (emp.LoadByPrimaryKey(empKey))
                {
                    CustomerCollection custColl = emp.CustomerCollectionByStaffAssigned;
                    custColl.MarkAllAsDeleted();
                    emp.MarkAsDeleted();
                    emp.Save();

                }

                custGroup = new CustomerGroup();
                custGroup.es.Connection.Name = "ForeignKeyTest";

                if (custGroup.LoadByPrimaryKey("XXXXX"))
                {
                    custGroup.MarkAsDeleted();
                    custGroup.Save();
                }
            }
		}
		public void TestForeach()
		{
			Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";

            emp.LoadByPrimaryKey(1);

            int i = 0;
            string oldKey = "";
            foreach (Customer cust in emp.CustomerCollectionByManager)
            {
                i++;
                string custKey = cust.CustomerID + cust.CustomerSub;
                Assert.AreNotEqual(oldKey, custKey);
                oldKey = custKey;
            }

            Assert.AreEqual(35, i);
        }
Ejemplo n.º 25
0
        private void createEmployee()
        {
            //check for empty form fields
            if (txtFirstName.Text != "" && txtLastName.Text != "" && txtUsername.Text != "" && txtEmailAddress.Text != "")
            {
                string roleName       = listRole.SelectedValue;
                string departmentName = listDepartment.SelectedValue;
                int    supervisorID   = Convert.ToInt32(listLeader.SelectedValue);
                string firstName      = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtFirstName.Text);
                string lastName       = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtLastName.Text);
                string username       = txtUsername.Text;
                string password1      = txtPassword.Text;
                string password2      = txtPassword2.Text;
                string emailAddress   = txtEmailAddress.Text;
                //make sure passwords match
                if (password1.Equals(password2))
                {
                    if (_myEmployeeManager.isValidPassword(password1) == true)
                    {
                        string pwdHash = _myEmployeeManager.GeneratePasswordHash(password1);
                        try
                        {
                            //retrieve info for reporting supervisor/lead
                            BusinessObjects.Employee currentSup = _myEmployeeManager.FindSingleEmployee(supervisorID);
                            string supervisorFirstName          = currentSup.FirstName;
                            string supervisorLastName           = currentSup.LastName;

                            try
                            {
                                //check to see if username is taken
                                BusinessObjects.Employee checkUsername = _myEmployeeManager.FindEmployee(username);
                                if (checkUsername.Username != null)
                                {
                                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Username already exists');", true);
                                }
                                Response.End();
                            }
                            catch (Exception)
                            {
                            }
                            //create new employee
                            BusinessObjects.Employee newEmployee = new BusinessObjects.Employee();
                            newEmployee.RoleName            = roleName;
                            newEmployee.DepartmentName      = departmentName;
                            newEmployee.SupervisorFirstName = supervisorFirstName;
                            newEmployee.SupervisorLastName  = supervisorLastName;
                            newEmployee.FirstName           = firstName;
                            newEmployee.LastName            = lastName;
                            newEmployee.Username            = username;
                            newEmployee.Password            = pwdHash;
                            newEmployee.EmailAddress        = emailAddress;

                            try
                            {
                                //add new employee to db
                                _myEmployeeManager.AddNewEmployee(newEmployee);
                                Employee         newEmp  = _myEmployeeManager.FindEmployee(newEmployee.Username);
                                ConsultationCard newCard = new ConsultationCard();
                                newCard.EmployeeID = newEmp.EmployeeID;
                                newCard.CommunicationRequestDate = "1/1/1900 12:00:00";
                                newCard.CompetitorsRequestDate   = "1/1/1900 12:00:00";
                                newCard.GoalsRequestDate         = "1/1/1900 12:00:00";
                                newCard.GrowthRequestDate        = "1/1/1900 12:00:00";
                                newCard.HeadcountRequestDate     = "1/1/1900 12:00:00";
                                newCard.MarketRequestDate        = "1/1/1900 12:00:00";
                                newCard.RapportRequestDate       = "1/1/1900 12:00:00";
                                newCard.RecommendedRequestDate   = "1/1/1900 12:00:00";
                                newCard.TermRequestDate          = "1/1/1900 12:00:00";
                                newCard.WebsiteRequestDate       = "1/1/1900 12:00:00";
                                _myConsultationCardManager.CreateConsultationCard(newCard);
                                _myConsultationCardManager.CreateNewCardSheet(newEmp.EmployeeID);
                                try
                                {
                                    //attempt to auto log in new user account
                                    Employee loginEmployee = _myEmployeeManager.FindEmployee(username);
                                    Session["loggedInUser"] = loginEmployee;
                                    //set flag for agentview page to identify a new user was created.
                                    Session["newUser"] = "******";
                                }
                                catch (Exception)
                                {
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        catch (Exception)
                        {
                        }
                        //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('User Created Successfully.');", true);

                        //Employee redirectCheck = Employee(Session["loggedInUser"]);

                        Employee checkRedirect = (Employee)Session["loggedInUser"];

                        if (checkRedirect.RoleName == "Manager")
                        {
                            Response.Redirect("ManagerView.aspx");
                        }
                        else
                        {
                            Response.Redirect("AgentView.aspx");
                        }
                    }
                    else
                    {
                        System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Password must contain at least one uppercase, one lowercase, one number, and one special character.');", true);
                    }
                }
                else
                {
                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Passwords do not match.');", true);
                }
            }
            else
            {
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('All fields required!');", true);
            }
        }
        public void ErrorsWithContinueTrueInsUpdDel()
        {
            EmployeeCollection coll = new EmployeeCollection();
            coll.es.Connection.Name = "ForeignKeyTest";
            coll.LoadAll();
            Assert.AreEqual(5, coll.Count, "Initial Load");

            using (esTransactionScope scope = new esTransactionScope())
            {
                // SQLite does not enforce FK constraints
                // So force a concurrency failure instead
                if (coll.es.Connection.ProviderSignature.DataProviderName
                    == "EntitySpaces.SQLiteProvider")
                {
                    Employee empConcurr = new Employee();
                    empConcurr.es.Connection.Name = "ForeignKeyTest";
                    empConcurr.LoadByPrimaryKey(2);
                    empConcurr.MarkAsDeleted();
                    empConcurr.Save();
                }

                // INSERT will succeed
                Employee emp1 = coll.AddNew();
                emp1.FirstName = "First1";
                emp1.LastName = "Last1";

                // INSERT will fail - LastName required
                Employee emp2 = coll.AddNew();

                // UPDATE will fail - LastName required
                Employee emp3 = coll.FindByPrimaryKey(1);
                emp3.LastName = null;

                // DELETE will fail - FK constraint
                Employee emp4 = coll.FindByPrimaryKey(2);
                emp4.MarkAsDeleted();

                // INSERT will succeed
                Employee emp5 = coll.AddNew();
                emp5.FirstName = "First5";
                emp5.LastName = "Last5";

                coll.Save(true);

                Assert.AreEqual(3, coll.Errors.Count(), "ErrorsCount");
                Assert.IsNotNull(coll.es.DeletedEntities, "DeletedErrors");

                foreach (Employee e in coll.Errors)
                {
                    Assert.IsTrue(e.es.RowError.Length > 0);
                }

                // Confirm only 2 rows got INSERTed
                EmployeeCollection coll2 = new EmployeeCollection();
                coll2.es.Connection.Name = "ForeignKeyTest";
                coll2.LoadAll();
                if (coll.es.Connection.ProviderSignature.DataProviderName
                    == "EntitySpaces.SQLiteProvider")
                {
                    Assert.AreEqual(6, coll2.Count, "Load");
                }
                else
                {
                    Assert.AreEqual(7, coll2.Count, "Load");

                    // Confirm nothing got DELETEd
                    Employee empDel = new Employee();
                    empDel.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsTrue(empDel.LoadByPrimaryKey(2), "Delete");
                }

                // Confirm nothing got UPDATEd
                Employee empUpd = new Employee();
                empUpd.es.Connection.Name = "ForeignKeyTest";
                Assert.IsTrue(empUpd.LoadByPrimaryKey(1));
                Assert.AreEqual("Smith", empUpd.LastName, "Update");

                // Confirm auto-incremeting PKs are brought back
                // and delete the 2 successfully inserted rows
                int emp1Id = emp1.EmployeeID.Value;
                Employee emp1Ins = new Employee();
                emp1Ins.es.Connection.Name = "ForeignKeyTest";

                Assert.IsTrue(emp1Ins.LoadByPrimaryKey(emp1Id), "LoadByPK1");
                emp1Ins.MarkAsDeleted();
                emp1Ins.Save();

                int emp5Id = emp5.EmployeeID.Value;
                Employee emp5Ins = new Employee();
                emp5Ins.es.Connection.Name = "ForeignKeyTest";

                Assert.IsTrue(emp5Ins.LoadByPrimaryKey(emp5Id), "LoadByPK2");
                emp5Ins.MarkAsDeleted();
                emp5Ins.Save();
            }
        }
Ejemplo n.º 27
0
        private void createSupEmployee()
        {
            //check for empty form fields
            if (txtFirstName.Text != "" && txtLastName.Text != "" && txtUsername.Text != "" && txtEmailAddress.Text != "")
            {
                //capture form data
                string roleName       = listRole.SelectedValue;
                string departmentName = listDepartment.SelectedValue;
                string firstName      = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtFirstName.Text);
                string lastName       = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtLastName.Text);
                string username       = txtUsername.Text;
                string password1      = txtPassword.Text;
                string password2      = txtPassword2.Text;
                string emailAddress   = txtEmailAddress.Text;
                //verify passwords match
                if (password1.Equals(password2))
                {
                    //check to make sure password meets min reqs
                    if (_myEmployeeManager.isValidPassword(password1) == true)
                    {
                        //convert password string to md5
                        string pwdHash = _myEmployeeManager.GeneratePasswordHash(password1);
                        try
                        {
                            try
                            {
                                //check to see if username is currently taken
                                BusinessObjects.Employee checkUsername = _myEmployeeManager.FindEmployee(username);
                                if (checkUsername.Username != null)
                                {
                                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Username already exists');", true);
                                }
                                Response.End();
                            }
                            catch (Exception)
                            {
                            }
                            //create new employee object using form data
                            //since role is supervisor, direct leader is not needed
                            //to eliminate need for managers to create accounts for sups to report to, defaulting supervisor direct leader to 'Hosting' 'Support'
                            BusinessObjects.Employee newEmployee = new BusinessObjects.Employee();
                            newEmployee.RoleName            = roleName;
                            newEmployee.DepartmentName      = departmentName;
                            newEmployee.SupervisorFirstName = "Hosting";
                            newEmployee.SupervisorLastName  = "Support";
                            newEmployee.FirstName           = firstName;
                            newEmployee.LastName            = lastName;
                            newEmployee.Username            = username;
                            newEmployee.Password            = pwdHash;
                            newEmployee.EmailAddress        = emailAddress;

                            try
                            {
                                //add new employee to db
                                _myEmployeeManager.AddNewEmployee(newEmployee);
                                try
                                {
                                    //attempt to auto log in new user account
                                    Employee loginEmployee = _myEmployeeManager.FindEmployee(username);
                                    Session["loggedInUser"] = loginEmployee;
                                    //set flag for agentview page to identify a new user was created
                                    Session["newUser"] = "******";
                                }
                                catch (Exception)
                                {
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        catch (Exception)
                        {
                        }
                        System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('User Created Successfully.');", true);
                        Employee checkRedirect = (Employee)Session["loggedInUser"];

                        if (checkRedirect.RoleName == "Manager")
                        {
                            Response.Redirect("ManagerView.aspx");
                        }
                        else
                        {
                            Response.Redirect("AgentView.aspx");
                        }
                    }
                    else
                    {
                        System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Password must contain at least one uppercase, one lowercase, one number, and one special character.');", true);
                    }
                }
                else
                {
                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Passwords do not match.');", true);
                }
            }
            else
            {
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('All fields required!');", true);
            }
        }
        public void TestMultiDeleteEntity()
        {
            int empKey = -1;
            int ordKey = -1;
            CustomerGroup custGroup = new CustomerGroup();
            custGroup.es.Connection.Name = "ForeignKeyTest";
            EmployeeCollection empColl = new EmployeeCollection();
            empColl.es.Connection.Name = "ForeignKeyTest";
            Employee emp = new Employee();
            emp.es.Connection.Name = "ForeignKeyTest";
            Employee testEmp = new Employee();
            testEmp.es.Connection.Name = "ForeignKeyTest";
            Customer cust = new Customer();
            cust.es.Connection.Name = "ForeignKeyTest";
            Order ord = new Order();
            ord.es.Connection.Name = "ForeignKeyTest";

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    // Setup
                    custGroup.GroupID = "YYYYY";
                    custGroup.GroupName = "Test";
                    custGroup.Save();

                    emp = empColl.AddNew();
                    emp.LastName = "LastName";
                    emp.FirstName = "FirstName";

                    cust = emp.CustomerCollectionByStaffAssigned.AddNew();
                    cust.CustomerID = "YYYYY";
                    cust.CustomerSub = "YYY";
                    cust.CustomerName = "Test";
                    cust.str().DateAdded = "2007-01-01 00:00:00";
                    cust.Active = true;
                    cust.Manager = 1;

                    ord = emp.OrderCollectionByEmployeeID.AddNew();
                    ord.CustID = "YYYYY";
                    ord.CustSub = "YYY";
                    ord.str().OrderDate = "2007-01-01";

                    empColl.Save();
                    empKey = emp.EmployeeID.Value;
                    ordKey = ord.OrderID.Value;

                    Assert.AreEqual(1, emp.CustomerCollectionByStaffAssigned.Count);
                    Assert.AreEqual(1, emp.OrderCollectionByEmployeeID.Count);
                    Assert.AreEqual(emp.EmployeeID.Value, cust.StaffAssigned.Value);
                    Assert.AreEqual(emp.EmployeeID.Value, ord.EmployeeID.Value);

                    // Test
                    testEmp.LoadByPrimaryKey(empKey);
                    testEmp.OrderCollectionByEmployeeID.MarkAllAsDeleted();
                    testEmp.CustomerCollectionByStaffAssigned.MarkAllAsDeleted();
                    testEmp.MarkAsDeleted();
                    testEmp.Save();

                    emp = new Employee();
                    emp.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsFalse(emp.LoadByPrimaryKey(empKey));

                    ord = new Order();
                    ord.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsFalse(ord.LoadByPrimaryKey(ordKey));

                    cust = new Customer();
                    cust.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsFalse(cust.LoadByPrimaryKey("YYYYY", "YYY"));
                }
            }
            finally
            {
                // Clean up
                ord = new Order();
                ord.es.Connection.Name = "ForeignKeyTest";
                if (ord.LoadByPrimaryKey(ordKey))
                {
                    ord.MarkAsDeleted();
                    ord.Save();
                }

                cust = new Customer();
                cust.es.Connection.Name = "ForeignKeyTest";
                if (cust.LoadByPrimaryKey("YYYYY", "YYY"))
                {
                    cust.MarkAsDeleted();
                    cust.Save();
                }

                emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";
                if (emp.LoadByPrimaryKey(empKey))
                {
                    emp.MarkAsDeleted();
                    emp.Save();
                }

                custGroup = new CustomerGroup();
                custGroup.es.Connection.Name = "ForeignKeyTest";

                if (custGroup.LoadByPrimaryKey("YYYYY"))
                {
                    custGroup.MarkAsDeleted();
                    custGroup.Save();
                }
            }
        }
        public void CastToDateTime()
        {
            int empId = 0;

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    // Create an employee with a date in the LastName column
                    Employee emp = new Employee();
                    emp.es.Connection.Name = "ForeignKeyTest";

                    switch (emp.es.Connection.ProviderSignature.DataProviderName)
                    {
                        case "EntitySpaces.OracleClientProvider":
                            emp.LastName = "31-DEC-2008 01:01:01";
                            break;
                        default:
                            emp.LastName = "2008-12-31";
                            break;
                    }
                    emp.FirstName = "required";
                    emp.Save();

                    empId = emp.EmployeeID.Value;

                    emp = new Employee();
                    emp.es.Connection.Name = "ForeignKeyTest";

                    emp.Query.Select((esDateTime)emp.Query.LastName.As("CastColumn"));
                    emp.Query.Where(emp.Query.EmployeeID == empId);

                    switch (emp.es.Connection.ProviderSignature.DataProviderName)
                    {
                        //case "EntitySpaces.MySqlClientProvider":
                        //case "EntitySpaces.NpgsqlProvider":
                        //case "EntitySpaces.Npgsql2Provider":
                        //case "EntitySpaces.VistaDBProvider":
                        case "EntitySpaces.MSAccessProvider":
                        case "EntitySpaces.SQLiteProvider":
                        //case "EntitySpaces.SqlServerCeProvider":
                            Assert.Ignore("Not supported.");
                            break;
                        case "EntitySpaces.OracleClientProvider":
                            string lq = emp.Query.Parse();
                            Assert.IsTrue(emp.Query.Load());

                            DateTime value = DateTime.Parse("2008-12-31 01:01:01");
                            object obj = emp.GetColumn("CastColumn");
                            Assert.AreEqual("System.DateTime", obj.GetType().ToString());
                            Assert.AreEqual(value, obj);
                            break;
                        default:
                            lq = emp.Query.Parse();
                            Assert.IsTrue(emp.Query.Load());

                            value = DateTime.Parse("2008-12-31");
                            obj = emp.GetColumn("CastColumn");
                            Assert.AreEqual("System.DateTime", obj.GetType().ToString());
                            Assert.AreEqual(value, obj);
                            break;
                    }
                }
            }
            finally
            {
                Employee emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";

                emp.Query.Where(emp.Query.EmployeeID == empId);
                if (emp.Query.Load())
                {
                    emp.MarkAsDeleted();
                    emp.Save();
                }
            }               
        }
        public void SaveAlternateConnection()
        {
            Employee emp = new Employee();
            int empId = -1;

            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    emp = new Employee();
                    emp.es.Connection.Name = "ForeignKeyTest";

                    emp.LastName = "McTest";
                    emp.FirstName = "Testy";
                    emp.Age = 30;
                    emp.Save();
                    empId = emp.EmployeeID.Value;

                    emp = new Employee();
                    emp.es.Connection.Name = "ForeignKeyTest";
                    Assert.IsTrue(emp.LoadByPrimaryKey(empId));
                    Assert.AreEqual(30, emp.Age.Value);
                }
            }
            finally
            {
                // Clean up
                emp = new Employee();
                emp.es.Connection.Name = "ForeignKeyTest";
                if (emp.LoadByPrimaryKey(empId))
                {
                    emp.MarkAsDeleted();
                    emp.Save();
                }
            }
        }