Exemple #1
0
        /// <summary>
        /// Updates the IssueHistory objects in the changes array list
        /// </summary>
        /// <param name="issueChanges">The issue changes.</param>
        private static void UpdateHistory(IEnumerable <IssueHistory> issueChanges)
        {
            if (issueChanges == null)
            {
                return;
            }

            foreach (var issueHistory in issueChanges)
            {
                issueHistory.TriggerLastUpdateChange = false; // set this to false since we don't trigger it from here
                IssueHistoryManager.SaveOrUpdate(issueHistory);
            }
        }
        /// <summary>
        /// Sends the issue notifications.
        /// </summary>
        /// <param name="issueId">The issue id.</param>
        /// <param name="issueChanges">The issue changes.</param>
        public static void SendIssueNotifications(int issueId, IEnumerable <IssueHistory> issueChanges)
        {
            // validate input
            if (issueId <= Globals.NEW_ID)
            {
                throw (new ArgumentOutOfRangeException("issueId"));
            }

            // TODO - create this via dependency injection at some point.
            IMailDeliveryService mailService = new SmtpMailDeliveryService();

            var issue            = DataProviderManager.Provider.GetIssueById(issueId);
            var issNotifications = DataProviderManager.Provider.GetIssueNotificationsByIssueId(issueId);
            var emailFormatType  = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text);

            var data = new Dictionary <string, object> {
                { "Issue", issue }
            };

            var writer = new System.IO.StringWriter();

            using (System.Xml.XmlWriter xml = new System.Xml.XmlTextWriter(writer))
            {
                xml.WriteStartElement("IssueHistoryChanges");

                foreach (var issueHistory in issueChanges)
                {
                    IssueHistoryManager.SaveOrUpdate(issueHistory);
                    xml.WriteRaw(issueHistory.ToXml());
                }

                xml.WriteEndElement();

                data.Add("RawXml_Changes", writer.ToString());
            }

            var          templateCache  = new List <CultureNotificationContent>();
            var          emailFormatKey = (emailFormatType == EmailFormatType.Text) ? "" : "HTML";
            const string subjectKey     = "IssueUpdatedSubject";
            var          bodyKey        = string.Concat("IssueUpdatedWithChanges", emailFormatKey);

            // get a list of distinct cultures
            var distinctCultures = (from c in issNotifications
                                    select c.NotificationCulture
                                    ).Distinct().ToList();

            // populate the template cache of the cultures needed
            foreach (var culture in from culture in distinctCultures let notificationContent = templateCache.FirstOrDefault(p => p.CultureString == culture) where notificationContent == null select culture)
            {
                templateCache.Add(new CultureNotificationContent().LoadContent(culture, subjectKey, bodyKey));
            }

            var displayname = UserManager.GetUserDisplayName(Security.GetUserName());

            foreach (var notification in issNotifications)
            {
                try
                {
                    //send notifications to everyone except who changed it.
                    if (notification.NotificationUsername.ToLower() == Security.GetUserName().ToLower())
                    {
                        continue;
                    }

                    var user = UserManager.GetUser(notification.NotificationUsername);

                    // skip to the next user if this user is not approved
                    if (!user.IsApproved)
                    {
                        continue;
                    }
                    // skip to next user if this user doesn't have notifications enabled.
                    if (!new WebProfile().GetProfile(user.UserName).ReceiveEmailNotifications)
                    {
                        continue;
                    }

                    var nc = templateCache.First(p => p.CultureString == notification.NotificationCulture);

                    var emailSubject = nc.CultureContents
                                       .First(p => p.ContentKey == subjectKey)
                                       .FormatContent(issue.FullId, displayname);

                    var bodyContent = nc.CultureContents
                                      .First(p => p.ContentKey == bodyKey)
                                      .TransformContent(data);

                    var message = new MailMessage
                    {
                        Subject    = emailSubject,
                        Body       = bodyContent,
                        IsBodyHtml = true
                    };

                    mailService.Send(user.Email, message);
                }
                catch (Exception ex)
                {
                    ProcessException(ex);
                }
            }
        }
        /// <summary>
        /// Deletes the IssueAttachment.
        /// </summary>
        /// <param name="issueAttachmentId">The issue attachment id.</param>
        /// <returns></returns>
        public static bool Delete(int issueAttachmentId)
        {
            var att     = GetById(issueAttachmentId);
            var issue   = IssueManager.GetById(att.IssueId);
            var project = ProjectManager.GetById(issue.ProjectId);

            if (DataProviderManager.Provider.DeleteIssueAttachment(issueAttachmentId))
            {
                try
                {
                    var history = new IssueHistory
                    {
                        IssueId                 = att.IssueId,
                        CreatedUserName         = Security.GetUserName(),
                        DateChanged             = DateTime.Now,
                        FieldChanged            = ResourceStrings.GetGlobalResource(GlobalResources.SharedResources, "Attachment", "Attachment"),
                        OldValue                = att.FileName,
                        NewValue                = ResourceStrings.GetGlobalResource(GlobalResources.SharedResources, "Deleted", "Deleted"),
                        TriggerLastUpdateChange = true
                    };

                    IssueHistoryManager.SaveOrUpdate(history);

                    var changes = new List <IssueHistory> {
                        history
                    };

                    IssueNotificationManager.SendIssueNotifications(att.IssueId, changes);
                }
                catch (Exception ex)
                {
                    if (Log.IsErrorEnabled)
                    {
                        Log.Error(ex);
                    }
                }

                if (HostSettingManager.Get(HostSettingNames.AttachmentStorageType, 0) == (int)IssueAttachmentStorageTypes.FileSystem)
                {
                    //delete IssueAttachment from file system.
                    try
                    {
                        if (string.IsNullOrEmpty(project.UploadPath))
                        {
                            project.UploadPath = project.Id.ToString();//use project id as pathroot
                        }
                        var filePath = String.Format(@"{2}{0}\{1}", project.UploadPath, att.FileName, HostSettingManager.Get(HostSettingNames.AttachmentUploadPath));

                        if (filePath.StartsWith("~"))
                        {
                            filePath = HttpContext.Current.Server.MapPath(filePath);
                        }

                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                        else
                        {
                            Log.Info(String.Format("Failed to locate file {0} to delete, it may have been moved or manually deleted", filePath));
                        }
                    }
                    catch (Exception ex)
                    {
                        //set user to log4net context, so we can use %X{user} in the appenders
                        if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                        {
                            MDC.Set("user", HttpContext.Current.User.Identity.Name);
                        }

                        if (Log.IsErrorEnabled)
                        {
                            Log.Error(String.Format("Error Deleting IssueAttachment - {0}", String.Format("{0}\\{1}", project.UploadPath, att.FileName)), ex);
                        }

                        throw new ApplicationException(LoggingManager.GetErrorMessageResource("AttachmentDeleteError"), ex);
                    }
                }
            }
            return(true);
        }