protected void Button_Reject_Click(object sender, EventArgs e)
        {
            connection.Open();

            SqlCommand updateReportStatus = new SqlCommand("UPDATE Report SET ReportStatus = @ReportStatus, Remarks = @Remarks WHERE Username = @AccountUsername AND CaseNumber = @CaseNumber", connection);

            updateReportStatus.Parameters.AddWithValue("@ReportStatus", "rejected");
            updateReportStatus.Parameters.AddWithValue("@AccountUsername", Label6.Text);
            updateReportStatus.Parameters.AddWithValue("@CaseNumber", Session["caseNumberOfThisPendingReport"].ToString());
            updateReportStatus.Parameters.AddWithValue("@Remarks", Label12_remarks.Text);
            updateReportStatus.ExecuteNonQuery();

            connection.Close();

            caseNumberOfReport = Session["caseNumberOfThisPendingReport"].ToString();

            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.BossRejectedReport;
            ActionLogs.Log(Context.User.Identity.Name, action);

            Session["rejectedMsg"] = "Report with the Case Number of <b><u><big>#" + Session["caseNumberOfThisPendingReport"].ToString() + "</b></u></big> has been <b>rejected</b>.";
            Response.Redirect("~/Content/BossConsole/PendingReports.aspx");

            //ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Report with the Case Number of #" + Session["caseNumberOfThisPendingReport"].ToString() + " has been rejected.'); window.location = 'PendingReports.aspx'; ", true);

            //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This report has been rejected.')", true);
        }
Beispiel #2
0
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

            connection.Open();
            SqlDataReader dataReader  = null;
            SqlCommand    dateCommand = new SqlCommand("SELECT * FROM ErrorExceptionLogs WHERE (lower(Username) LIKE @txtSearchValue OR lower(ExceptionType) LIKE @txtSearchValue OR lower(ErrorMessage) LIKE @txtSearchValue OR lower(ErrorSource) LIKE @txtSearchValue OR lower(Location) LIKE @txtSearchValue) ORDER BY convert(datetime,Timestamp) DESC", connection);

            dateCommand.Parameters.AddWithValue("@txtSearchValue", "%" + txtSearchValue.Text.Trim().ToLower() + "%");
            dataReader = dateCommand.ExecuteReader();

            DataTable dt = new DataTable();

            dt.Load(dataReader);

            GridView1.DataSource = dt;
            ViewState["Datable"] = dt;
            GridView1.DataBind();

            if (dt.Rows.Count == 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
            }

            connection.Close();


            searchValue = txtSearchValue.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchErrorLogs;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            bool hasData = false;

            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

            connection.Open();
            SqlDataReader dateReader  = null;
            SqlCommand    dateCommand = new SqlCommand("SELECT DISTINCT(convert(date, Timestamp)) AS Date FROM Logs WHERE lower(Action) LIKE @Action AND Username = @AccountUsername ORDER BY convert(date,Timestamp) DESC", connection);

            dateCommand.Parameters.AddWithValue("@Action", "%" + txtSearchValue.Text.Trim().ToLower() + "%");
            dateCommand.Parameters.AddWithValue("@AccountUsername", bossUsername.Text);
            dateReader = dateCommand.ExecuteReader();

            while (dateReader.Read())
            {
                DateTime date = (DateTime)dateReader["Date"];
                //Response.Write("Date : " + date + "<br>");
                AddDateToPlaceholder(date);

                SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);
                connection2.Open();
                SqlDataReader logReader  = null;
                SqlCommand    logCommand = new SqlCommand("SELECT Action, Timestamp FROM Logs WHERE lower(Action) LIKE @Action AND Username = @AccountUsername AND convert(date, Timestamp) = convert(date,@Date) ORDER BY convert(date,Timestamp) ASC", connection2);

                logCommand.Parameters.AddWithValue("@Action", "%" + txtSearchValue.Text.Trim().ToLower() + "%");
                logCommand.Parameters.AddWithValue("@AccountUsername", bossUsername.Text);
                logCommand.Parameters.AddWithValue("@Date", date);
                logReader = logCommand.ExecuteReader();

                while (logReader.Read())
                {
                    hasData = true;

                    string   action     = logReader["Action"].ToString();
                    DateTime actionDate = (DateTime)logReader["Timestamp"];
                    //Response.Write("Date : " + actionDate + " Action : " + action + "<br>");
                    AddActionToPlaceholder(action, actionDate);
                }
            }

            if (hasData == false)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
            }


            searchValue = txtSearchValue.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchBossLogs;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
Beispiel #4
0
        protected void btnSearchBoth_Click(object sender, EventArgs e)
        {
            string s = TextBox2.Text;

            DateTime datetimeDT;

            if (DateTime.TryParse(s, out datetimeDT))
            {
                string date = s.ToString().Split(' ')[0];

                date = String.Format("{0:dd/MM/yyyy}", date);
                DateTime InputDate = Convert.ToDateTime(date);


                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

                connection.Open();
                SqlDataReader dataReader  = null;
                SqlCommand    dateCommand = new SqlCommand("SELECT * FROM ErrorExceptionLogs WHERE ((lower(Username) LIKE @txtSearchValue OR lower(ExceptionType) LIKE @txtSearchValue OR lower(ErrorMessage) LIKE @txtSearchValue OR lower(ErrorSource) LIKE @txtSearchValue OR lower(Location) LIKE @txtSearchValue) AND convert(date, Timestamp, 103) = convert(date,@Timestamp,103)) ORDER BY convert(date,Timestamp) DESC", connection);

                dateCommand.Parameters.AddWithValue("@txtSearchValue", "%" + TextBox1.Text.Trim().ToLower() + "%");
                dateCommand.Parameters.AddWithValue("@Timestamp", InputDate);

                dataReader = dateCommand.ExecuteReader();

                DataTable dt = new DataTable();
                dt.Load(dataReader);

                GridView1.DataSource = dt;
                ViewState["Datable"] = dt;
                GridView1.DataBind();

                if (dt.Rows.Count == 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
                }

                connection.Close();
            }

            searchValue = TextBox1.Text + " " + TextBox2.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchErrorLogs;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
        protected void btnAuthenticate_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                string inputUsername = Context.User.Identity.Name;
                string inputPassword = txtPasswordAuthenticate.Text;

                string dbUsername     = "";
                string dbPasswordHash = "";
                string dbSalt         = "";

                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

                connection.Open();
                SqlCommand myCommand = new SqlCommand("SELECT HashedPassword, Salt, Role, Username FROM UserAccount WHERE Username = @AccountUsername", connection);
                myCommand.Parameters.AddWithValue("@AccountUsername", inputUsername);

                SqlDataReader myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    dbPasswordHash = (myReader["HashedPassword"].ToString());
                    dbSalt         = (myReader["Salt"].ToString());
                    dbUsername     = (myReader["Username"].ToString());
                }
                connection.Close();

                string passwordHash = ComputeHash(inputPassword, new SHA512CryptoServiceProvider(), Convert.FromBase64String(dbSalt));

                if (dbUsername.Equals(inputUsername.Trim()))
                {
                    if (dbPasswordHash.Equals(passwordHash))
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "alert", "$('#myModal').modal('hide')", true);

                        //Add to logs
                        ActionLogs.Action action = ActionLogs.Action.ReauthenticatedDueToAccountLockout;
                        ActionLogs.Log(Context.User.Identity.Name, action);
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "alert", "$('#myModal').modal('show')", true);
                        errormsgPasswordAuthenticate.Visible = true;
                    }
                }
            }
        }
Beispiel #6
0
        protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
        {
            Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            Session["AccountUsername"] = Context.User.Identity.Name;
            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.Logout;
            ActionLogs.Log(Session["AccountUsername"].ToString(), action);

            connection.Open();
            SqlCommand updateFirstLoginAccess = new SqlCommand("UPDATE UserAccount SET isFirstTimeAccessed = @isFirstTimeAccessed WHERE Username = @AccountUsername", connection);

            updateFirstLoginAccess.Parameters.AddWithValue("@isFirstTimeAccessed", "0");
            updateFirstLoginAccess.Parameters.AddWithValue("@AccountUsername", Session["AccountUsername"].ToString());
            updateFirstLoginAccess.ExecuteNonQuery();
            connection.Close();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

            connection.Open();
            SqlDataReader dataReader  = null;
            SqlCommand    dateCommand = new SqlCommand("SELECT * FROM Report WHERE (lower(Username) LIKE @txtSearchValue OR lower(Subject) LIKE @txtSearchValue OR lower(CaseNumber) LIKE @txtSearchValue OR lower(ReportStatus) LIKE @txtSearchValue OR lower(Subject) LIKE @txtSearchValue) AND Username = @AccountUsername AND (ReportStatus = 'accepted' OR ReportStatus = 'pending' OR ReportStatus = 'rejected')", connection);

            dateCommand.Parameters.AddWithValue("@txtSearchValue", "%" + txtSearchValue.Text.Trim().ToLower() + "%");
            dateCommand.Parameters.AddWithValue("@AccountUsername", Context.User.Identity.Name);

            dataReader = dateCommand.ExecuteReader();

            DataTable dt = new DataTable();

            dt.Load(dataReader);
            GridView1.DataSource = dt;
            //store viewstate
            ViewState["Datable"] = dt;
            GridView1.DataBind();

            if (dt.Rows.Count == 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
            }

            connection.Close();



            searchValue = txtSearchValue.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();
            staffName   = Context.User.Identity.Name;

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchByStaff;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
        protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
        {
            Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);


            // FormsAuthentication.SignOut();
            // FormsAuthentication.RedirectToLoginPage();
            Session["AccountUsername"] = Context.User.Identity.Name;

            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.Logout;
            ActionLogs.Log(Session["AccountUsername"].ToString(), action);

            connection.Open();
            SqlCommand updateFirstLoginAccess = new SqlCommand("UPDATE UserAccount SET isFirstTimeAccessed = @isFirstTimeAccessed WHERE Username = @AccountUsername", connection);

            updateFirstLoginAccess.Parameters.AddWithValue("@isFirstTimeAccessed", "0");
            updateFirstLoginAccess.Parameters.AddWithValue("@AccountUsername", Session["AccountUsername"].ToString());
            updateFirstLoginAccess.ExecuteNonQuery();
            connection.Close();

            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            //Response.Cache.SetNoStore();

            //Clear cookies
            //string[] cookies = Request.Cookies.AllKeys;
            //foreach (string cookie in cookies)
            //{
            //    Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
            //}

            //FormsAuthentication.SignOut();
            //Session.Abandon();
            //FormsAuthentication.RedirectToLoginPage();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        protected void btnSearchBoth_Click(object sender, EventArgs e)
        {
            string s = TextBox2.Text;

            DateTime datetimeDT;

            if (DateTime.TryParse(s, out datetimeDT))
            {
                string date = s.ToString().Split(' ')[0];

                date = String.Format("{0:dd/MM/yyyy}", date);
                DateTime InputDate = Convert.ToDateTime(date);

                try
                {
                    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

                    connection.Open();

                    SqlCommand dateCommand = new SqlCommand("SELECT DISTINCT(Timestamp) AS [DD/MM/YYYY] FROM LOGS WHERE (Username = @AccountUsername AND convert(date, Timestamp, 103) = convert(date, @Timestamp, 103))", connection);

                    dateCommand.Parameters.AddWithValue("@AccountUsername", bossUsername.Text);
                    dateCommand.Parameters.AddWithValue("@Timestamp", InputDate);
                    //dateCommand.Parameters.AddWithValue("@txtSearchValue", "%" + TextBox1.Text.Trim().ToLower() + "%");

                    var dbDate = (DateTime)dateCommand.ExecuteScalar();

                    if (dbDate != null)
                    {
                        AddDateToPlaceholder(dbDate);

                        SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);
                        connection2.Open();
                        SqlDataReader logReader  = null;
                        SqlCommand    logCommand = new SqlCommand("SELECT Action, Timestamp FROM Logs WHERE (Username = @AccountUsername AND convert(date, Timestamp, 103) = convert(date, @Timestamp, 103) AND lower(Action) LIKE @txtSearchValue) ORDER BY convert(date, Timestamp, 103) ASC", connection2);

                        logCommand.Parameters.AddWithValue("@AccountUsername", bossUsername.Text);
                        logCommand.Parameters.AddWithValue("@Timestamp", dbDate);

                        logCommand.Parameters.AddWithValue("@txtSearchValue", "%" + TextBox1.Text.Trim().ToLower() + "%");
                        logReader = logCommand.ExecuteReader();

                        while (logReader.Read())
                        {
                            string action     = logReader["Action"].ToString();
                            string actionDate = logReader["Timestamp"].ToString();
                            //Response.Write("Date : " + actionDate + " Action : " + action + "<br>");
                            DateTime actionDateDT = Convert.ToDateTime(actionDate);

                            AddActionToPlaceholder(action, actionDateDT);
                        }
                    }
                }
                catch (System.NullReferenceException exc)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please check that you have entered a correct format in DD/MM/YYYY.')", true);
            }


            searchValue = TextBox1.Text + " " + TextBox2.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchBossLogs;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
Beispiel #10
0
        protected void btnSearchDate_Click(object sender, EventArgs e)
        {
            string s = txtSearchValueDate.Text;

            DateTime dt;

            if (DateTime.TryParse(s, out dt))
            {
                string date = s.ToString().Split(' ')[0];

                date = String.Format("{0:dd/MM/yyyy}", date);
                DateTime InputDate = Convert.ToDateTime(date);


                //String hour = s.ToString().Split(' ')[1].Split(':')[0];
                //Response.Write(hour + "\n");
                //String min = s.ToString().Split(' ')[1].Split(':')[1];
                //Response.Write(min + "\n");
                //String sec = s.ToString().Split(' ')[1].Split(':')[2];
                //Response.Write(sec + "\n");

                //string time = hour + ":" + min + ":" + sec;

                //if (txtSearchValueDate.Text.Contains(time))
                //{
                //    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please check that you have entered a correct format in DD/MM/YYYY!')", true);
                //}

                try
                {
                    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

                    connection.Open();

                    SqlCommand dateCommand = new SqlCommand("SELECT * FROM ErrorExceptionLogs WHERE convert(date, Timestamp, 103) = convert(date,@Timestamp,103)", connection);
                    //OR convert(time(0), Timestamp) = @Time)
                    //SELECT (convert(varchar(15), Timestamp, 108)) FROM ErrorExceptionLogs

                    dateCommand.Parameters.AddWithValue("@Timestamp", InputDate);
                    //dateCommand.Parameters.AddWithValue("@Time", time);

                    SqlDataReader dataReader = dateCommand.ExecuteReader();

                    DataTable dt2 = new DataTable();
                    dt2.Load(dataReader);

                    GridView1.DataSource = dt2;
                    ViewState["Datable"] = dt;
                    GridView1.DataBind();

                    if (dt2.Rows.Count == 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
                    }
                    connection.Close();
                }
                catch (System.NullReferenceException exc)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('There is no data found for this search.')", true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please check that you have entered a correct format in DD/MM/YYYY.')", true);
            }

            searchValue = txtSearchValueDate.Text;
            url         = System.Web.HttpContext.Current.Request.Url.ToString();

            //Add to logs
            ActionLogs.Action actionLog = ActionLogs.Action.SearchErrorLogs;
            ActionLogs.Log(Context.User.Identity.Name, actionLog);
        }
        protected void LogIn(object sender, EventArgs e)
        {
            string inputUsername = username.Text;
            string inputPassword = password.Text;

            string dbUsername     = "";
            string dbPasswordHash = "";
            string dbSalt         = "";
            string dbStatus       = "";

            connection.Open();
            SqlCommand myCommand = new SqlCommand("SELECT HashedPassword, Salt, Role, Username FROM UserAccount WHERE Username = @AccountUsername", connection);

            myCommand.Parameters.AddWithValue("@AccountUsername", inputUsername);

            SqlDataReader myReader = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                dbPasswordHash = (myReader["HashedPassword"].ToString());
                dbSalt         = (myReader["Salt"].ToString());
                dbStatus       = (myReader["Role"].ToString());
                dbUsername     = (myReader["Username"].ToString());
            }
            connection.Close();

            string passwordHash = ComputeHash(inputPassword, new SHA512CryptoServiceProvider(), Convert.FromBase64String(dbSalt));

            if (IsValid)
            {
                if (dbUsername.Equals(inputUsername.Trim()))
                {
                    if (dbPasswordHash.Equals(passwordHash))
                    {
                        if (dbStatus.Equals("Staff"))
                        {
                            Session["AccountUsername"] = inputUsername;

                            //Add to logs
                            ActionLogs.Action action = ActionLogs.Action.Login;
                            ActionLogs.Log(username.Text, action);

                            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username.Text, DateTime.Now, DateTime.Now.AddMinutes(10), false, username.Text);
                            String     encryptedTicket           = FormsAuthentication.Encrypt(authTicket);
                            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                            Response.Cookies.Add(authCookie);

                            Response.Redirect("~/Content/StaffConsole/NewReport.aspx");
                        }
                    }
                    else
                    {
                        IncorrectInputLabel.Text = "Incorrect username/password";
                    }
                }
                else
                {
                    IncorrectInputLabel.Text = "Incorrect username/password";
                }


                if (dbUsername.Equals(inputUsername) && dbPasswordHash.Equals(passwordHash) && dbStatus.Equals("Boss"))
                {
                    Session["AccountUsername"] = username.Text;

                    //Add to logs
                    ActionLogs.Action action = ActionLogs.Action.Login;
                    ActionLogs.Log(username.Text, action);

                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username.Text, DateTime.Now, DateTime.Now.AddMinutes(10), false, username.Text);
                    String     encryptedTicket           = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    Response.Cookies.Add(authCookie);

                    Response.Redirect("~/Content/BossConsole/PendingReports.aspx");
                }
            }
        }
        protected void btnSaveAsPDF_Click(object sender, EventArgs e)
        {
            //string inputUsername = Context.User.Identity.Name;
            //string inputUsername = Session["AccountUsername"].ToString();
            string rStatus = "accepted";

            dbCaseNumber = Session["caseNumberOfThisSelectedReport"].ToString();

            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString);

            connection.Open();
            SqlCommand myCommand = new SqlCommand("SELECT CaseNumber, Username, Date, Subject, Description, Remarks, CreatedDateTime FROM Report WHERE ReportStatus = @reportStatus AND CaseNumber = @cNum", connection);

            //myCommand.Parameters.AddWithValue("@AccountUsername", inputUsername); //Taking the latest report of that user only. //Should be click on a particular report number - thats the report that we should take
            myCommand.Parameters.AddWithValue("@reportStatus", rStatus);
            myCommand.Parameters.AddWithValue("@cNum", dbCaseNumber);


            SqlDataReader myReader = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                //dbCaseNumber = (myReader["CaseNumber"].ToString());
                dbUsername        = (myReader["Username"].ToString());
                dbDate            = (myReader["Date"].ToString());
                dbSubject         = (myReader["Subject"].ToString());
                dbDescription     = (myReader["Description"].ToString());
                dbRemarks         = (myReader["Remarks"].ToString());
                dbCreatedDateTime = (myReader["CreatedDateTime"].ToString());
            }
            connection.Close();

            //Creating a pdf document
            PdfDocument doc = new PdfDocument();

            //Create a page
            PdfPageBase page = doc.Pages.Add();

            //Draw the contents of page
            AlignText(page);

            // + Encryption (Joanne)
            doc.Security.KeySize       = PdfEncryptionKeySize.Key128Bit;
            doc.Security.OwnerPassword = "******";
            doc.Security.UserPassword  = PasswordTxt.Text;
            doc.Security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields;

            //// + DigitalSignature Method 1 (KaiTat)
            //String pfxPath = @"C:\\Program Files (x86)\\e-iceblue\\Spire.pdf\\Demos\\Data\\Demo.pfx";
            //PdfCertificate digi = new PdfCertificate(pfxPath, "e-iceblue");
            //PdfSignature signature = new PdfSignature(doc, page, digi, "demo");
            //signature.ContactInfo = "Harry Hu";
            //signature.Certificated = true;
            //signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

            //KT Digital Signature Method 2
            PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature");

            signaturefield.BorderWidth   = 1.0f;
            signaturefield.BorderStyle   = PdfBorderStyle.Solid;
            signaturefield.BorderColor   = new PdfRGBColor(System.Drawing.Color.Black);
            signaturefield.HighlightMode = PdfHighlightMode.Outline;
            signaturefield.Bounds        = new RectangleF(350, 600, 100, 100);


            doc.Form.Fields.Add(signaturefield);



            // + Watermark - Text (Joanne)
            string wmText = "Report #" + dbCaseNumber + " by " + Context.User.Identity.Name;

            PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));

            brush.Graphics.SetTransparency(0.3f);
            brush.Graphics.Save();
            brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
            brush.Graphics.RotateTransform(-45);
            brush.Graphics.DrawString(wmText, new PdfFont(PdfFontFamily.Helvetica, 20), PdfBrushes.Black, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
            brush.Graphics.Restore();
            brush.Graphics.SetTransparency(1);
            page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(1, 1), page.Canvas.ClientSize));



            //Save pdf to a location
            //doc.SaveToFile("C:\\Users\\User\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");
            doc.SaveToFile("C:\\Saved PDF\\" + dbCaseNumber + ".pdf");
            //Kt testing
            //doc.SaveToFile("C:\\Users\\Kai Tat\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");


            //Launching the PDF File
            System.Diagnostics.Process.Start("C:\\Saved PDF\\" + dbCaseNumber + ".pdf");
            //Kt testing
            //System.Diagnostics.Process.Start("C:\\Users\\Kai Tat\\Desktop\\CreatePDFTest" + dbCaseNumber + ".pdf");


            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.ReportSavedToPdf;
            ActionLogs.Log(Context.User.Identity.Name, action);
        }
        //private string Decrypt(string cipherText)
        //{
        //    string EncryptionKey = "MAKV2SPBNI99212";
        //    byte[] cipherBytes = Convert.FromBase64String(cipherText);
        //    using (Aes encryptor = Aes.Create())
        //    {
        //        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        //        encryptor.Key = pdb.GetBytes(32);
        //        encryptor.IV = pdb.GetBytes(16);
        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
        //            {
        //                cs.Write(cipherBytes, 0, cipherBytes.Length);
        //                cs.Close();
        //            }
        //            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        //        }
        //    }
        //    return cipherText;
        //}


        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            //string uname = Context.User.Identity.Name;
            string uname = Session["AccountUsername"].ToString();
            //Case Number Created +1
            //Retrieve the latest case number and +1
            string dbCaseNumber = "";

            connection.Open();
            SqlCommand    myCommand = new SqlCommand("SELECT CaseNumber FROM Report", connection);
            SqlDataReader myReader  = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                dbCaseNumber = (myReader["CaseNumber"].ToString());

                cNumber = int.Parse(dbCaseNumber);
            }
            cNumber++;

            //cNumber = int.Parse(dbCaseNumber);
            //cNumber++;
            connection.Close();

            //Converting input date into datetime type input
            DateTime DateInput = new DateTime();

            DateInput = Convert.ToDateTime(TextBox4.Text);

            //Getting the date time when submit drafts/save reports as drafts
            DateTime createdDateTime = new DateTime();

            createdDateTime = DateTime.Now;

            string NameInput    = TextBox3.Text;
            string SubjectInput = TextBox2.Text;
            string CaseDesInput = TextBox1.Text;
            string status       = "pending";


            connection.Open();


            //(KT)
            string constr = ConfigurationManager.ConnectionStrings["FileDatabaseConnectionString2"].ConnectionString;
            //using (SqlConnection con = new SqlConnection(constr))
            //{
            //    con.Open();
            //    using (SqlCommand cmd = new SqlCommand("INSERT INTO Report (Subject, Description) VALUES(@Subject, @Description)"))
            //    {
            //        cmd.CommandType = CommandType.Text;
            //        cmd.Parameters.AddWithValue("@Subject", Encrypt(TextBox2.Text.Trim()));
            //        cmd.Parameters.AddWithValue("@Description", Encrypt(TextBox1.Text.Trim()));
            //        cmd.Connection = con;

            //        cmd.ExecuteNonQuery();
            //        con.Close();
            //    }
            //}
            //Response.Redirect(Request.Url.AbsoluteUri);

            SqlCommand insertReportCommand = new SqlCommand();

            insertReportCommand.CommandText = "INSERT INTO Report (CaseNumber, Username, Date, Subject, Description, Remarks, ReportStatus, CreatedDateTime)" +
                                              " VALUES (@caseNumber, @username, @date, @subject, @description, @remarks, @status, @createdDT)";
            insertReportCommand.Parameters.AddWithValue("@caseNumber", cNumber);
            insertReportCommand.Parameters.AddWithValue("@username", NameInput);
            insertReportCommand.Parameters.AddWithValue("@date", DateInput);
            insertReportCommand.Parameters.AddWithValue("@subject", SubjectInput);
            //insertReportCommand.Parameters.AddWithValue("@description", CaseDesInput);
            //insertReportCommand.Parameters.AddWithValue("@subject", Encrypt(TextBox2.Text.Trim()));
            insertReportCommand.Parameters.AddWithValue("@description", Encrypt(CaseDesInput.Trim())); //TextBox1.Text.Trim()
            insertReportCommand.Parameters.AddWithValue("@Remarks", "");
            insertReportCommand.Parameters.AddWithValue("@status", status);
            insertReportCommand.Parameters.AddWithValue("@createdDT", createdDateTime);


            insertReportCommand.Connection = connection;
            insertReportCommand.ExecuteNonQuery();
            connection.Close();

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
            //"alert('Case #'" + cNumber + "' has been created.');" + "window.location = 'SubmittedReports.aspx'; ", true);


            caseNumberOfReport = cNumber + "";


            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.StaffSubmittedReport;
            ActionLogs.Log(Context.User.Identity.Name, action);


            string message = "Case #" + cNumber + " has been created.";

            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "'); window.location = 'SubmittedReports.aspx'; ", true);
        }
        protected void SaveAsDraftsButton_Click(object sender, EventArgs e)
        {
            //COPY PASTED FROM SUBMIT BUTTON
            //Flow: create a case record in the reports db

            //Case Number Created +1
            //Retrieve the latest case number and +1
            string dbCaseNumber = "";

            connection.Open();
            SqlCommand    myCommand = new SqlCommand("SELECT CaseNumber FROM Report", connection);
            SqlDataReader myReader  = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                dbCaseNumber = (myReader["CaseNumber"].ToString());
            }

            cNumber = int.Parse(dbCaseNumber);
            connection.Close();
            cNumber++;

            //Converting input date into datetime type input
            DateTime DateInput = new DateTime();

            DateInput = Convert.ToDateTime(TextBox4.Text);

            //Getting the date time when submit drafts/save reports as drafts
            DateTime createdDateTime = new DateTime();

            createdDateTime = DateTime.Now;

            string NameInput    = TextBox3.Text;
            string SubjectInput = TextBox2.Text;
            string CaseDesInput = TextBox1.Text;
            string status       = "drafts";

            //Add the details into database (done)
            //Report inserted into database, with ReportStatus = drafts (done)
            //Report details encrypted (not done)

            connection.Open();

            SqlCommand insertReportCommand = new SqlCommand();

            insertReportCommand.CommandText = "INSERT INTO Report (CaseNumber, Username, Date, Subject, Description, Remarks, ReportStatus, CreatedDateTime)" +
                                              " VALUES (@caseNumber, @username, @date, @subject, @description, @remarks, @status, @createdDT)";
            insertReportCommand.Parameters.AddWithValue("@caseNumber", cNumber);
            insertReportCommand.Parameters.AddWithValue("@username", NameInput);
            insertReportCommand.Parameters.AddWithValue("@date", DateInput);
            insertReportCommand.Parameters.AddWithValue("@subject", SubjectInput);
            insertReportCommand.Parameters.AddWithValue("@description", Encrypt(CaseDesInput.Trim()));
            insertReportCommand.Parameters.AddWithValue("@Remarks", "");
            insertReportCommand.Parameters.AddWithValue("@status", status);
            insertReportCommand.Parameters.AddWithValue("@createdDT", createdDateTime);


            insertReportCommand.Connection = connection;
            insertReportCommand.ExecuteNonQuery();
            connection.Close();


            caseNumberOfReport = cNumber + "";


            //Add to logs
            ActionLogs.Action action = ActionLogs.Action.ReportSavedAsDrafts;
            ActionLogs.Log(Context.User.Identity.Name, action);

            //alert
            string message = "Your report has been saved in drafts!";

            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "'); window.location = 'SubmittedReports.aspx'; ", true);
        }