partial void UpdateTicketAttachment(TicketAttachment instance)
 {
     string user = HttpContext.Current.User.Identity.GetFormattedUserName();
     DateTime dt = DateTime.Now;
     instance.UploadedBy = user;
     instance.UploadedDate = dt;
     instance.Ticket.LastUpdateBy = user;
     instance.Ticket.LastUpdateDate = dt;
     ExecuteDynamicUpdate(instance);
 }
        public Ticket GetNewTicket()
        {
            string details = Page.Request.Form["details"];

            Ticket ticket = null;
            if (Page.IsValid)
            {
                if (!string.IsNullOrEmpty(details))
                {
                    DateTime now = DateTime.Now;
                    string user = Page.User.Identity.GetFormattedUserName();
                    ticket = new Ticket();
                    ticket.Type = TypeDropDownList.SelectedValue;
                    ticket.Category = CategoryDropDownList.SelectedValue;
                    ticket.Title = TitleTextBox.Text;
                    ticket.IsHtml = false;
                    ticket.Details = details;
                    if (!string.IsNullOrEmpty(PriorityDropDownList.SelectedValue))
                    {
                        ticket.Priority = PriorityDropDownList.SelectedValue;
                    }
                    string[] tags = TagManager.GetTagsFromString(TagPickerControl.TagList);
                    ticket.TagList = string.Join(",", tags);
                    ticket.AffectsCustomer = AffectsCustomerCheckBox.Checked;
                    ticket.PublishedToKb = false;
                    ticket.CreatedBy = user;
                    ticket.CreatedDate = now;
                    if (CreateOnBehalfTextBox.Checked)
                    {
                        ticket.Owner = OwnerDropDownList.SelectedValue;
                    }
                    else
                    {
                        ticket.Owner = user;
                    }
                    ticket.CurrentStatus = "Active";
                    ticket.CurrentStatusSetBy = user;
                    ticket.CurrentStatusDate = now;


                    TicketComment openingComment = new TicketComment();
                    if (CreateOnBehalfTextBox.Checked)
                    {
                        openingComment.CommentEvent = string.Format("created the ticket on behalf of {0}", SecurityManager.GetUserDisplayName(ticket.Owner));
                    }
                    else
                    {
                        openingComment.CommentEvent = string.Format("created the ticket");
                    }
                    openingComment.CommentedBy = user;
                    openingComment.CommentedDate = now;


                    HttpFileCollection uploadedFiles = Request.Files;

                    for (int i = 0; i < uploadedFiles.Count; i++)
                    {
                        
                        HttpPostedFile userPostedFile = uploadedFiles[i];
                        if (userPostedFile.ContentLength > 0)
                        {
                            TicketAttachment attachment = new TicketAttachment();
                            string fName = Path.GetFileName(userPostedFile.FileName);//FileUploader.FileName;

                            attachment.FileName = fName;
                            var description = Page.Request.Form[fName];
                            if (!string.IsNullOrEmpty(description))
                            {
                                if (description.Length > 500)
                                {
                                    attachment.FileDescription = description.Substring(0, 500);
                                }
                                else
                                {
                                    attachment.FileDescription = description;
                                }
                            }
                            attachment.FileSize = userPostedFile.ContentLength;//FileUploader.PostedFile.ContentLength;
                            string mtype = userPostedFile.ContentType;
                            attachment.FileType = (string.IsNullOrEmpty(mtype) ? "application/octet-stream" : mtype);
                            byte[] fileContent = new byte[userPostedFile.ContentLength];
                            userPostedFile.InputStream.Read(fileContent, 0, userPostedFile.ContentLength);//FileUploader.FileBytes;
                            attachment.FileContents = fileContent;
                            ticket.TicketAttachments.Add(attachment);
                        }
                    }

                    ticket.TicketComments.Add(openingComment);

                    foreach (string tag in tags)
                    {
                        TicketTag tTag = new TicketTag();
                        tTag.TagName = tag;
                        ticket.TicketTags.Add(tTag);
                    }
                }
                else
                {
                    lblDetailsRequired.Visible = true;
                }

            }
            return ticket;
        }
 partial void DeleteTicketAttachment(TicketAttachment instance);
 partial void UpdateTicketAttachment(TicketAttachment instance);
 partial void InsertTicketAttachment(TicketAttachment instance);
		private void detach_TicketAttachments(TicketAttachment entity)
		{
			this.SendPropertyChanging();
			entity.Ticket = null;
		}
        private TicketComment PerformActivity()
        {
            List<string> eventDetailItems = null;
            string eventText = null;
            if (CheckIsActivityAllowed())
            {
                switch (Activity)
                {
                    case "NoChanges":
                        break;
                    case "EditTicket":
                        eventText = "заявка отредактирована";
                        break;
                    case "AddComment":
                        if (EnforceRequiredComment())
                        {
                            if (ResolvedCheckBoxContainer.Visible && ResolveCheckBox.Checked)
                            {
                                eventText = ResolveTicket(eventText);
                            }
                            else
                            {
                                eventText = "комментарий добавлен";
                            }

                        }
                        break;

                    case "AddAttachments":

                        eventDetailItems = new List<string>();

                        HttpFileCollection uploadedFiles = Request.Files;
                        var newFiles = 0;
                        var updatedFiles = 0;
                        var removedFiles = 0;
                        for (int i = 0; i < uploadedFiles.Count; i++)
                        {

                            HttpPostedFile userPostedFile = uploadedFiles[i];
                            if (userPostedFile.ContentLength > 0)
                            {
                                newFiles++;
                                TicketAttachment attachment = new TicketAttachment();
                                string fName = Path.GetFileName(userPostedFile.FileName);//FileUploader.FileName;

                                attachment.FileName = fName;
                                var description = Page.Request.Form[fName];
                                if (!string.IsNullOrEmpty(description))
                                {
                                    if (description.Length > 500)
                                    {
                                        attachment.FileDescription = description.Substring(0, 500);
                                    }
                                    else
                                    {
                                        attachment.FileDescription = description;
                                    }
                                }
                                attachment.FileSize = userPostedFile.ContentLength;//FileUploader.PostedFile.ContentLength;
                                string mtype = userPostedFile.ContentType;
                                attachment.FileType = (string.IsNullOrEmpty(mtype) ? "application/octet-stream" : mtype);
                                byte[] fileContent = new byte[userPostedFile.ContentLength];
                                userPostedFile.InputStream.Read(fileContent, 0, userPostedFile.ContentLength);//FileUploader.FileBytes;
                                attachment.FileContents = fileContent;
                                TicketToDisplay.TicketAttachments.Add(attachment);
                                eventDetailItems.Add(string.Format("Новое приложение: {0}", attachment.FileName));
                            }

                            foreach (RepeaterItem item in AttachmentsRepeater.Items)
                            {
                                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                                {
                                    var AttachmentUpdateId = (HiddenField)item.FindControl("AttachmentUpdateId");
                                    var AttachmentDescription = (TextBox)item.FindControl("AttachmentDescription");
                                    var DeleteAttachmentCheckBox = (CheckBox)item.FindControl("DeleteAttachmentCheckBox");

                                    var modAttachment = TicketToDisplay.TicketAttachments.SingleOrDefault(ta => ta.FileId == Convert.ToInt32(AttachmentUpdateId.Value));

                                    if (DeleteAttachmentCheckBox.Checked)
                                    {
                                        eventDetailItems.Add(string.Format("Removed attachment: {0}", modAttachment.FileName));
                                        removedFiles++;
                                        DeleteTicketAttachment(modAttachment.FileId);
                                        //TicketToDisplay.TicketAttachments.Remove(modAttachment);
                                        eventText = "приложение удалено";
                                    }
                                    else if (modAttachment.FileDescription != AttachmentDescription.Text)
                                    {
                                        eventDetailItems.Add(string.Format("Updated attachment: {0}", modAttachment.FileName));
                                        updatedFiles++;
                                        modAttachment.FileDescription = AttachmentDescription.Text;
                                        eventText = "изменения сохранены";
                                    }
                                }
                            }

                            if ((newFiles + removedFiles + updatedFiles) > 0)
                            {

                                eventText = "изменить приложение к заявке";
                            }
                        }

                        break;
                    case "SupplyInfo":
                        if (EnforceRequiredComment())
                        {
                            if (SupplyInfoActivateTicketCheckBox.Checked)
                            {
                                eventText = "дополнительная информация предоставлена";

                                TicketToDisplay.CurrentStatus = "Active";
                                TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                                TicketToDisplay.CurrentStatusDate = DateTime.Now;
                            }
                            else
                            {
                                eventText = "комментарий добавлен";
                            }
                        }
                        break;
                    case "Resolve":
                        if (EnforceRequiredComment())
                        {
                            eventText = ResolveTicket(eventText);
                        }
                        break;
                    case "RequestMoreInfo":
                        if (EnforceRequiredComment())
                        {
                            eventText = "запрос дополнительной информации отправлен";
                            TicketToDisplay.CurrentStatus = "More Info";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                    case "CancelMoreInfo":
                        eventText = GetOptionalCommentEventText("запрос дополнительной информации отменен");
                        TicketToDisplay.CurrentStatus = "Active";
                        TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                        TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        break;
                    case "CloseTicket":
                        eventText = GetOptionalCommentEventText("заявка закрыта");
                        TicketToDisplay.CurrentStatus = "Closed";
                        TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                        TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        break;
                    case "ReopenTicket":

                        if (EnforceRequiredComment())
                        {
                            eventText = "заявка снова открыта";

                            if ((SecurityManager.IsStaff && Page.User.Identity.GetFormattedUserName() != TicketToDisplay.Owner && ReopenOwnedByMe.Checked) || (!SecurityManager.IsStaff && Page.User.Identity.GetFormattedUserName() != TicketToDisplay.Owner))
                            {
                                TicketToDisplay.Owner = Page.User.Identity.GetFormattedUserName();
                                eventText = eventText + " как владелец";
                            }
                            if (SecurityManager.IsStaff && ReopenAssignToMe.Checked)
                            {
                                TicketToDisplay.AssignedTo = Page.User.Identity.GetFormattedUserName();
                                eventText = eventText + "назначить на себя";
                            }
                            else
                            {
                                TicketToDisplay.AssignedTo = null;
                            }

                            TicketToDisplay.CurrentStatus = "Active";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                    case "TakeOver":

                        TicketToDisplay.CurrentStatus = "Active";
                        string oldAssigned = TicketToDisplay.AssignedTo;

                        if (!string.IsNullOrEmpty(oldAssigned))
                        {
                            eventText = GetOptionalCommentEventText(string.Format("заявку принял от - {0}", SecurityManager.GetUserDisplayName(oldAssigned)));
                        }
                        else
                        {
                            eventText = GetOptionalCommentEventText("принял заявку на себя");
                        }

                        TicketToDisplay.AssignedTo = Page.User.Identity.GetFormattedUserName();

                        break;
                    case "Assign":
                        TicketToDisplay.CurrentStatus = "Active";
                        string oldAssignedDisplay = SecurityManager.GetUserDisplayName(TicketToDisplay.AssignedTo);
                        string newAssignedDisplay = SecurityManager.GetUserDisplayName(AssignDropDownList.SelectedValue);
                        if (string.IsNullOrEmpty(TicketToDisplay.AssignedTo))
                        {
                            eventText = string.Format("заявка назначена - {0}", newAssignedDisplay);
                        }
                        else if (TicketToDisplay.AssignedTo == Page.User.Identity.Name)
                        {
                            eventText = string.Format("заявка пришла от {0}", newAssignedDisplay);
                        }
                        else
                        {
                            eventText = string.Format("заявка переназначена от {0} - {1}", oldAssignedDisplay, newAssignedDisplay);
                        }

                        if (TicketToDisplay.Priority != PriorityEdit.SelectedValue)
                        {
                            TicketToDisplay.Priority = PriorityEdit.SelectedValue;
                            eventText = string.Format("{0} с приоритетом {1}", eventText, TicketToDisplay.Priority);
                        }

                        eventText = GetOptionalCommentEventText(eventText);

                        TicketToDisplay.AssignedTo = AssignDropDownList.SelectedValue;
                        break;
                    case "GiveUp":
                        if (EnforceRequiredComment())
                        {
                            eventText = "отказался от заявки";
                            TicketToDisplay.AssignedTo = null;
                        }
                        break;
                    case "ForceClose":
                        if (EnforceRequiredComment())
                        {
                            eventText = "заявка закрыта принудительно";
                            TicketToDisplay.CurrentStatus = "Closed";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                }
            }
            TicketComment comment = null;
            if (eventText != null)
            {
                comment = new TicketComment();
                comment.IsHtml = false;
                comment.CommentEvent = eventText;

                StringBuilder sb = new StringBuilder();
                if (eventDetailItems != null)
                {
                    foreach (var v in eventDetailItems)
                    {

                        sb.Append("<div class='MultiFieldEditContainer'>");
                        sb.Append("<div class='MultiFieldEditFactsContainer'>");
                        sb.Append(v);
                        sb.Append("</div>");
                        sb.Append("</div>");
                    }
                }

                var commentText = Request.Form["comments"];
                if (!string.IsNullOrEmpty(commentText))
                {
                    commentText = commentText.Trim();
                }
                if (sb.Length > 1 && !string.IsNullOrEmpty(commentText))
                {
                    sb.Append("\n\n------------\n\n");

                }

                if (!string.IsNullOrEmpty(commentText))
                {
                    sb.Append(commentText);
                }
                comment.Comment = sb.ToString();
            }
            return comment;
        }
        private TicketComment PerformActivity()
        {
            List<string> eventDetailItems = null;
            string eventText = null;
            if (CheckIsActivityAllowed())
            {
                switch (Activity)
                {
                    case "NoChanges":
                        break;
                    case "EditTicket":
                        eventText = "has edited ticket fields";
                        break;
                    case "AddComment":
                        if (EnforceRequiredComment())
                        {
                            if (ResolvedCheckBoxContainer.Visible && ResolveCheckBox.Checked)
                            {
                                eventText = ResolveTicket(eventText);
                            }
                            else
                            {
                                eventText = "added comment";
                            }

                        }
                        break;

                    case "AddAttachments":

                        eventDetailItems = new List<string>();

                        HttpFileCollection uploadedFiles = Request.Files;
                        var newFiles = 0;
                        var updatedFiles = 0;
                        var removedFiles = 0;
                        for (int i = 0; i < uploadedFiles.Count; i++)
                        {

                            HttpPostedFile userPostedFile = uploadedFiles[i];
                            if (userPostedFile.ContentLength > 0)
                            {
                                newFiles++;
                                TicketAttachment attachment = new TicketAttachment();
                                string fName = Path.GetFileName(userPostedFile.FileName);//FileUploader.FileName;

                                

                                attachment.FileName = fName;
                                var description = Page.Request.Form[fName];
                                if (!string.IsNullOrEmpty(description))
                                {
                                    if (description.Length > 500)
                                    {
                                        attachment.FileDescription = description.Substring(0, 500);
                                    }
                                    else
                                    {
                                        attachment.FileDescription = description;
                                    }
                                }
                                attachment.FileSize = userPostedFile.ContentLength;//FileUploader.PostedFile.ContentLength;
                                string mtype = userPostedFile.ContentType;
                                attachment.FileType = (string.IsNullOrEmpty(mtype) ? "application/octet-stream" : mtype);
                                byte[] fileContent = new byte[userPostedFile.ContentLength];
                                userPostedFile.InputStream.Read(fileContent, 0, userPostedFile.ContentLength);//FileUploader.FileBytes;
                                attachment.FileContents = fileContent;
                                TicketToDisplay.TicketAttachments.Add(attachment);
                                eventDetailItems.Add(string.Format("New attachment: {0}", attachment.FileName));
                            }

                            foreach (RepeaterItem item in AttachmentsRepeater.Items)
                            {
                                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                                {
                                    var AttachmentUpdateId = (HiddenField)item.FindControl("AttachmentUpdateId");
                                    var AttachmentDescription = (TextBox)item.FindControl("AttachmentDescription");
                                    var DeleteAttachmentCheckBox = (CheckBox)item.FindControl("DeleteAttachmentCheckBox");

                                    var modAttachment = TicketToDisplay.TicketAttachments.SingleOrDefault(ta => ta.FileId == Convert.ToInt32(AttachmentUpdateId.Value));

                                    if (DeleteAttachmentCheckBox.Checked)
                                    {
                                        eventDetailItems.Add(string.Format("Removed attachment: {0}", modAttachment.FileName));
                                        removedFiles++;
                                        DeleteTicketAttachment(modAttachment.FileId);
                                        //TicketToDisplay.TicketAttachments.Remove(modAttachment);
                                        eventText = "removed attachment";
                                    }
                                    else if (modAttachment.FileDescription != AttachmentDescription.Text)
                                    {
                                        eventDetailItems.Add(string.Format("Updated attachment: {0}", modAttachment.FileName));
                                        updatedFiles++;
                                        modAttachment.FileDescription = AttachmentDescription.Text;
                                        eventText = "updated attachment description";
                                    }
                                }
                            }

                            if ((newFiles + removedFiles + updatedFiles) > 0)
                            {

                                eventText = "modified ticket attachments";
                            }
                        }

                        break;
                    case "SupplyInfo":
                        if (EnforceRequiredComment())
                        {
                            if (SupplyInfoActivateTicketCheckBox.Checked)
                            {
                                eventText = "has provided more information";

                                TicketToDisplay.CurrentStatus = "Active";
                                TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                                TicketToDisplay.CurrentStatusDate = DateTime.Now;
                            }
                            else
                            {
                                eventText = "added comment";
                            }
                        }
                        break;
                    case "Resolve":
                        if (EnforceRequiredComment())
                        {
                            eventText = ResolveTicket(eventText);
                        }
                        break;
                    case "RequestMoreInfo":
                        if (EnforceRequiredComment())
                        {
                            eventText = "has requested more information";
                            TicketToDisplay.CurrentStatus = "More Info";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                    case "CancelMoreInfo":
                        eventText = GetOptionalCommentEventText("has cancelled the request for more information");
                        TicketToDisplay.CurrentStatus = "Active";
                        TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                        TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        break;
                    case "CloseTicket":
                        eventText = GetOptionalCommentEventText("has closed the ticket");
                        TicketToDisplay.CurrentStatus = "Closed";
                        TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                        TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        break;
                    case "ReopenTicket":
                        if (EnforceRequiredComment())
                        {
                            eventText = "has re-opened the ticket";

                            if ((SecurityManager.IsStaff && Page.User.Identity.GetFormattedUserName() != TicketToDisplay.Owner && ReopenOwnedByMe.Checked) || (!SecurityManager.IsStaff && Page.User.Identity.GetFormattedUserName() != TicketToDisplay.Owner))
                            {
                                TicketToDisplay.Owner = Page.User.Identity.GetFormattedUserName();
                                eventText = eventText + " as the owner";
                            }
                            if (SecurityManager.IsStaff && ReopenAssignToMe.Checked)
                            {
                                TicketToDisplay.AssignedTo = Page.User.Identity.GetFormattedUserName();
                                eventText = eventText + " and assigned it to themself";
                            }
                            else
                            {
                                TicketToDisplay.AssignedTo = null;
                            }

                            TicketToDisplay.CurrentStatus = "Active";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                    case "TakeOver":

                        string oldAssigned = TicketToDisplay.AssignedTo;

                        if (!string.IsNullOrEmpty(oldAssigned))
                        {
                            eventText = GetOptionalCommentEventText(string.Format("has taken over the ticket from {0}", SecurityManager.GetUserDisplayName(oldAssigned)));
                        }
                        else
                        {
                            eventText = GetOptionalCommentEventText("has taken over the ticket");
                        }

                        TicketToDisplay.AssignedTo = Page.User.Identity.GetFormattedUserName();

                        break;
                    case "Assign":
                        string oldAssignedDisplay = SecurityManager.GetUserDisplayName(TicketToDisplay.AssignedTo);
                        string newAssignedDisplay = SecurityManager.GetUserDisplayName(AssignDropDownList.SelectedValue);
                        if (string.IsNullOrEmpty(TicketToDisplay.AssignedTo))
                        {
                            eventText = string.Format("assigned the ticket to {0}", newAssignedDisplay);
                        }
                        else if (TicketToDisplay.AssignedTo == Page.User.Identity.Name)
                        {
                            eventText = string.Format("passed the ticket to {0}", newAssignedDisplay);
                        }
                        else
                        {
                            eventText = string.Format("reassigned the ticket from {0} to {1}", oldAssignedDisplay, newAssignedDisplay);
                        }

                        if (TicketToDisplay.Priority != PriorityEdit.SelectedValue)
                        {
                            TicketToDisplay.Priority = PriorityEdit.SelectedValue;
                            eventText = string.Format("{0} at a priority of {1}", eventText, TicketToDisplay.Priority);
                        }

                        eventText = GetOptionalCommentEventText(eventText);

                        TicketToDisplay.AssignedTo = AssignDropDownList.SelectedValue;
                        break;
                    case "GiveUp":
                        if (EnforceRequiredComment())
                        {
                            eventText = "has given up on the ticket";
                            TicketToDisplay.AssignedTo = null;
                        }
                        break;
                    case "ForceClose":
                        if (EnforceRequiredComment())
                        {
                            eventText = "has closed the ticket by force";
                            TicketToDisplay.CurrentStatus = "Closed";
                            TicketToDisplay.CurrentStatusSetBy = Page.User.Identity.GetFormattedUserName();
                            TicketToDisplay.CurrentStatusDate = DateTime.Now;
                        }
                        break;
                }
            }
            TicketComment comment = null;
            if (eventText != null)
            {
                comment = new TicketComment();
                comment.IsHtml = false;
                comment.CommentEvent = eventText;

                StringBuilder sb = new StringBuilder();
                if (eventDetailItems != null)
                {
                    foreach (var v in eventDetailItems)
                    {

                        sb.Append("<div class='MultiFieldEditContainer'>");
                        sb.Append("<div class='MultiFieldEditFactsContainer'>");
                        sb.Append(v);
                        sb.Append("</div>");
                        sb.Append("</div>");
                    }
                }

                var commentText = Request.Form["comments"];
                if (!string.IsNullOrEmpty(commentText))
                {
                    commentText = commentText.Trim();
                }
                if (sb.Length > 1 && !string.IsNullOrEmpty(commentText))
                {
                    sb.Append("\n\n------------\n\n");

                }

                if (!string.IsNullOrEmpty(commentText))
                {
                    sb.Append(commentText);
                }
                comment.Comment = sb.ToString();
            }
            return comment;
        }