Example #1
0
        /// <summary>
        /// Applies project default values to the issue
        /// </summary>
        /// <param name="issue">Issue that will be initialized with default values</param>
        private static void SetDefaultValues(Issue issue)
        {
            List <DefaultValue> defValues     = IssueManager.GetDefaultIssueTypeByProjectId(issue.ProjectId);
            DefaultValue        selectedValue = defValues.FirstOrDefault();

            if (selectedValue != null)
            {
                issue.IssueTypeId         = selectedValue.IssueTypeId;
                issue.PriorityId          = selectedValue.PriorityId;
                issue.ResolutionId        = selectedValue.ResolutionId;
                issue.CategoryId          = selectedValue.CategoryId;
                issue.MilestoneId         = selectedValue.MilestoneId;
                issue.AffectedMilestoneId = selectedValue.AffectedMilestoneId;

                if (selectedValue.AssignedUserName != "none")
                {
                    issue.AssignedUserName = selectedValue.AssignedUserName;
                }

                if (selectedValue.OwnerUserName != "none")
                {
                    issue.OwnerUserName = selectedValue.OwnerUserName;
                }

                issue.StatusId = selectedValue.StatusId;

                issue.Visibility = selectedValue.IssueVisibility;

                if (selectedValue.DueDate.HasValue)
                {
                    DateTime date = DateTime.Today;
                    date          = date.AddDays(selectedValue.DueDate.Value);
                    issue.DueDate = date;
                }

                issue.Progress   = selectedValue.Progress;
                issue.Estimation = selectedValue.Estimation;
            }
        }
        /// <summary>
        /// Saves this instance.
        /// </summary>
        /// <param name="entity">The issue attachment to save.</param>
        /// <returns></returns>
        public static bool SaveOrUpdate(IssueAttachment entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            if (entity.IssueId <= Globals.NEW_ID)
            {
                throw (new ArgumentException("Cannot save issue attachment, the issue id is invalid"));
            }
            if (String.IsNullOrEmpty(entity.FileName))
            {
                throw (new ArgumentException("The attachment file name cannot be empty or null"));
            }

            var invalidReason = String.Empty;

            if (!IsValidFile(entity.FileName, out invalidReason))
            {
                throw new ApplicationException(invalidReason);
            }

            //Start new save attachment code
            if (entity.Attachment.Length > 0)
            {
                // save the file to the upload directory
                var projectId = IssueManager.GetById(entity.IssueId).ProjectId;
                var project   = ProjectManager.GetById(projectId);

                if (project.AllowAttachments)
                {
                    entity.ContentType = entity.ContentType.Replace("/x-png", "/png");

                    if (entity.ContentType == "image/bmp")
                    {
                        using (var ms = new MemoryStream(entity.Attachment, 0, entity.Attachment.Length))
                        {
                            ms.Write(entity.Attachment, 0, entity.Attachment.Length);
                            var img = Image.FromStream(ms);
                            img.Save(ms, ImageFormat.Png);
                            ms.Seek(0, SeekOrigin.Begin);
                            entity.Attachment = ms.ToArray();
                        }

                        entity.ContentType = "image/png";
                        entity.FileName    = Path.ChangeExtension(entity.FileName, "png");
                    }

                    entity.Size = entity.Attachment.Length;

                    if (HostSettingManager.Get(HostSettingNames.AttachmentStorageType, 0) == (int)IssueAttachmentStorageTypes.Database)
                    {
                        //save the attachment record to the database.
                        var tempId = DataProviderManager.Provider.CreateNewIssueAttachment(entity);
                        if (tempId > 0)
                        {
                            entity.Id = tempId;
                            return(true);
                        }
                        return(false);
                    }

                    var projectPath = project.UploadPath;

                    try
                    {
                        if (projectPath.Length == 0)
                        {
                            projectPath = project.Id.ToString();
                        }
                        //throw new ApplicationException(String.Format(LoggingManager.GetErrorMessageResource("UploadPathNotDefined"), project.Name));

                        var attachmentGuid  = Guid.NewGuid();
                        var attachmentBytes = entity.Attachment;
                        entity.Attachment = null;    //set attachment to null
                        entity.FileName   = String.Format("{0}.{1}{2}", Path.GetFileNameWithoutExtension(entity.FileName), attachmentGuid, Path.GetExtension(entity.FileName));

                        var uploadedFilePath = string.Empty;

                        // added by WRH 2012-08-18
                        // this to fix the issue where attachments from the mailbox reader cannot be saved due to the lack of a http context.
                        // we need to supply the actual folder path on the entity
                        if (HttpContext.Current != null)
                        {
                            uploadedFilePath = string.Format(@"{0}\{1}", string.Format("{0}{1}", HostSettingManager.Get(HostSettingNames.AttachmentUploadPath), projectPath), entity.FileName);

                            if (uploadedFilePath.StartsWith("~"))
                            {
                                uploadedFilePath = HttpContext.Current.Server.MapPath(uploadedFilePath);
                            }
                        }
                        else
                        {
                            if (entity.ProjectFolderPath.Trim().Length > 0)
                            {
                                uploadedFilePath = string.Format("{0}\\{1}", entity.ProjectFolderPath, entity.FileName);
                            }
                        }

                        //save the attachment record to the database.
                        var tempId = DataProviderManager.Provider.CreateNewIssueAttachment(entity);

                        if (tempId > 0)
                        {
                            entity.Id = tempId;

                            //save file to file system
                            var fi = new FileInfo(uploadedFilePath);

                            if (!Directory.Exists(fi.DirectoryName))
                            {
                                Directory.CreateDirectory(fi.DirectoryName);
                            }

                            File.WriteAllBytes(uploadedFilePath, attachmentBytes);

                            return(true);
                        }

                        return(false);
                    }
                    catch (DirectoryNotFoundException ex)
                    {
                        if (Log.IsErrorEnabled)
                        {
                            Log.Error(String.Format(LoggingManager.GetErrorMessageResource("UploadPathNotFound"), projectPath), ex);
                        }
                        throw;
                    }
                    catch (Exception ex)
                    {
                        if (Log.IsErrorEnabled)
                        {
                            Log.Error(ex.Message, ex);
                        }
                        throw;
                    }
                }
            }

            return(false);
        }
        /// <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);
        }