/// <summary>
 /// Insert Assignment Information
 /// </summary>
 /// <param name="data">Assignment Information</param>
 /// <returns>Number Affected Row</returns>
 public static Tuple <ErrorObject, int> Assignment(tblAssignment data)
 {
     erros = new ErrorObject();
     try
     {
         using (EileenGaldamezEntities db = new EileenGaldamezEntities())
         {
             int propertyFind = db.tblAssignment.Count();
             if (propertyFind > 0)
             {
                 data.id = db.tblAssignment.Max(s => s.id);
             }
             else
             {
                 data.id = 1;
             }
             db.tblAssignment.Add(data);
             result  = db.SaveChanges();
             Message = "Affected Row: " + result.ToString();
             return(new Tuple <ErrorObject, int>(erros.IfError(false), data.id));
         }
     }
     catch (Exception ex)
     {
         erros.InfoError(ex);
         return(new Tuple <ErrorObject, int>(erros, 0));
     }
 }
        protected void rAssignment_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            MultiView mv = e.Item.FindControl("mvToggle") as MultiView;

            mv.ActiveViewIndex = 0;

            Label label        = e.Item.FindControl("lblAssignmentID") as Label;
            int   assignmentID = Convert.ToInt32(label.Text);

            using (DatabaseDataContext db = new DatabaseDataContext())
            {
                tblAssignment assignment = db.tblAssignments.Where(x => x.assignmentID == assignmentID).FirstOrDefault();
                LinkButton    linkButton = e.Item.FindControl("btnDownloadFiles") as LinkButton;

                if (assignment.fileName == null)
                {
                    linkButton.Visible = false;
                }

                if (assignment.assignmentEndDate > DateTime.Now)
                {
                    Button button = e.Item.FindControl("btnArchive") as Button;
                    button.Enabled = false;

                    button         = e.Item.FindControl("btnGrade") as Button;
                    button.Enabled = false;
                }
            }
        }
            /// <summary>
            /// Return All Assingnment To specific Product, category, Codition and TransactionType IDS
            /// </summary>
            /// <param name="ProductID"></param>
            /// <param name="CategoryID"></param>
            /// <param name="ConditionID"></param>
            /// <param name="TransactionTypeID"></param>
            /// <returns>All Assignment</returns>
            public static Tuple <ErrorObject, tblAssignment> GetAssignmentByProductIDAndCategoryWithCondition(int ProductID, int CategoryID, int ConditionID, int TransactionTypeID)
            {
                tblAssignment data = new tblAssignment();

                erros = new ErrorObject();

                try
                {
                    using (EileenGaldamezEntities db = new EileenGaldamezEntities())
                    {
                        data = (from TC in db.tblTransactionConfigurate
                                join A in db.tblAssignment on TC.idAnchorTransaction equals A.id
                                join T in db.tblTransaction on TC.idTransaction equals T.id
                                where A.idProduct == ProductID && TC.idTransactionType == TransactionTypeID && T.idConditionProduct == ConditionID
                                select A).First();
                    }
                    erros.Error = false;
                    return(new Tuple <ErrorObject, tblAssignment>(erros.IfError(false), data));
                }
                catch (Exception ex)
                {
                    erros.InfoError(ex);
                    return(new Tuple <ErrorObject, tblAssignment>(erros, data));
                }
            }
        private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            assignmentid = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
            tblAssignment tb = db.tblAssignments.Where(a => a.AssignmentId == assignmentid).FirstOrDefault();

            cboSubjectId.Text     = tb.tblSubject.SubjectName;
            dateTimePicker1.Value = Convert.ToDateTime(tb.ReleaseDate);
            dateTimePicker2.Value = Convert.ToDateTime(tb.SubmissionDate);
            txtRemarks.Text       = tb.Remarks;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            tblAssignment tb = db.tblAssignments.Where(a => a.AssignmentId == assignmentid).FirstOrDefault();

            db.tblAssignments.Remove(tb);
            if (db.SaveChanges() > 0)
            {
                MessageBox.Show("Assignment Deleted");
                LoadGrid();
                ClearData();
            }
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            tblAssignment tb = db.tblAssignments.Where(a => a.AssignmentId == assignmentid).FirstOrDefault();

            tb.SubjectId      = Convert.ToInt32(cboSubjectId.SelectedValue);
            tb.ReleaseDate    = dateTimePicker1.Value;
            tb.SubmissionDate = dateTimePicker2.Value;
            tb.Remarks        = txtRemarks.Text;
            if (db.SaveChanges() > 0)
            {
                MessageBox.Show("Assignment Updated");
                LoadGrid();
                ClearData();
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            tblAssignment tb = new tblAssignment();

            tb.SubjectId      = Convert.ToInt32(cboSubjectId.SelectedValue);
            tb.ReleaseDate    = dateTimePicker1.Value;
            tb.SubmissionDate = dateTimePicker2.Value;
            tb.Remarks        = txtRemarks.Text;
            db.tblAssignments.Add(tb);
            if (db.SaveChanges() > 0)
            {
                MessageBox.Show("Assignment Added");
                LoadGrid();
                ClearData();
            }
        }
            private static GetAssignmentResponse Assignments(GetAssignmentResponse request)
            {
                GetAssignmentResponse response = new GetAssignmentResponse();

                response.Error = new Handler.ErrorObject();

                try
                {
                    tblAssignment bussines = new tblAssignment()
                    {
                        id         = request.Assignment.id,
                        amount     = request.Assignment.amount,
                        loan       = request.Assignment.loan,
                        idProduct  = request.Assignment.idProduct,
                        idEmployee = request.Assignment.idEmployee,
                        detail     = request.Assignment.detail,
                        max        = request.Assignment.Max,
                        min        = request.Assignment.Min,
                        idCategory = request.Assignment.idCategory,
                        createDate = request.Assignment.createDate,
                        upDateDate = null,
                        deleteDate = null,
                        state      = "Active"
                    };

                    var result = AssignmentData.Insert.Assignment(bussines);
                    if (result.Item1.Error)
                    {
                        response.Error.InfoError(result.Item1);
                    }
                    else
                    {
                        response.Message = result.Item2.ToString();
                    }
                }
                catch (Exception ex)
                {
                    response.Error.InfoError(ex);
                }

                return(response);
            }
            /// <summary>
            /// Return Assignment By Specific ID
            /// </summary>
            /// <param name="id">Assignment ID</param>
            /// <returns>Assignment By Specific ID Or null If Exist Error</returns>
            public static Tuple <ErrorObject, tblAssignment> GetAssignment(int id)
            {
                tblAssignment data = new tblAssignment();

                erros = new ErrorObject();

                try
                {
                    using (EileenGaldamezEntities db = new EileenGaldamezEntities())
                    {
                        data = db.tblAssignment.Find(id);
                    }
                    erros.Error = false;
                    return(new Tuple <ErrorObject, tblAssignment>(erros.IfError(false), data));
                }
                catch (Exception ex)
                {
                    erros.InfoError(ex);
                    return(new Tuple <ErrorObject, tblAssignment>(erros, data));
                }
            }
            /// <summary>
            /// Return All Assingnment To specific Product, category IDS
            /// </summary>
            /// <param name="ProductID"></param>
            /// <param name="CategoryID"></param>
            /// <returns>All Assignment</returns>
            public static Tuple <ErrorObject, tblAssignment> GetAssignmentByProductIDAndCategoryID(int ProductID, int CategoryID)
            {
                tblAssignment data = new tblAssignment();

                erros = new ErrorObject();

                try
                {
                    using (EileenGaldamezEntities db = new EileenGaldamezEntities())
                    {
                        data = db.tblAssignment.Where(r => r.idProduct == ProductID && r.idCategory == CategoryID).First();
                    }
                    erros.Error = false;
                    return(new Tuple <ErrorObject, tblAssignment>(erros.IfError(false), data));
                }
                catch (Exception ex)
                {
                    erros.InfoError(ex);
                    return(new Tuple <ErrorObject, tblAssignment>(erros, data));
                }
            }
            public static GetAssignmentResponse Assignments(GetAssignmentResponse request)
            {
                GetAssignmentResponse response = new GetAssignmentResponse();

                try
                {
                    tblAssignment bussines = new tblAssignment()
                    {
                        id         = request.Assignment.id,
                        amount     = request.Assignment.amount,
                        detail     = request.Assignment.detail,
                        idCategory = request.Assignment.idCategory,
                        idEmployee = request.Assignment.idEmployee,
                        idProduct  = request.Assignment.idProduct,
                        min        = request.Assignment.Min,
                        max        = request.Assignment.Max,
                        loan       = request.Assignment.loan,
                        createDate = request.Assignment.createDate,
                        upDateDate = request.Assignment.upDateDate,
                        deleteDate = request.Assignment.deleteDate,
                        state      = request.Assignment.state
                    };

                    var result = AssignmentData.Update.Assignment(bussines);
                    if (result.Item1.Error)
                    {
                        response.Error.InfoError(result.Item1);
                    }
                    else
                    {
                        response.Message = result.Item2;
                    }
                }
                catch (Exception ex)
                {
                    response.Error.InfoError(ex);
                }

                return(response);
            }
        protected void btnArchive_Click(object sender, EventArgs e)
        {
            int hash = sender.GetHashCode();

            foreach (RepeaterItem item in rAssignment.Items)
            {
                Button button = item.FindControl("btnArchive") as Button;

                if (button.GetHashCode() == hash)
                {
                    Label label        = item.FindControl("lblAssignmentID") as Label;
                    int   assignmentID = Convert.ToInt32(label.Text);

                    using (DatabaseDataContext db = new DatabaseDataContext())
                    {
                        tblAssignment assignment = db.tblAssignments.Where(x => x.assignmentID == assignmentID).FirstOrDefault();

                        assignment.isArchived = true;
                        db.SubmitChanges();
                    }
                }
            }
        }
            /// <summary>
            /// Update Assignment Information
            /// </summary>
            /// <param name="data">Assignment Information</param>
            /// <returns>Number Affected Row</returns>
            public static Tuple <ErrorObject, string> Assignment(tblAssignment data)
            {
                erros = new ErrorObject();
                try
                {
                    using (EileenGaldamezEntities db = new EileenGaldamezEntities())
                    {
                        var row = db.tblAssignment.Single(p => p.id == data.id);
                        row.min        = data.min;
                        row.max        = data.max;
                        row.detail     = data.detail;
                        row.upDateDate = data.upDateDate;
                        result         = db.SaveChanges();
                        Message        = "Affected Row: " + result.ToString();

                        return(new Tuple <ErrorObject, string>(erros.IfError(false), Message));
                    }
                }
                catch (Exception ex)
                {
                    erros.InfoError(ex);
                    return(new Tuple <ErrorObject, string>(erros, String.Empty));
                }
            }
        private void btnSave_Click(object sender, EventArgs e)
        {
            tblAssignmentSubmission tb = new tblAssignmentSubmission();
            tblStudent tbl             = db.tblStudents.Where(a => a.StudentId == studentid).FirstOrDefault();

            tb.StudentId     = tbl.StudentId;
            tb.AssignmentId  = Convert.ToInt32(cboAssignmentId.SelectedValue);
            tb.StatusId      = Convert.ToInt32(cboStatusId.SelectedValue);
            tb.SubmittedDate = dateTimePicker1.Value;
            tblAssignment tba            = db.tblAssignments.Where(a => a.AssignmentId == tb.AssignmentId).FirstOrDefault();
            DateTime      subdate        = Convert.ToDateTime(tb.SubmittedDate);
            DateTime      submissiondate = Convert.ToDateTime(tba.SubmissionDate);
            //DateTime submissiondate = Convert.ToDateTime(tba.ReleaseDate);
            TimeSpan dt = subdate.Subtract(submissiondate);

            if (dt.TotalDays >= 1)
            {
                txtIsOnTime.Text = "No";
                int d = Convert.ToInt16(dt.TotalDays);
                MessageBox.Show("Assignment Submission Late by " + d + " days");
            }
            else
            {
                txtIsOnTime.Text = "Yes";
            }

            tb.IsOnTime = Convert.ToString(txtIsOnTime.Text);

            db.tblAssignmentSubmissions.Add(tb);
            if (db.SaveChanges() > 0)
            {
                MessageBox.Show("Assignment Submitted");
                LoadGrid();
                // ClearData();
            }
        }
        // -------------- Form View --------------- //

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (DateTime.Parse(dtStartDate.Text).Date <= DateTime.Now.Date)
            {
                regStartDate.Visible = true;
                return;
            }
            else
            {
                regStartDate.Visible = false;
            }

            if (DateTime.Parse(dtStartDate.Text).Date >= DateTime.Parse(dtEndDate.Text).Date)
            {
                regEndDate.Visible = true;
                return;
            }
            else
            {
                regEndDate.Visible = false;
            }

            string extension;

            var postedFileExtension = Path.GetExtension(fuSupplementaryFiles.FileName);

            if (!string.Equals(postedFileExtension, ".pdf", StringComparison.OrdinalIgnoreCase) &&
                !string.Equals(postedFileExtension, ".docx", StringComparison.OrdinalIgnoreCase))
            {
                lSupplementaryFiles.Visible = true;

                return;
            }
            else
            {
                if (string.Equals(postedFileExtension, ".pdf", StringComparison.OrdinalIgnoreCase))
                {
                    extension = ".pdf";
                }
                else
                {
                    extension = ".docx";
                }

                lSupplementaryFiles.Visible = false;
            }

            using (DatabaseDataContext db = new DatabaseDataContext())
            {
                string fileName = fuSupplementaryFiles.HasFile ? (txtAssignmentTitle.Text + SessionManager.TeacherID + extension) : null;

                tblAssignment assignment = new tblAssignment
                {
                    assignmentQuestionStatement = txtQuestionStatement.Text,
                    assignmentTitle             = txtAssignmentTitle.Text,
                    assignmentStartDate         = DateTime.Parse(dtStartDate.Text),
                    assignmentEndDate           = DateTime.Parse(dtEndDate.Text),
                    isGraded               = false,
                    isArchived             = false,
                    assignmentMaximumMarks = Convert.ToInt32(txtMaximumMarks.Text),
                    teacherID              = SessionManager.TeacherID,
                    fileName               = fileName
                };

                db.tblAssignments.InsertOnSubmit(assignment);

                if (assignment.fileName != null)
                {
                    //Saves file to a folder located inside the server
                    string savePath = Server.MapPath("~/Files/SupplementaryFiles");

                    //Renames the file such that there cannot be any duplicates
                    string saveFileName = fileName;

                    string imgSavePath = Path.Combine(savePath, saveFileName);
                    fuSupplementaryFiles.SaveAs(imgSavePath);
                }

                db.SubmitChanges();

                //assignment = (tblAssignment)db.GetChangeSet().Inserts.FirstOrDefault();

                var assignments  = db.tblAssignments.ToList();
                int assignmentID = assignments.LastOrDefault().assignmentID;

                var students = db.tblStudentSubjects.Where(x => x.teacherID == SessionManager.TeacherID && x.isVisible);

                int userID;

                foreach (tblStudentSubject student in students)
                {
                    userID = db.tblStudents.Where(x => x.studentID == student.studentID).FirstOrDefault().userID;

                    tblStudentAssignment studentAssignment = new tblStudentAssignment
                    {
                        studentID               = student.studentID,
                        assignmentID            = assignmentID,
                        studentAssignmentStatus = false,
                        studentAssignmentMarks  = null
                    };

                    db.tblStudentAssignments.InsertOnSubmit(studentAssignment);
                    db.SubmitChanges();

                    NotificationManager.assignmentCreateNotification(userID);
                }

                var list = db.tblAssignments.Where(x => x.teacherID == SessionManager.TeacherID).SortBy("assignmentEndDate");

                assignments = db.tblAssignments.Where(x => x.teacherID == SessionManager.TeacherID && x.isArchived == false).SortBy("assignmentEndDate").ToList();

                Session["assignmentList"] = assignments;

                ControlManager.populateControl(assignments, rAssignment);
            }

            ControlManager.clearTextBoxes(vForm);
            mvTeacherAssignments.ActiveViewIndex = 0;
            pCreate.Visible = true;
        }