/// <summary>
        /// Approve single requisition and persist with database
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public void ApproveRequisition(Requisition requisition)
        {
            try
            {
                if (ValidateRequisition(requisition, RequisitionMethod.Approve))
                {
                    requisitionDAO.ApproveRequisition(requisition);
                }
                else
                {
                    ErrorMessage("Approval of Requisition Failed");
                }
            }
            catch (Exception)
            {

                throw new ApprovalException("Approval Failed.");
            }
        }
        /// <summary>
        /// Approval of the requisition
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public void ApproveRequisition(Requisition requisition)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    var tempRequisition = (from p in context.Requisitions
                                           where p.RequisitionID == requisition.RequisitionID
                                           select p).FirstOrDefault<Requisition>();

                    var status = (from s in context.Statuses where s.Name == "Approved & Pending" select s).FirstOrDefault<Status>();

                    //requisition status will be changed to "Approved & Pending"
                    UpdateRequisitionStatus(tempRequisition, status);
                    context.SaveChanges();
                    ts.Complete();
                }
            }
            catch (Exception)
            {
                throw new RequisitionException("Approval Failed.");
            }
        }
        /// <summary>
        /// Cancel the requisition before approval
        /// </summary>
        /// <param name="cancelRequisition">requisition object</param>
        public void CancelRequisition(Requisition cancelRequisition)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    var tempRequisition = (from p in context.Requisitions
                                           where p.RequisitionID == cancelRequisition.RequisitionID
                                           select p).FirstOrDefault<Requisition>();

                    var status = (from s in context.Statuses where s.Name == "Cancel" select s).FirstOrDefault<Status>();

                    UpdateRequisitionStatus(tempRequisition, status);
                    context.SaveChanges();
                    ts.Complete();
                }
            }
            catch (Exception)
            {

                throw new RequisitionException("Approval Failed");
            }
        }
 /// <summary>
 /// Cancel a new requisition and persist with database
 /// </summary>
 /// <param name="requisition">requisition object</param>
 public void CancelRequisition(Requisition requisition)
 {
     if (ValidateRequisition(requisition, RequisitionMethod.Cancel))
     {
         requisitionDAO.CancelRequisition(requisition);
     }
     else
     {
         ErrorMessage("Cancel Requisition Failed.");
     }
 }
        /// <summary>
        /// Create a new requisition and persist with database
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public void CreateRequisition(Requisition requisition)
        {
            try
            {
                //Create a transaction scope
                using (TransactionScope ts = new TransactionScope())
                {
                    if (requisition != null)
                    {
                        //Add requisition to context
                        context.AddToRequisitions(requisition);

                        //Save the changes
                        context.SaveChanges();

                        //Notify Transaction completed
                        ts.Complete();
                    }
                }

            }
            catch (Exception ex)
            {
                //Exception thrown incase if insert fails
                throw new RequisitionException("Create requisition failed." +ex.Message);

            }
        }
 /// <summary>
 /// Update requisition status and persist with database
 /// </summary>
 /// <param name="requisition">requisition object</param>
 /// <param name="status">status object</param>
 public void UpdateRequisitionStatus(Requisition requisition, Status status)
 {
     if (ValidateRequisition(requisition, RequisitionMethod.UpdateStatus))
     {
         requisitionDAO.UpdateRequisitionStatus(requisition, status);
     }
 }
        /// <summary>
        /// Validate Requisition
        /// </summary>
        /// <param name="requisition">Requisition object</param>
        /// <param name="requisitionMethod">enum requisitionMethod</param>
        /// <returns>boolean</returns>
        private bool ValidateRequisition(Requisition requisition, RequisitionMethod requisitionMethod)
        {
            try
            {
                if (requisition != null)
                {
                    if (requisitionMethod == RequisitionMethod.Create)
                    {

                        if ((requisition.CreatedBy != 0 || requisition.CreatedByUser != null) &&
                            (requisition.DepartmentID != 0 || requisition.Department != null) &&
                            (requisition.RequisitionForm != string.Empty || requisition.RequisitionForm != null) &&
                            (requisition.StatusID != 0 || requisition.Status != null) &&
                            (requisition.UrgencyID != 0 || requisition.Urgency != null) &&
                            (requisition.DateRequested != null && requisition.DateRequested.Date.ToShortDateString() == DateTime.Now.Date.ToShortDateString()) &&
                            (requisition.ApprovedByUser == null) && (requisition.DateApproved == null))
                        {
                            return true;
                        }

                    }
                    if (requisitionMethod == RequisitionMethod.Update)
                    {

                        if ((requisition.CreatedBy != 0 || requisition.CreatedByUser != null) &&
                           (requisition.DepartmentID != 0 || requisition.Department != null) &&
                           (requisition.RequisitionForm != string.Empty || requisition.RequisitionForm != null) &&
                           (requisition.StatusID == 2 || requisition.Status != null) &&
                           (requisition.UrgencyID != 0 || requisition.Urgency != null) &&
                           (requisition.DateRequested != null && requisition.DateRequested.Date.ToShortDateString() != string.Empty) &&
                           (requisition.ApprovedBy != 0))
                        {
                            return true;
                        }
                        else
                        {
                            try
                            {
                                throw new RequisitionException("Update Requisition Failed");
                            }
                            catch (Exception)
                            {

                                throw;
                            }

                        }
                    }

                    if (requisitionMethod == RequisitionMethod.UpdateStatus)
                    {
                        if (requisition.RequisitionID != 0)
                        {
                            return true;
                        }
                    }

                    if (requisitionMethod == RequisitionMethod.Approve || requisitionMethod == RequisitionMethod.Reject)
                    {
                        if (requisition.ApprovedBy != 0 && requisition.ApprovedByUser.Role.Contains("DepartmentHeads"))
                        {
                            return true;
                        }
                    }

                    if (requisitionMethod == RequisitionMethod.Cancel)
                    {
                        if (requisition.ApprovedBy == 0 || requisition.ApprovedBy == null)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception)
            {
                throw new RequisitionException("Create Requisition failed. Please try again later");
            }
        }
        /// <summary>
        /// 
        /// Update the requisition before approval
        /// </summary>
        /// <param name="updateRequisition">requisition object</param>
        public void UpdateRequisition(Requisition updateRequisition)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    var tempReq = (from r in context.Requisitions
                                   where r.RequisitionID == updateRequisition.RequisitionID
                                   select r).FirstOrDefault<Requisition>();

                    tempReq = updateRequisition;
                    context.SaveChanges();
                    ts.Complete();
                }
            }
            catch (Exception ex)
            {
                throw new RequisitionException("Update requisition failed." + ex.Message);
            }
        }
        protected void PopulateData(Requisition requisition)
        {
            List<RequisitionItem> reqItems = null;
            List<SpecialRequisitionItem> splReqItems = null;
            if (requisition.RequisitionID > 0)
            {
                reqItems = requisitionManager.GetAllRequisitionItems(requisition);
                splReqItems = requisitionManager.GetAllSpecialRequisitionItems(requisition);

                if (reqItems.Count > 0)
                {
                    RequestItemGridView.DataSource = reqItems;
                    RequestItemGridView.DataKeyNames = new string[] { "RequisitionItemID" };
                }

                if (splReqItems.Count > 0)
                {
                    SpecialRequestItemGridView.DataSource = splReqItems;
                    SpecialRequestItemGridView.DataKeyNames = new string[] { "SpecialStationeryID" };
                }

                DetailsView1.DataSource = reqItems;
                DetailsView2.DataSource = splReqItems;
                DataBind();
            }

            if (requisition.RequisitionID == 0)
            {
                reqItems = requisition.RequisitionItems.ToList<RequisitionItem>();
                splReqItems = requisition.SpecialRequisitionItems.ToList<SpecialRequisitionItem>();

                if (reqItems.Count > 0)
                {
                    RequestItemGridView.DataSource = reqItems;
                    RequestItemGridView.DataKeyNames = new string[] { "RequisitionItemID" };

                }

                if (splReqItems.Count > 0)
                {
                    SpecialRequestItemGridView.DataSource = splReqItems;

                }
                DetailsView1.DataSource = reqItems;
            }
        }
        /// <summary>
        /// Get All special RequisitionItems in the requisition form
        /// </summary>
        /// <param name="requisition"></param>
        /// <returns></returns>
        public List<SpecialRequisitionItem> GetAllSpecialRequisitionItems(Requisition requisition)
        {
            try
            {
                return (from ri in context.SpecialRequisitionItems
                        where ri.RequisitionID == requisition.RequisitionID
                        select ri).ToList<SpecialRequisitionItem>();
            }
            catch (Exception)
            {

                throw;
            }
        }
 /// <summary>
 /// Generate the requisitionID for each requisition
 /// </summary>
 /// <param name="requisition">requisition object</param>
 /// <returns>string</returns>
 public string GetRequisitionNumber(Requisition requisition)
 {
     var department = (from d in context.Departments where d.DepartmentID == requisition.DepartmentID select d).FirstOrDefault<Department>();
     var riList = (from r in context.Requisitions where r.DepartmentID == department.DepartmentID select r).ToList<Requisition>();
     int count;
     if (riList.Count == 0)
     {
         count = 0;
     }
     else
     {
         Requisition ri = riList.Last<Requisition>();
         String[] temp = ri.RequisitionForm.Split('/');
         count = Convert.ToInt32(temp[1]);
     }
     return department.Code + "/" + String.Format("{0:0000}", (++count)) + "/" + DateTime.Now.ToString("yy");
 }
        /// <summary>
        /// Get All RequisitionItems in the requisition form
        /// </summary>
        /// <param name="requisition"></param>
        /// <returns></returns>
        public List<RequisitionItem> GetAllRequisitionItems(Requisition requisition)
        {
            try
            {
                List<RequisitionItem> temp = requisitionDAO.GetAllRequisitionItems(requisition);
                if (temp != null)
                    return temp;

                ErrorMessage("Result Not Found");
                return null;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// Get All special RequisitionItems in the requisition form
        /// </summary>
        /// <param name="requisition"></param>
        /// <returns></returns>
        public List<SpecialRequisitionItem> GetAllSpecialRequisitionItems(Requisition requisition)
        {
            try
            {
                List<SpecialRequisitionItem> temp = requisitionDAO.GetAllSpecialRequisitionItems(requisition);
                if (temp != null)
                {
                    return temp;
                }
                else
                {
                    ErrorMessage("Result not found");
                    return null;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// Create a new requisition and persist with database
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public Requisition CreateRequisition(Requisition requisition)
        {
            try
            {
                bool isTestOK = false;
                StatusSearchDTO sdto = new StatusSearchDTO() { Name = "Pending" };
                Status status = requisitionDAO.GetStatusByName(sdto);
                requisition.StatusID = status.StatusID;

                if (ValidateRequisition(requisition, RequisitionMethod.Create))
                {
                    if (requisition.RequisitionItems.Count > 0 || requisition.SpecialRequisitionItems.Count > 0)
                    {
                        foreach (RequisitionItem requisitionItem in requisition.RequisitionItems)
                        {
                            isTestOK = ValidateRequisitionItem(requisitionItem, RequisitionMethod.Create);
                            if (!isTestOK)
                            {
                                break;
                            }
                        }
                        foreach (SpecialRequisitionItem specialRequisitionItem in requisition.SpecialRequisitionItems)
                        {
                            isTestOK = ValidateSpecialRequisitionItem(specialRequisitionItem, RequisitionMethod.Create);

                            if (!isTestOK)
                            {
                                break;
                            }
                        }
                    }

                    if (isTestOK)
                    {

                        requisitionDAO.CreateRequisition(requisition);
                        return requisition;
                    }

                    else
                    {
                        ErrorMessage("Create Requisition Failed. Please check the input.");
                    }
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return null;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Create instance of new requisition
            Requisition r = new Requisition();

            UserDAO user = new UserDAO();
            RequisitionManager rq = new RequisitionManager();
            CatalogDAO cat = new CatalogDAO();

            //set the properties of requisition object
            r.DepartmentID = user.GetDepartmentByID(1).DepartmentID;
            r.CreatedBy = user.GetUserByID(1).UserID;
            r.StatusID = rq.GetStatusByID(new Status() { StatusID = 1}).StatusID;
            r.ApprovedBy = user.GetUserByID(2).UserID;
            r.UrgencyID = rq.GetUrgencyByID(new Urgency() { UrgencyID = 1 }).UrgencyID;
            r.RequisitionForm = "test";
            r.DateRequested = DateTime.Now;
            //r.DateApproved = DateTime.Now;

            //Create a new requisitionitem for the current requisition
            RequisitionItem rqi = new RequisitionItem()
            {
                RequisitionID = r.RequisitionID,
                StationeryID = cat.GetAllStationeries().FirstOrDefault<Stationery>().StationeryID,
                QuantityRequested = 10,
                QuantityIssued = 10,
                Price = 5

            };

            //Create a new specialrequisitionitem for the current requisition
            SpecialRequisitionItem spi = new SpecialRequisitionItem()
            {
                RequisitionID = r.RequisitionID,
                SpecialStationeryID = 1,
                QuantityRequested = 10,
                QuantityIssued = 10,
                Price = 5,
                Name = "arav",
                Description = "test"

            };

            //Add Child objects of the requisition objects
            //Add requisitionitem to requisition object
            r.RequisitionItems.Add(rqi);

            //Add specialitem to requisition object
            r.SpecialRequisitionItems.Add(spi);

            //Persist requisition to database
            //EF is very intelligent. It will also persist to requistionitem and specialrequistionitem
            rq.CreateRequisition(r);

            r = rq.GetAllRequisition().Last<Requisition>();
            r.RequisitionItems.Last<RequisitionItem>().QuantityIssued = 6;

            rq.UpdateRequisition(r);

            spi = rq.GetAllSpecialRequisitionItems(r).Last<SpecialRequisitionItem>();

            rq.DeleteSpecialRequisitionItem(spi);

            //Testing databinding after creation of requisitions
            if (!IsPostBack)
            {
                GridView1.DataSource = rq.GetAllRequisitionItems(r);
                GridView1.DataBind();

                if (r != null)
                {
                    GridView2.DataSource = rq.GetAllRequisition();
                    GridView2.DataBind();
                }
            }
        }
 /// <summary>
 /// Deprecated Method for adding a new object to the Requisitions EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToRequisitions(Requisition requisition)
 {
     base.AddObject("Requisitions", requisition);
 }
 /// <summary>
 /// Create a new Requisition object.
 /// </summary>
 /// <param name="requisitionID">Initial value of the RequisitionID property.</param>
 /// <param name="createdBy">Initial value of the CreatedBy property.</param>
 /// <param name="departmentID">Initial value of the DepartmentID property.</param>
 /// <param name="requisitionForm">Initial value of the RequisitionForm property.</param>
 /// <param name="statusID">Initial value of the StatusID property.</param>
 /// <param name="urgencyID">Initial value of the UrgencyID property.</param>
 /// <param name="dateRequested">Initial value of the DateRequested property.</param>
 public static Requisition CreateRequisition(global::System.Int32 requisitionID, global::System.Int32 createdBy, global::System.Int32 departmentID, global::System.String requisitionForm, global::System.Int32 statusID, global::System.Int32 urgencyID, global::System.DateTime dateRequested)
 {
     Requisition requisition = new Requisition();
     requisition.RequisitionID = requisitionID;
     requisition.CreatedBy = createdBy;
     requisition.DepartmentID = departmentID;
     requisition.RequisitionForm = requisitionForm;
     requisition.StatusID = statusID;
     requisition.UrgencyID = urgencyID;
     requisition.DateRequested = dateRequested;
     return requisition;
 }
        private Requisition CreateRequisition()
        {
            Requisition req = new Requisition();
            User currentUser = Utilities.Membership.GetCurrentLoggedInUser();
            req.DepartmentID = currentUser.DepartmentID;
            req.DateRequested = DateTime.Now.Date;
            req.CreatedBy = currentUser.UserID;
            req.RequisitionForm = requisitionManager.GetRequisitionNumber(req);

            return req;
        }
 /// <summary>
 /// Get Requisition by primary key
 /// </summary>
 /// <param name="requisition">requisition object</param>
 /// <returns>requisition object</returns>
 public Requisition GetRequisitionByID(Requisition requisition)
 {
     try
     {
         return GetAllRequisition().Where(r => r.RequisitionID == requisition.RequisitionID).FirstOrDefault<Requisition>();
     }
     catch (Exception)
     {
         throw;
     }
 }
 /// <summary>
 /// Generate the requisitionID for each requisition
 /// </summary>
 /// <param name="requisition"></param>
 /// <returns></returns>
 public string GetRequisitionNumber(Requisition requisition)
 {
     return requisitionDAO.GetRequisitionNumber(requisition);
 }
        /// <summary>
        /// Reject single requisition and persist with database
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public void RejectRequisition(Requisition requisition)
        {
            try
            {
                if (ValidateRequisition(requisition, RequisitionMethod.Reject))
                {
                    requisitionDAO.RejectRequisition(requisition);
                }
                else
                {
                    ErrorMessage("Rejection of Requisition Failed");
                }
            }
            catch (Exception)
            {

                throw new ApprovalException("Rejection Failed for all requisitions.");
            }
        }
        /// <summary>
        /// Update requisition and persist with database
        /// </summary>
        /// <param name="requisition">requisition object</param>
        public void UpdateRequisition(Requisition requisition)
        {
            try
            {
                        requisitionDAO.UpdateRequisition(requisition);
                //bool isTrue = false;
                //if (ValidateRequisition(requisition, RequisitionMethod.Update))
                //{
                //    foreach (RequisitionItem item in requisition.RequisitionItems)
                //    {
                //        isTrue = ValidateRequisitionItem(item, RequisitionMethod.Update);
                //        if (!isTrue)
                //        {
                //            break;
                //        }
                //    }
                //    foreach (SpecialRequisitionItem splItem in requisition.SpecialRequisitionItems)
                //    {
                //        isTrue = ValidateSpecialRequisitionItem(splItem, RequisitionMethod.Update);
                //        if (!isTrue)
                //        {
                //            break;
                //        }
                //    }

                //    if (isTrue)
                //    {
                //    }
                //    else
                //    {
                //        ErrorMessage("Update Requisition Failed");
                //    }
                //}
            }
            catch (Exception)
            {

                throw;
            }
        }
 /// <summary>
 /// Update the requisition status
 /// </summary>
 /// <param name="requisition">requistion object</param>
 /// <param name="status">status object</param>
 public void UpdateRequisitionStatus(Requisition requisition, Status status)
 {
     try
     {
         requisition.StatusID = status.StatusID;
         requisition.DateApproved = DateTime.Now;
     }
     catch (Exception)
     {
         throw new RequisitionException("Update failed.");
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            requisitionManager = new RequisitionManager();
            cManager = new CatalogManager();
            CancelButton.Visible = false;
            if (!IsPostBack)
            {
                UrgencyDDL.DataSource = requisitionManager.GetAllUrgencies();
                UrgencyDDL.DataTextField = "Name";
                UrgencyDDL.DataValueField = "UrgencyID";
                DataBind();

                foreach (ListItem item in UrgencyDDL.Items)
                {
                    if (item.Text == "Normal")
                    {
                        item.Selected = true;
                    }
                }
                requisition = CreateRequisition();
                Session["Requisition"] = requisition;
            }

            if (Session["Requisition"] != null)
            {
                requisition = (Requisition)Session["Requisition"];
            }

            string key = string.Empty;
            int val = 0;
            NameValueCollection nv = Request.QueryString;
            if (nv.HasKeys())
            {
                key = nv.GetKey(0);
                try
                {
                    val = Convert.ToInt32(nv.Get(0));
                }
                catch (Exception)
                {

                }

            }
            if (key == "RequestID" && val > 0)
            {
                requisition = requisitionManager.GetRequisitionByID(val);

                if (requisition != null)
                {
                    Panel1.Visible = false;
                    Panel2.Visible = false;
                    RequestItemGridView.Columns[0].Visible = false;
                    RequestItemGridView.Columns[1].Visible = false;
                    SpecialRequestItemGridView.Columns[0].Visible = false;
                    Panel4.Visible = false;
                    SubmitButton.Visible = false;
                    if (requisition.Status.Name == "Pending")
                    {
                        CancelButton.Visible = true;
                    }
                    GridDataBind();
                }
            }
        }