Example #1
0
        public ActionResult Submit(Models.FormData formData)
        {
            // extra validation
            if (!ModelState.IsValid)
            {
                return(View("Index"));
            }


            // generate external reference from [Agency Code][Batch Number]-[Sequence Number]-[Date]-[Gift Suffix]

            // generate external reference data source, set to the Agency Code

            // generate source, a 9 digit code relating to the campaign that elicited the response



            _context.Add(formData);
            var id = formData;

            _context.SaveChanges();
            formData.Signature = DataHelper.SaveSignature(formData.FormDataId, formData.Signature);
            _context.Update(formData);
            _context.SaveChanges();

            return(Ok());
        }
Example #2
0
        public Boolean SendMail(string from, List <string> emailList, string subject, string bodyHtml, TForm newForm, Int32 formId, SystemUsers sentUser)
        {
            try
            {
                MailMessage completeMessage = new MailMessage();
                completeMessage.From       = new MailAddress(from);
                completeMessage.Subject    = subject;
                completeMessage.Body       = bodyHtml;
                completeMessage.IsBodyHtml = true;

                //SmtpClient client = new SmtpClient("TingleNT30.wctingle.com");
                //client.UseDefaultCredentials = true;
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.Credentials = new NetworkCredential("*****@*****.**", "ZXCasdQWE123!");
                client.EnableSsl   = true;

                using (FormContext ctx = new FormContext())
                {
                    foreach (string email in emailList)
                    {
                        RequestNotifications newRN = new RequestNotifications
                        {
                            Form            = ctx.TForms.FirstOrDefault(x => x.FormID == newForm.FormID),
                            BodyHtml        = bodyHtml,
                            RequestedFormId = formId,
                            SentBy          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == sentUser.SystemUserID),
                            Status          = 0,
                            Timestamp       = DateTime.Now,
                            ToEmailAddress  = email
                        };

                        ctx.RequestNotifications.Add(newRN);
                        ctx.SaveChanges();

                        try
                        {
                            completeMessage.To.Clear();
                            completeMessage.To.Add(email);
                            client.Send(completeMessage);

                            newRN.Status = 1;

                            ctx.SaveChanges();
                        }
                        catch (Exception exc)
                        {}
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
                //throw ex;
            }
        }
Example #3
0
        public Boolean SendInventoryNotification(List <string> emailList, string bodyHtml, SystemUsers sentUser)
        {
            try
            {
                MailMessage completeMessage = new MailMessage();
                completeMessage.From       = new MailAddress("*****@*****.**");
                completeMessage.Subject    = "Inventory Approval Notification";
                completeMessage.Body       = bodyHtml;
                completeMessage.IsBodyHtml = true;

                //SmtpClient client = new SmtpClient("TingleNT30.wctingle.com");
                //client.UseDefaultCredentials = true;
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.Credentials = new NetworkCredential("*****@*****.**", "ZXCasdQWE123!");
                client.EnableSsl   = true;

                using (FormContext ctx = new FormContext())
                {
                    foreach (string email in emailList)
                    {
                        InventoryApprovalNotifications newRN = new InventoryApprovalNotifications
                        {
                            BodyHtml       = bodyHtml,
                            SentBy         = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == sentUser.SystemUserID),
                            Status         = 0,
                            Timestamp      = DateTime.Now,
                            ToEmailAddress = email
                        };

                        ctx.InventoryApprovalNotifications.Add(newRN);
                        ctx.SaveChanges();

                        try
                        {
                            completeMessage.To.Clear();
                            completeMessage.To.Add(email);
                            client.Send(completeMessage);

                            newRN.Status = 1;

                            ctx.SaveChanges();
                        }
                        catch (Exception exc)
                        { }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #4
0
        protected void btnAddSkuQuantity_Click(object sender, EventArgs e)
        {
            try
            {
                using (FormContext ctx = new FormContext())
                {
                    SkuQuantity newSQ = new SkuQuantity
                    {
                        MaterialSku = txtMaterialSku.Text,
                        Quantity    = txtQuantityOrdered.Text,
                        TempId      = lblRandomIdentifier.Text,
                        Completed   = false
                    };

                    ctx.SkuQuantityItems.Add(newSQ);
                    ctx.SaveChanges();
                    txtMaterialSku.Text     = "";
                    txtQuantityOrdered.Text = "";
                }

                gvSkus.DataBind();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #5
0
        protected void gvSkus_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView    gv              = (GridView)sender;
                GridViewRow gvr             = (GridViewRow)gv.Rows[e.RowIndex];
                Label       lblRecordIdEdit = (Label)gvr.FindControl("lblRecordIdEdit");
                int         id              = Convert.ToInt32(lblRecordIdEdit.Text);

                using (FormContext ctx = new FormContext())
                {
                    var sku = ctx.SkuQuantityItems.FirstOrDefault(x => x.RecordId == id);

                    sku.Completed   = ((CheckBox)gvr.FindControl("cbCompletedEdit")).Checked;
                    sku.MaterialSku = ((TextBox)gvr.FindControl("txtMaterialSkuEdit")).Text;
                    sku.Quantity    = ((TextBox)gvr.FindControl("txtQuantityEdit")).Text;

                    ctx.SaveChanges();
                    gvSkus.DataBind();
                    lblAddSkuMessage.Text = "";
                }
            }
            catch (Exception ex)
            {
                lblAddSkuMessage.Text = "Unable to update Material SKU# and/or Quantity.  Please contact your system administrator.";
            }
        }
Example #6
0
        public IHttpActionResult AddForm([FromBody] FormModel form)
        {
            //grab data and add new form
            var db = new FormContext();

            db.Forms.Add(form);
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            //add user session data
            if (HttpContext.Current.Session != null &&
                HttpContext.Current.Session["forms"] != null)
            {
                var sessionForms = HttpContext.Current.Session["forms"];
                if (sessionForms == null)
                {
                    HttpContext.Current.Session.Add("forms", listOfForms);
                }
            }
            //ViewBag.FromSession = HttpContext.Current.Session["forms"];

            return(Ok(form));
        }
Example #7
0
        protected void btnSaveAccountSettings_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    UserLogic uLogic = new UserLogic();
                    System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
                    SystemUsers currentUser = uLogic.GetCurrentUser(user);

                    using (FormContext ctx = new FormContext())
                    {
                        var updateUser = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID);

                        updateUser.Greeting    = txtGreeting.Text;
                        updateUser.DisplayName = txtDisplayName.Text;
                        updateUser.UserStatus  = ctx.UserStatuses.FirstOrDefault(x => x.StatusText == ddlUserStatus.SelectedText);

                        ctx.SaveChanges();

                        divSaveCancel.Visible      = false;
                        divLabelEdit.Visible       = true;
                        divDisplayNameEdit.Visible = false;
                        ddlUserStatus.Enabled      = false;
                        txtGreeting.Enabled        = false;

                        lblUser.Text = txtDisplayName.Text;
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
Example #8
0
 public IActionResult Form(Form f)
 {
     if (ModelState.IsValid)
     {
         _context.Add(f);
         _context.SaveChanges();
     }
     return(View(f));
 }
        protected void btnInsertEmail_Click(object sender, EventArgs e)
        {
            try
            {
                using (FormContext ctx = new FormContext())
                {
                    if (!ctx.NotificationEmailAddresses.Any(x => x.Name == txtNameInsert.Text || x.Address == txtAddressInsert.Text))
                    {
                        if (!ctx.SystemUsers.Any(x => x.EmailAddress == txtAddressInsert.Text))
                        {
                            NotificationEmailAddress newEmail = new NotificationEmailAddress();

                            newEmail.Timestamp = DateTime.Now;
                            newEmail.Name      = txtNameInsert.Text;
                            newEmail.Address   = txtAddressInsert.Text;
                            newEmail.Status    = Convert.ToInt16(rblNotificationEmailStatusInsert.SelectedValue);

                            ctx.NotificationEmailAddresses.Add(newEmail);

                            ctx.SaveChanges();

                            lblInsertEmailMessage.Text = "";
                            txtAddressInsert.Text      = "";
                            txtNameInsert.Text         = "";
                            rblNotificationEmailStatusInsert.SelectedIndex = 0;
                            ddlNotifyOther.DataBind();
                        }
                        else
                        {
                            lblInsertEmailMessage.Text = "A System User already exists with this Email Address.  Please enter a unique Email Address.";
                        }
                    }
                    else
                    {
                        if (ctx.NotificationEmailAddresses.Any(x => x.Name == txtNameInsert.Text && x.Address == txtAddressInsert.Text))
                        {
                            lblInsertEmailMessage.Text = "A Notification Email already exists with this Name and Email Address.  Please enter a unique Name and Email Address.";
                        }
                        else if (ctx.NotificationEmailAddresses.Any(x => x.Name == txtNameInsert.Text))
                        {
                            lblInsertEmailMessage.Text = "A Notification Email already exists with this Name.  Please enter a unique Name.";
                        }
                        else if (ctx.NotificationEmailAddresses.Any(x => x.Address == txtAddressInsert.Text))
                        {
                            lblInsertEmailMessage.Text = "A Notification Email already exists with this Email Address.  Please enter a unique Email Address.";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblInsertEmailMessage.Text = "Unable to add this Email Address.  Please contact your system administrator.";
            }
        }
Example #10
0
        protected void cbFavoriteCannotWaitForContainer_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                using (FormContext ctx = new FormContext())
                {
                    System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
                    UserLogic   uLogic      = new UserLogic();
                    SystemUsers currentUser = uLogic.GetCurrentUser(user);
                    if (currentUser != null)
                    {
                        if (cbFavoriteCannotWaitForContainer.Checked == true)
                        {
                            FavoriteForm favForm = new FavoriteForm();
                            if (ctx.SystemUsers.Any(s => s.SystemUserID == currentUser.SystemUserID) && ctx.TForms.Any(t => t.FormName == "Cannot Wait For Container"))
                            {
                                if (!ctx.FavoriteForms.Any(f => f.Form.FormName == "Cannot Wait For Container" && f.User.SystemUserID == currentUser.SystemUserID))
                                {
                                    favForm.User = ctx.SystemUsers.First(s => s.SystemUserID == currentUser.SystemUserID);
                                    favForm.Form = ctx.TForms.First(t => t.FormName == "Cannot Wait For Container");

                                    ctx.FavoriteForms.Add(favForm);
                                }
                            }
                            else
                            {
                                lblUserMessage.Visible = true;
                                lblUserMessage.Text    = "Unable to add Favorite Form.  Please contact your System Administrator for more information.";
                            }
                        }
                        else
                        {
                            if (ctx.FavoriteForms.Any(f => f.User.SystemUserID == currentUser.SystemUserID && f.Form.FormName == "Cannot Wait For Container"))
                            {
                                var favForm = ctx.FavoriteForms.First(f => f.User.SystemUserID == currentUser.SystemUserID && f.Form.FormName == "Cannot Wait For Container");
                                ctx.FavoriteForms.Remove(favForm);
                            }
                        }

                        ctx.SaveChanges();
                        LoadFavoriteForms();
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #11
0
        public bool AddExpeditedOrderForm(string oowOrderNumber, string customer, string accountNumber, ExpediteCode expediteCode, string purchaseOrderNumber, string materialSku, string quantityOrdered,
                                          Nullable <DateTime> installDate, string sM, string contactName, string phoneNumber, string shipToName, string shipToAddress, string shipToCity, string shipToState, string shipToZip,
                                          string additionalInfo, Status status, string submittedByUser, string ccFormToEmail, string company, out Int32 formId)
        {
            try
            {
                using (FormContext _db = new FormContext())
                {
                    var expCode          = _db.ExpediteCodes.SingleOrDefault(ec => ec.ExpediteCodeID == expediteCode.ExpediteCodeID);
                    var submissionStatus = _db.Statuses.SingleOrDefault(s => s.StatusId == status.StatusId);

                    var newForm = new ExpeditedOrderForm();
                    newForm.Timestamp           = DateTime.Now;
                    newForm.OowOrderNumber      = oowOrderNumber;
                    newForm.Customer            = customer;
                    newForm.AccountNumber       = accountNumber;
                    newForm.ExpediteCode        = expCode;
                    newForm.PurchaseOrderNumber = purchaseOrderNumber;
                    newForm.InstallDate         = installDate;
                    newForm.SM              = sM;
                    newForm.ContactName     = contactName;
                    newForm.PhoneNumber     = phoneNumber;
                    newForm.ShipToName      = shipToName;
                    newForm.ShipToAddress   = shipToAddress;
                    newForm.ShipToCity      = shipToCity;
                    newForm.ShipToState     = shipToState;
                    newForm.ShipToZip       = shipToZip;
                    newForm.AdditionalInfo  = additionalInfo;
                    newForm.Status          = submissionStatus;
                    newForm.SubmittedByUser = submittedByUser;
                    newForm.CCFormToEmail   = ccFormToEmail;
                    newForm.Company         = company;

                    _db.ExpeditedOrderForms.Add(newForm);
                    _db.SaveChanges();

                    formId = newForm.RecordId;
                }
                return(true);
            }
            catch (Exception ex)
            {
                formId = 0;
                return(false);
                //throw ex;
            }
        }
Example #12
0
        public SystemUsers GetCurrentUser(System.Security.Principal.IPrincipal user)
        {
            try
            {
                SystemUsers sUser = ctx.SystemUsers.Where(u => u.UserName == user.Identity.Name).FirstOrDefault();

                if (sUser != null)
                {
                    return(sUser);
                }
                else
                {
                    UserRoles uRole = ctx.UserRoles.Where(ur => ur.RoleName == "User").FirstOrDefault();

                    ctx.SystemUsers.Add(new SystemUsers {
                        UserName     = user.Identity.Name,
                        DisplayName  = user.Identity.Name.Substring(System.Web.HttpContext.Current.User.Identity.Name.IndexOf(@"\") + 1),
                        UserRole     = uRole,
                        EmailAddress = user.Identity.Name.Substring(System.Web.HttpContext.Current.User.Identity.Name.IndexOf(@"\") + 1),
                        Points       = 0,
                        Greeting     = "",
                        UserStatus   = ctx.UserStatuses.FirstOrDefault(x => x.StatusText == "Online")
                    });

                    ctx.SaveChanges();

                    SystemUsers newUser = ctx.SystemUsers.Where(u => u.UserName == user.Identity.Name).FirstOrDefault();



                    if (newUser != null)
                    {
                        return(newUser);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Example #13
0
        public int save(FormViewModel form)
        {
            var formEntity = new Form {
                Name = form.Name, FormId = form.FormId
            };

            using (var db = new FormContext())
            {
                db.Entry(formEntity).State = formEntity.FormId == 0 ?
                                             EntityState.Added :
                                             EntityState.Modified;
                db.SaveChanges();
            }
            var questions = form.Questions != null?form.Questions.Select(q => new Question
            {
                FormId     = formEntity.FormId,
                QuestionId = q.QuestionId,
                Order      = q.Order,
                Type       = q.Type,
                Name       = q.Name,
                Label      = q.Label,
                Options    = q.Options != null ? q.Options.Select(o => new Option {
                    QuestionId = q.QuestionId,
                    OptionId   = o.OptionId,
                    Label      = o.Label,
                    Value      = o.Label
                }).ToList() : new List <Option>()
            }).ToList() : new List <Question>();

            using (var db = new FormContext())
            {
                questions.ForEach(q => {
                    db.Entry(q).State = q.QuestionId == 0 ?
                                        EntityState.Added :
                                        EntityState.Modified;
                    q.Options.ToList().ForEach(o => db.Entry(o).State = o.OptionId == 0 ?
                                                                        EntityState.Added :
                                                                        EntityState.Modified);
                });
                db.SaveChanges();
            }

            return(formEntity.FormId);
        }
Example #14
0
        public void save(FormViewModel form)
        {
            using (var db = new FormContext())
            {
                var respodent = new Respondent
                {
                    FirstName    = form.RespondentFirstName,
                    LastName     = form.RespondentLastName,
                    EmailAddress = form.RespondentEmailAddress
                };

                var responses = form.Questions.Select(q => new Response {
                    Value = q.Value, QuestionId = q.QuestionId, Respondent = respodent
                }).ToList();

                db.Responses.AddRange(responses);
                db.SaveChanges();
            }
        }
        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            try
            {
                int recordId;
                Int32.TryParse(lblRecordId.Text, out recordId);

                UserLogic newLogic = new UserLogic();

                System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
                SystemUsers currentUser = newLogic.GetCurrentUser(user);

                using (var ctx = new FormContext())
                {
                    var thisForm = ctx.CannotWaitForContainerForms.FirstOrDefault(eof => eof.RecordId == recordId);

                    Comments newComment = new Comments
                    {
                        Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Cannot Wait For Container"),
                        Note          = txtNewComment.Text,
                        RelatedFormId = thisForm.RecordId,
                        SystemComment = false,
                        Timestamp     = DateTime.Now,
                        User          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID)
                    };

                    ctx.Comments.Add(newComment);
                    ctx.SaveChanges();

                    txtNewComment.Text    = "";
                    txtNewComment.Invalid = false;

                    rptrComments.DataBind();
                    Session["NewComment"] = "true";
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #16
0
        public void gvSkus_DeleteItem(int RecordId)
        {
            try
            {
                using (FormContext ctx = new FormContext())
                {
                    SkuQuantity SkuToDelete = ctx.SkuQuantityItems.FirstOrDefault(x => x.RecordId == RecordId);

                    if (SkuToDelete != null)
                    {
                        ctx.SkuQuantityItems.Remove(SkuToDelete);
                        ctx.SaveChanges();
                    }

                    lblAddSkuMessage.Text = "";
                }
            }
            catch (Exception ex)
            {
                lblAddSkuMessage.Text = "Unable to delete Material SKU# and Quantity.  Please contact your system administrator.";
            }
        }
Example #17
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    DateTime            tryInstallDate;
                    Nullable <DateTime> installDate = null;
                    DateTime            tryDueDate;
                    Nullable <DateTime> dueDate = null;
                    Int32         formId;
                    int           statusId;
                    int           expediteCodeId;
                    string        emailListString = lblEmailsSentTo.Text.Replace(" ", "");
                    List <string> emailList       = emailListString.Split(',').ToList <string>();

                    System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
                    UserLogic   uLogic      = new UserLogic();
                    SystemUsers currentUser = uLogic.GetCurrentUser(user);

                    DateTime.TryParse(txtInstallDate.Value, out tryInstallDate);
                    if (txtDueByDate.Value != "")
                    {
                        DateTime.TryParse(txtDueByDate.Value, out tryDueDate);

                        if (tryDueDate.Year > 0001)
                        {
                            dueDate = tryDueDate;
                        }
                    }
                    else
                    {
                        dueDate = null;
                    }

                    if (tryInstallDate.Year > 0001)
                    {
                        installDate = tryInstallDate;
                    }

                    expediteCodeId = Convert.ToInt32(ddlExpediteCode.SelectedValue);
                    statusId       = Convert.ToInt32(ddlStatus.SelectedValue);

                    string accountNumber       = txtAccountNumber.Text;
                    int    accountNumberLength = txtAccountNumber.Text.Length;

                    while (accountNumberLength < 6)
                    {
                        accountNumber = "0" + accountNumber;
                        accountNumberLength++;
                    }

                    using (FormContext ctx = new FormContext())
                    {
                        var   expediteCode    = ctx.ExpediteCodes.FirstOrDefault(c => c.ExpediteCodeID.Equals(expediteCodeId));
                        var   status          = ctx.Statuses.FirstOrDefault(s => s.StatusId.Equals(statusId));
                        Int32 requestedUserId = Convert.ToInt32(ddlRequestedBy.SelectedValue);
                        var   requestedUser   = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == requestedUserId);
                        var   modifiedUser    = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID);

                        Models.ExpeditedOrderForm newForm = new Models.ExpeditedOrderForm
                        {
                            Timestamp           = DateTime.Now,
                            Company             = ddlCompany.SelectedText,
                            Customer            = txtCustomer.Text,
                            AccountNumber       = accountNumber,
                            ExpediteCode        = expediteCode,
                            PurchaseOrderNumber = txtPurchaseOrderNumber.Text,
                            OowOrderNumber      = txtOowOrderNumber.Text,
                            InstallDate         = installDate,
                            SM                    = txtSM.Text,
                            ContactName           = txtContactName.Text,
                            PhoneNumber           = txtPhoneNumber.Text,
                            ShipToName            = txtShipToName.Text,
                            ShipToAddress         = txtShipToAddress.Text,
                            ShipToCity            = txtShipToCity.Text,
                            ShipToState           = txtShipToState.Text,
                            ShipToZip             = txtShipToZip.Text,
                            ShipToPhone           = txtShipToPhone.Text,
                            Status                = ctx.Statuses.FirstOrDefault(s => s.StatusText == ddlStatus.SelectedItem.Text),
                            RequestedUser         = requestedUser,
                            LastModifiedUser      = modifiedUser,
                            SubmittedUser         = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID),
                            DueDate               = dueDate,
                            Priority              = ctx.Priorities.FirstOrDefault(x => x.PriorityText == ddlPriority.SelectedText),
                            LastModifiedTimestamp = DateTime.Now
                        };

                        if (ddlAssignedTo.SelectedIndex != -1)
                        {
                            Int32 assignedUserId = Convert.ToInt32(ddlAssignedTo.SelectedValue);
                            newForm.AssignedUser = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == assignedUserId);
                        }

                        ctx.ExpeditedOrderForms.Add(newForm);
                        ctx.SaveChanges();

                        if (newForm.AssignedUser != null)
                        {
                            Int32 assignedUserId = Convert.ToInt32(ddlAssignedTo.SelectedValue);

                            UserAssignmentAssociation uA = new UserAssignmentAssociation
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                                RelatedFormId = newForm.RecordId,
                                User          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == assignedUserId)
                            };

                            ctx.UserAssignments.Add(uA);
                        }

                        if (newForm.RequestedUser != null)
                        {
                            UserRequestAssociation uR = new UserRequestAssociation
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                                RelatedFormId = newForm.RecordId,
                                User          = requestedUser
                            };

                            ctx.UserRequests.Add(uR);
                        }

                        ctx.SaveChanges();

                        formId = newForm.RecordId;

                        Comments systemComment = new Comments
                        {
                            Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                            Note          = "Request Created By: " + currentUser.DisplayName,
                            RelatedFormId = formId,
                            SystemComment = true,
                            Timestamp     = DateTime.Now
                        };

                        ctx.Comments.Add(systemComment);

                        Comments systemComment2 = new Comments
                        {
                            Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                            Note          = "Requested By: " + requestedUser.DisplayName,
                            RelatedFormId = formId,
                            SystemComment = true,
                            Timestamp     = DateTime.Now
                        };

                        ctx.Comments.Add(systemComment2);

                        if (ddlAssignedTo.SelectedIndex != -1)
                        {
                            Comments systemComment3 = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                                Note          = "Request Assigned To: " + requestedUser.DisplayName,
                                RelatedFormId = formId,
                                SystemComment = true,
                                Timestamp     = DateTime.Now
                            };

                            ctx.Comments.Add(systemComment3);
                        }

                        if (txtComments.Text != "")
                        {
                            Comments firstComment = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                                Note          = txtComments.Text,
                                RelatedFormId = formId,
                                SystemComment = false,
                                Timestamp     = DateTime.Now,
                                User          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID),
                            };

                            ctx.Comments.Add(firstComment);
                            ctx.SaveChanges();
                        }

                        if (ctx.SkuQuantityItems.Any(x => x.TempId == lblRandomIdentifier.Text))
                        {
                            var skus = ctx.SkuQuantityItems.Where(x => x.TempId == lblRandomIdentifier.Text);

                            foreach (var sku in skus)
                            {
                                sku.ExpeditedOrderForm = ctx.ExpeditedOrderForms.FirstOrDefault(x => x.RecordId == formId);
                            }

                            ctx.SaveChanges();
                        }


                        if (lblEmailsSentTo.Text != "")
                        {
                            Comments notifyComment = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Expedited Order"),
                                Note          = "Request Notifications Sent To: " + lblEmailsSentTo.Text,
                                RelatedFormId = formId,
                                SystemComment = true,
                                Timestamp     = DateTime.Now
                            };

                            ctx.Comments.Add(notifyComment);

                            ctx.SaveChanges();

                            TForm submittedForm = ctx.TForms.FirstOrDefault(tf => tf.FormName == "Expedited Order");

                            SendEmail     msg      = new SendEmail();
                            StringBuilder bodyHtml = new StringBuilder();

                            bodyHtml.AppendLine("<div style=\"width:50%; text-align:center;\"><img src=\"http://www.wctingle.com/img/Logo.jpg\" /><br /><br />")
                            .Append("A new Expedited Order Request has been submitted.<br /><br />")
                            .AppendLine("<table style=\"border: 4px solid #d0604c;background-color:#FFF;width:100%;margin-lefT:auto; margin-right:auto;\">")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td colspan=\"4\" style=\"text-align: center;vertical-align: middle;font-weight: bold;font-size: 20px;border: 4px solid #d0604c; color:#FFF; background-color:#bc4445;\">Expedited Order Request</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Company:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(ddlCompany.SelectedText).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%; color:#bc4445\"></td>")
                            .AppendLine("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000\"></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Customer:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtCustomer.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Expedite Code:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(expediteCode.Code).Append(" - ").Append(expediteCode.Description).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Contact Name:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtContactName.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Phone Number:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtPhoneNumber.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr><td colspan=\"4\"><br /></td></tr>");

                            if (ctx.SkuQuantityItems.Any(x => x.ExpeditedOrderForm.RecordId == formId))
                            {
                                bodyHtml.AppendLine("<tr><td colspan=\"4\"><table>");

                                var skus = ctx.SkuQuantityItems.Where(x => x.ExpeditedOrderForm.RecordId == formId);

                                foreach (var sku in skus)
                                {
                                    bodyHtml.AppendLine("<tr>")
                                    .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:20%;color:#bc4445;\">Material SKU#:</td>")
                                    .Append("           <td style=\"text-align:left;font-size:16px;font-weight:bold;width:20%;color:#000;\">").Append(sku.MaterialSku).AppendLine("</td>")
                                    .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:20%;color:#bc4445;\">Quantity Ordered:</td>")
                                    .Append("           <td style=\"text-align:left;font-size:16px;font-weight:bold;width:20%;color:#000;\">").Append(sku.Quantity).AppendLine("</td>")
                                    .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:20%;color:#bc4445;\">Completed:</td>")
                                    .Append("           <td style=\"text-align:left;font-size:16px;font-weight:bold;width:20%;color:#000;\">").Append(sku.Completed.ToString()).AppendLine("</td>")
                                    .AppendLine("    </tr>");
                                }

                                bodyHtml.AppendLine("    </table></td></tr>");
                            }

                            bodyHtml.AppendLine("    <tr><td colspan=\"4\"><br /></td></tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Account Number:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtAccountNumber.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Purchase Order #:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtPurchaseOrderNumber.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">OOW Order Number:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtOowOrderNumber.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">S/M:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtSM.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Install Date:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtInstallDate.Value).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\"></td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\"></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:left;font-size:16px;font-weight:bold;border: 4px solid #d0604c;color:#FFF; background-color:#bc4445;\" colspan=\"4\">Ship To (If different than default)</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Name:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToName.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Street Address:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToAddress.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">City: </td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToCity.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">State:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToState.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Zip:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToZip.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Phone:</td>")
                            .AppendLine("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipToPhone.Text).Append("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("       <td style=\"width:100%;\" colspan=\"4\">")
                            .AppendLine("        <table style=\"border:none; width:100%\">")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td colspan=\"4\">")
                            .AppendLine("                    <span style=\"font-weight:bold; color:#bc4445; text-decoration:underline\">Assignment and Request Details:</span>")
                            .AppendLine("                </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:20%; text-align:right\"><span class=\"formRedText\">Requested By:</span></td>")
                            .Append("                    <td style=\"width:25%; text-align:left\">").AppendLine(ddlRequestedBy.SelectedItem.Text)
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:20%; text-align:right\"><span class=\"formRedText\">Assigned To:</span></td>")
                            .Append("                   <td style=\"width:25%; text-align:left\">");

                            if (ddlAssignedTo.SelectedIndex != -1)
                            {
                                bodyHtml.AppendLine(ddlAssignedTo.SelectedItem.Text);
                            }
                            else
                            {
                                bodyHtml.AppendLine("N/A");
                            }

                            bodyHtml.AppendLine("            </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:18%; text-align:right\"><span class=\"formRedText\">Date Created:</span></td>")
                            .AppendLine("                <td style=\"width:18%; text-align:left\">")
                            .AppendLine(DateTime.Now.ToShortDateString())
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:18%; text-align:right\"><span class=\"formRedText\">Due By:</span></td>")
                            .Append("                    <td style=\"width:18%; text-align:left\">").Append(txtDueByDate.Value).AppendLine("</td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:10%; text-align:right\"><span class=\"formRedText\">Status:</span></td>")
                            .Append("                    <td style=\"width:10%; text-align:left\">").AppendLine(ddlStatus.SelectedText)
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:10%; text-align:right\"><span class=\"formRedText\">Priority:</span></td>")
                            .Append("                    <td style=\"width:10%; text-align:left\">").AppendLine(ddlPriority.SelectedText)
                            .AppendLine("                </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("        </table>")
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .Append("       <td style=\"width:100%; text-align:center\" colspan=\"4\">Created By: ").AppendLine(currentUser.DisplayName)
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .Append("           <td style=\"width:100%; text-align:center\" colspan=\"4\"><span style=\"color:#bc4445; font-weight:bold\">Request Notifications Sent To:</span> <br />")
                            .AppendLine(lblEmailsSentTo.Text)
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("           <td style=\"width:100%; text-align:center\" colspan=\"4\"><br /><br /></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("</table><br /><br />");

                            if (cbSendComments.Checked)
                            {
                                bodyHtml.AppendLine("<div style=\"width:80%; color:#bc4445; margin: 0 auto; text-align:center;\">Comments<br /></div>")
                                .AppendLine("<div style=\"width:80%; background-color:#bc4445; margin: 0 auto; text-align: left; padding:3px; color: white; \">")
                                .Append(txtComments.Text).AppendLine("<br /><br />")
                                .AppendLine("<span style=\"padding-right:15px\">").AppendLine(currentUser.DisplayName).AppendLine("</span>")
                                .AppendLine(DateTime.Now.ToString("MMMM dd, yyyy"))
                                .AppendLine("</div>");
                            }

                            bodyHtml.AppendLine("</div><br /><br />");

                            bool result = msg.SendMail("*****@*****.**", emailList, "Expedited Order Request", bodyHtml.ToString(), submittedForm, formId, currentUser);

                            txtAccountNumber.Enabled       = false;
                            txtContactName.Enabled         = false;
                            txtCustomer.Enabled            = false;
                            txtInstallDate.Disabled        = true;
                            txtMaterialSku.Enabled         = false;
                            txtOowOrderNumber.Enabled      = false;
                            txtPhoneNumber.Enabled         = false;
                            txtPurchaseOrderNumber.Enabled = false;
                            txtQuantityOrdered.Enabled     = false;
                            txtShipToAddress.Enabled       = false;
                            txtShipToCity.Enabled          = false;
                            txtShipToName.Enabled          = false;
                            txtShipToState.Enabled         = false;
                            txtShipToZip.Enabled           = false;
                            txtShipToPhone.Enabled         = false;
                            txtSM.Enabled             = false;
                            ddlExpediteCode.Enabled   = false;
                            ddlCompany.Enabled        = false;
                            ddlRequestedBy.Enabled    = false;
                            ddlAssignedTo.Enabled     = false;
                            txtDueByDate.Disabled     = true;
                            ddlStatus.Enabled         = false;
                            ddlPriority.Enabled       = false;
                            cbNotifyStandard.Enabled  = false;
                            cbNotifyRequester.Enabled = false;
                            cbNotifyOther.Enabled     = false;
                            cbNotifyAssignee.Enabled  = false;
                            cbSendComments.Enabled    = false;
                            txtComments.Enabled       = false;
                            btnAddSkuQuantity.Enabled = false;

                            string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                            Response.Redirect(pageUrl + "?FormAction=add&sendEmail=" + result.ToString());
                        }
                        else
                        {
                            string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                            Response.Redirect(pageUrl + "?FormAction=add&sendEmail=NotRequired");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                pnlCompleted.Visible = true;
                pnlForm.Visible      = false;
                lblMessage.Text      = "An error occured during submission of this request.  <br /><br />It is possible that the form was completed before this error occurred, <br />so please contact your System Administrator before re-submitting.";
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    DateTime            tryDateRequired;
                    Nullable <DateTime> dateRequired = null;
                    Int32               formId;
                    int                 statusId;
                    DateTime            tryDueDate;
                    Nullable <DateTime> dueDate         = null;
                    string              emailListString = lblEmailsSentTo.Text.Replace(" ", "");
                    List <string>       emailList       = emailListString.Split(',').ToList <string>();

                    System.Security.Principal.IPrincipal user = System.Web.HttpContext.Current.User;
                    UserLogic   uLogic      = new UserLogic();
                    SystemUsers currentUser = uLogic.GetCurrentUser(user);

                    DateTime.TryParse(txtDateRequired.Value, out tryDateRequired);

                    if (txtDueByDate.Value != "")
                    {
                        DateTime.TryParse(txtDueByDate.Value, out tryDueDate);

                        if (tryDueDate.Year > 0001)
                        {
                            dueDate = tryDueDate;
                        }
                    }
                    else
                    {
                        dueDate = null;
                    }

                    if (tryDateRequired.Year > 0001)
                    {
                        dateRequired = tryDateRequired;
                    }

                    statusId = Convert.ToInt32(ddlStatus.SelectedValue);

                    using (FormContext ctx = new FormContext())
                    {
                        var   status          = ctx.Statuses.FirstOrDefault(s => s.StatusId.Equals(statusId));
                        Int32 requestedUserId = Convert.ToInt32(ddlRequestedBy.SelectedValue);
                        var   requestedUser   = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == requestedUserId);
                        var   modifiedUser    = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID);

                        Models.OrderCancellationForm newForm = new Models.OrderCancellationForm
                        {
                            Timestamp          = DateTime.Now,
                            Company            = ddlCompany.SelectedValue,
                            OrderNumber        = txtOrderNumber.Text,
                            ArmstrongReference = txtArmstrongReference.Text,
                            Customer           = txtCustomer.Text,
                            PO                    = txtPO.Text,
                            SKU                   = txtSKU.Text,
                            POStatusList          = ddlPOStatus.Text,
                            Line                  = txtLine.Text,
                            LineOfPO              = txtLineOfPO.Text,
                            Size                  = txtSize.Text,
                            DateRequired          = dateRequired.Value,
                            ShipVia               = txtShipVia.Text,
                            Serial                = txtSerial.Text,
                            TruckRoute            = txtTruckRoute.Text,
                            Status                = ctx.Statuses.FirstOrDefault(s => s.StatusText == ddlStatus.SelectedItem.Text),
                            RequestedUser         = requestedUser,
                            LastModifiedUser      = modifiedUser,
                            SubmittedUser         = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID),
                            DueDate               = dueDate,
                            Priority              = ctx.Priorities.FirstOrDefault(x => x.PriorityText == ddlPriority.SelectedText),
                            LastModifiedTimestamp = DateTime.Now
                        };

                        if (ddlAssignedTo.SelectedIndex != -1)
                        {
                            Int32 assignedUserId = Convert.ToInt32(ddlAssignedTo.SelectedValue);
                            newForm.AssignedUser = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == assignedUserId);
                        }

                        ctx.OrderCancellationForms.Add(newForm);
                        ctx.SaveChanges();

                        if (newForm.AssignedUser != null)
                        {
                            Int32 assignedUserId = Convert.ToInt32(ddlAssignedTo.SelectedValue);

                            UserAssignmentAssociation uA = new UserAssignmentAssociation
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                                RelatedFormId = newForm.RecordId,
                                User          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == assignedUserId)
                            };

                            ctx.UserAssignments.Add(uA);
                        }

                        if (newForm.RequestedUser != null)
                        {
                            UserRequestAssociation uR = new UserRequestAssociation
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                                RelatedFormId = newForm.RecordId,
                                User          = requestedUser
                            };

                            ctx.UserRequests.Add(uR);
                        }

                        ctx.SaveChanges();

                        formId = newForm.RecordId;

                        Comments systemComment = new Comments
                        {
                            Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                            Note          = "Request Created By: " + currentUser.DisplayName,
                            RelatedFormId = formId,
                            SystemComment = true,
                            Timestamp     = DateTime.Now
                        };

                        ctx.Comments.Add(systemComment);

                        Comments systemComment2 = new Comments
                        {
                            Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                            Note          = "Requested By: " + requestedUser.DisplayName,
                            RelatedFormId = formId,
                            SystemComment = true,
                            Timestamp     = DateTime.Now
                        };

                        ctx.Comments.Add(systemComment2);

                        if (ddlAssignedTo.SelectedIndex != -1)
                        {
                            Comments systemComment3 = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                                Note          = "Request Assigned To: " + requestedUser.DisplayName,
                                RelatedFormId = formId,
                                SystemComment = true,
                                Timestamp     = DateTime.Now
                            };

                            ctx.Comments.Add(systemComment3);
                        }

                        if (txtComments.Text != "")
                        {
                            Comments firstComment = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                                Note          = txtComments.Text,
                                RelatedFormId = formId,
                                SystemComment = false,
                                Timestamp     = DateTime.Now,
                                User          = ctx.SystemUsers.FirstOrDefault(x => x.SystemUserID == currentUser.SystemUserID),
                            };

                            ctx.Comments.Add(firstComment);
                            ctx.SaveChanges();
                        }

                        if (lblEmailsSentTo.Text != "")
                        {
                            Comments notifyComment = new Comments
                            {
                                Form          = ctx.TForms.FirstOrDefault(x => x.FormName == "Order Cancellation"),
                                Note          = "Request Notifications Sent To: " + lblEmailsSentTo.Text,
                                RelatedFormId = formId,
                                SystemComment = true,
                                Timestamp     = DateTime.Now
                            };

                            ctx.Comments.Add(notifyComment);

                            ctx.SaveChanges();

                            TForm submittedForm = ctx.TForms.FirstOrDefault(tf => tf.FormName == "Order Cancellation");

                            SendEmail     msg      = new SendEmail();
                            StringBuilder bodyHtml = new StringBuilder();

                            bodyHtml.AppendLine("<div style=\"width:50%; text-align:center;\"><img src=\"http://www.wctingle.com/img/Logo.jpg\" /><br /><br />")
                            .Append("A new Order Cancellation Request has been submitted.<br /><br />")
                            .AppendLine("<table style=\"border: 4px solid #d0604c;background-color:#FFF;width:100%;margin-lefT:auto; margin-right:auto;\">")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td colspan=\"4\" style=\"text-align: center;vertical-align: middle;font-weight: bold;font-size: 20px;border: 4px solid #d0604c; color:#FFF; background-color:#bc4445;\">Order Cancellation Request</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Company:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(ddlCompany.SelectedText).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%; color:#bc4445\"></td>")
                            .AppendLine("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000\"></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Order #:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtOrderNumber.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Armstrong Reference:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtArmstrongReference.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Customer:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtCustomer.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">PO:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtPO.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">SKU:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtSKU.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Status of PO:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(ddlPOStatus.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Line:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtLine.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Line of PO:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtLineOfPO.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Size:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtSize.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\"></td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:left;font-size:16px;font-weight:bold;border: 4px solid #d0604c;color:#FFF; background-color:#bc4445;\" colspan=\"4\"></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Date Required:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtDateRequired.Value).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Ship Via:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtShipVia.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Serial:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtSerial.Text).AppendLine("</td>")
                            .AppendLine("        <td style=\"text-align:right;font-size:16px;font-weight:bold;width:25%;color:#bc4445;\">Truck Route:</td>")
                            .Append("        <td style=\"text-align:left;font-size:16px;font-weight:bold;width:25%;color:#000;\">").Append(txtTruckRoute.Text).AppendLine("</td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("       <td style=\"width:100%;\" colspan=\"4\">")
                            .AppendLine("        <table style=\"border:none; width:100%\">")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td colspan=\"4\">")
                            .AppendLine("                    <span style=\"font-weight:bold; color:#bc4445; text-decoration:underline\">Assignment and Request Details:</span>")
                            .AppendLine("                </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:20%; text-align:right\"><span class=\"formRedText\">Requested By:</span></td>")
                            .Append("                    <td style=\"width:25%; text-align:left\">").AppendLine(ddlRequestedBy.SelectedItem.Text)
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:20%; text-align:right\"><span class=\"formRedText\">Assigned To:</span></td>")
                            .Append("                   <td style=\"width:25%; text-align:left\">");

                            if (ddlAssignedTo.SelectedIndex != -1)
                            {
                                bodyHtml.AppendLine(ddlAssignedTo.SelectedItem.Text);
                            }
                            else
                            {
                                bodyHtml.AppendLine("N/A");
                            }

                            bodyHtml.AppendLine("            </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:18%; text-align:right\"><span class=\"formRedText\">Date Created:</span></td>")
                            .AppendLine("                <td style=\"width:18%; text-align:left\">")
                            .AppendLine(DateTime.Now.ToShortDateString())
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:18%; text-align:right\"><span class=\"formRedText\">Due By:</span></td>")
                            .Append("                    <td style=\"width:18%; text-align:left\">").Append(txtDueByDate.Value).AppendLine("</td>")
                            .AppendLine("            </tr>")
                            .AppendLine("            <tr>")
                            .AppendLine("                <td style=\"width:10%; text-align:right\"><span class=\"formRedText\">Status:</span></td>")
                            .Append("                    <td style=\"width:10%; text-align:left\">").AppendLine(ddlStatus.SelectedText)
                            .AppendLine("                </td>")
                            .AppendLine("                <td style=\"width:10%; text-align:right\"><span class=\"formRedText\">Priority:</span></td>")
                            .Append("                    <td style=\"width:10%; text-align:left\">").AppendLine(ddlPriority.SelectedText)
                            .AppendLine("                </td>")
                            .AppendLine("            </tr>")
                            .AppendLine("        </table>")
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .Append("       <td style=\"width:100%; text-align:center\" colspan=\"4\">Created By: ").AppendLine(currentUser.DisplayName)
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .Append("           <td style=\"width:100%; text-align:center\" colspan=\"4\"><span style=\"color:#bc4445; font-weight:bold\">Request Notifications Sent To:</span> <br />")
                            .AppendLine(lblEmailsSentTo.Text)
                            .AppendLine("       </td>")
                            .AppendLine("    </tr>")
                            .AppendLine("    <tr>")
                            .AppendLine("           <td style=\"width:100%; text-align:center\" colspan=\"4\"><br /><br /></td>")
                            .AppendLine("    </tr>")
                            .AppendLine("</table><br /><br />");

                            if (cbSendComments.Checked)
                            {
                                bodyHtml.AppendLine("<div style=\"width:80%; color:#bc4445; margin: 0 auto; text-align:center;\">Comments<br /></div>")
                                .AppendLine("<div style=\"width:80%; background-color:#bc4445; margin: 0 auto; text-align: left; padding:3px; color: white; \">")
                                .Append(txtComments.Text).AppendLine("<br /><br />")
                                .AppendLine("<span style=\"padding-right:15px\">").AppendLine(currentUser.DisplayName).AppendLine("</span>")
                                .AppendLine(DateTime.Now.ToString("MMMM dd, yyyy"))
                                .AppendLine("</div>");
                            }

                            bodyHtml.AppendLine("</div><br /><br />");

                            bool result = msg.SendMail("*****@*****.**", emailList, "Order Cancellation Request", bodyHtml.ToString(), submittedForm, formId, currentUser);

                            txtOrderNumber.Enabled        = false;
                            txtArmstrongReference.Enabled = false;
                            txtCustomer.Enabled           = false;
                            txtPO.Enabled             = false;
                            txtSKU.Enabled            = false;
                            ddlPOStatus.Enabled       = false;
                            txtLine.Enabled           = false;
                            txtLineOfPO.Enabled       = false;
                            txtSize.Enabled           = false;
                            txtDateRequired.Disabled  = true;
                            txtShipVia.Enabled        = false;
                            txtSerial.Enabled         = false;
                            txtTruckRoute.Enabled     = false;
                            ddlCompany.Enabled        = false;
                            ddlRequestedBy.Enabled    = false;
                            ddlAssignedTo.Enabled     = false;
                            txtDueByDate.Disabled     = true;
                            ddlStatus.Enabled         = false;
                            ddlPriority.Enabled       = false;
                            cbNotifyStandard.Enabled  = false;
                            cbNotifyRequester.Enabled = false;
                            cbNotifyOther.Enabled     = false;
                            cbNotifyAssignee.Enabled  = false;
                            cbSendComments.Enabled    = false;
                            txtComments.Enabled       = false;

                            string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                            Response.Redirect(pageUrl + "?FormAction=add&sendEmail=" + result.ToString(), false);
                        }
                        else
                        {
                            string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                            Response.Redirect(pageUrl + "?FormAction=add&sendEmail=NotRequired");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                pnlCompleted.Visible = true;
                pnlForm.Visible      = false;
                lblMessage.Text      = "An error occured during submission of this request.  <br /><br />It is possible that the form was completed before this error occurred, <br />so please contact your System Administrator before re-submitting.";
            }
        }
 public void Save()
 {
     _context.SaveChanges();
 }
Example #20
0
    private static void saveForm(int IdForm)
    {
        FormContext db             = new FormContext();
        Form        f              = db.Forms.Find(IdForm);
        Control     pf             = findControlI(_Page, "PanelForm" + IdForm);
        String      EmailTo        = "";
        String      Subject        = "";
        string      ValueToSubject = "";

        FormRender.IsUpdated = Request.QueryString["IsUpdated"] != null?Convert.ToBoolean(Request.QueryString["IsUpdated"]) : false;


        List <FormResult> frs = new List <FormResult>();
        FormResult        fr1 = new FormResult();

        if (IsUpdated)
        {
            fr1 = db.FormResults.FirstOrDefault(row => row.IdPopupLoad == IdPopupLoad && row.Deleted == 0);
            frs = db.FormResults.Where(row => row.IdFormSaved == fr1.IdFormSaved).ToList();
        }


        FormSaved fs = new FormSaved();

        if (pf != null)
        {
            if (!IsUpdated)
            {
                fs         = new FormSaved();
                fs.Created = DateTime.Now;
                db.FormSaveds.Add(fs);
                db.SaveChanges();
            }
            else
            {
                fs = db.FormSaveds.Find(fr1.IdFormSaved);
            }

            var ET = new EmailTemplate(f.EmailTemplate == null ? "" : f.EmailTemplate);



            string result = "";
            result += setting("EMAIL_PRETEXT") + Environment.NewLine;
            result += "ОБРАЩЕНИЕ №: " + fs.Id + Environment.NewLine;
            ET.AddParam("АОН", (Request.QueryString["AbonentNumber"] != null ? Request.QueryString["AbonentNumber"].ToString() : ""));
            result += "АОН: " + (Request.QueryString["AbonentNumber"] != null ? Request.QueryString["AbonentNumber"].ToString() : "") + Environment.NewLine;
            ET.AddParam("Дата и время обращения", DateTime.Now.ToString());
            result += "Дата и время обращения: " + DateTime.Now + Environment.NewLine;
            ET.AddParam("Оператор", Operator);
            result += "Оператор: " + Operator + Environment.NewLine;
            if (f.IdTask == 4)
            {
                result += getFramePath();
            }
            List <FormField> FormFields = f.FormFields.Where(p => p.Active == 1 && p.Deleted == 0).ToList();

            foreach (FormField ff in FormFields)
            {
                FormResult fr = new FormResult();
                if (IsUpdated)
                {
                    fr = frs.FirstOrDefault(row => row.IdField == ff.Id);
                }
                else
                {
                    fr = new FormResult()
                    {
                        Deleted = Request.QueryString["debug"] != null ? 1 : 0, IdFormSaved = fs.Id, IdPopupLoad = IdPopupLoad, IdField = ff.Id, IdForm = ff.IdForm, IdTask = IdTask, IdProject = IdProject, Active = 1, Created = DateTime.Now, Updated = DateTime.Now
                    }
                };

                System.Type T = null;
                if (ff.FormTypeField.SystemTitle != "")
                {
                    try { T = System.Web.Compilation.BuildManager.GetType("FormField" + ff.FormTypeField.SystemTitle, true); }
                    catch (Exception e) { };
                }
                ;
                if (T == null)
                {
                    switch (ff.FormTypeField.Id)
                    {
                    case 2:
                        handlerFieldDropDownList(fr, ff);
                        if (ff.FormEmails.Count(p => p.IdReferenceBookData == fr.IdValue) > 0)
                        {
                            var objEmail = ff.FormEmails.First(p => p.IdReferenceBookData == fr.IdValue);
                            if (objEmail != null)
                            {
                                EmailTo += (EmailTo == "" ? "" : ", ") + objEmail.Email;
                                Subject += (Subject == "" ? "" : ", ") + objEmail.Subject;
                            }
                            ;
                        }
                        ;
                        break;
                    }
                }
                else
                {
                    object  Obj  = Activator.CreateInstance(T);
                    Control cObj = (Control)Obj.GetType().InvokeMember("handlerResult", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, Obj, new object[] { ff, fr, _Page });
                }
                result += ff.Title + ": " + fr.Value + (fr.Note != "" ? ", " : "") + fr.Note + Environment.NewLine;

                ET.AddParam(ff.Title, fr.Value + (fr.Note != "" ? ", " : "") + fr.Note);

                if (!IsUpdated)
                {
                    db.FormResults.Add(fr);
                }

                if (ff.InSubjectEmail == true)
                {
                    ValueToSubject += (ValueToSubject != "" ? " -> " : "") + fr.Value + (fr.Note != "" ? ", " : "") + fr.Note;
                }
            }

            db.SaveChanges();

            if (f.SendToEmail == 1)
            {
                HiddenField hf       = (HiddenField)findControlI(_Page, "PanelFormHiddenFieldEmail" + IdForm);
                string      emails   = hf.Value;
                Label       Messager = (Label)findControlI(_Page, "MessagerForm" + IdForm);
                if (EmailTo != "")
                {
                    emails += (emails != "" ? "," : "") + EmailTo;
                }

                try
                {
                    if (emails != "")
                    {
                        if (f.IsBodyHtml)
                        {
                            result = result.Replace(Environment.NewLine, "<br/>");
                        }

                        if (f.EmailTemplate != null && f.EmailTemplate != "" && f.IsBodyHtml)
                        {
                            result = ET.GetFullBody();
                        }

                        EmailSender.sendEmail(emails, result, (Subject != "" ? Subject : f.Title) + (ValueToSubject != "" ? (" : " + ValueToSubject) : ""), IdTask, IdProject, IdPopupLoad, true, f.Id, f.IsBodyHtml);

                        Messager.Text      = "Форма отправлена";
                        Messager.Visible   = true;
                        Messager.ForeColor = System.Drawing.Color.Green;
                    }
                }
                catch (Exception err)
                {
                    Messager.Text      = err.Message.ToString();
                    Messager.Visible   = true;
                    Messager.ForeColor = System.Drawing.Color.Red;
                }
            }
            ;

            if (f.HasSaveButton == 1)
            {
                if (f.SendToEmail == 0)
                {
                    Label Messager = (Label)findControlI(_Page, "MessagerForm" + IdForm);
                    Messager.Text      = "Форма сохранена";
                    Messager.Visible   = true;
                    Messager.ForeColor = System.Drawing.Color.Green;
                }
                if (!IsUpdated)
                {
                    foreach (FormField ff in FormFields)
                    {
                        switch (ff.FormTypeField.Id)
                        {
                        case 1: ((TextBox)findControlI(_Page, "FormField" + ff.IdForm + "_" + ff.Id)).Text = ""; break;

                        case 2:
                            DropDownList ddl = (DropDownList)findControlI(_Page, "FormField" + ff.IdForm + "_" + ff.Id);
                            if (ddl.Enabled)
                            {
                                ddl.SelectedIndex = -1;
                            }
                            TextBox tb = (TextBox)findControlI(_Page, "TextBoxForm" + ff.IdForm + "_" + ff.Id);
                            if (tb != null)
                            {
                                tb.Text = "";
                            }
                            break;
                        }
                    }
                }
            }
        }
    }