示例#1
0
        /// <summary>
        /// Deletes the project.
        /// </summary>
        /// <param name="projectId">The project id.</param>
        /// <returns></returns>
        public static bool Delete(int projectId)
        {
            if (projectId <= Globals.NEW_ID)
            {
                throw (new ArgumentOutOfRangeException("projectId"));
            }

            var uploadpath = GetById(projectId).UploadPath;

            if (DataProviderManager.Provider.DeleteProject(projectId))
            {
                DeleteProjectCustomView(projectId);

                try
                {
                    uploadpath = string.Concat(HostSettingManager.Get(HostSettingNames.AttachmentUploadPath), uploadpath);
                    if (uploadpath.StartsWith("~"))
                    {
                        uploadpath = HttpContext.Current.Server.MapPath(uploadpath);
                    }

                    Directory.Delete(uploadpath, true);
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format(LoggingManager.GetErrorMessageResource("DeleteProjectUploadFolderError"), uploadpath, projectId), ex);
                }

                return(true);
            }
            return(false);
        }
示例#2
0
        /// <summary>
        /// Sends the user registered notification.
        /// </summary>
        /// <param name="userName">The user.</param>
        public static void SendUserRegisteredNotification(string userName)
        {
            if (userName == "")
            {
                throw new ArgumentNullException("userName");
            }

            var user = GetUser(userName);

            if (user.ProviderUserKey == null)
            {
                throw new ArgumentNullException("userName");
            }

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

            var          emailFormatType = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text);
            var          emailFormatKey  = (emailFormatType == EmailFormatType.Text) ? "" : "HTML";
            const string subjectKey      = "UserRegisteredSubject";
            var          bodyKey         = string.Concat("UserRegistered", emailFormatKey);
            var          profile         = new WebProfile().GetProfile(user.UserName);

            var nc = new CultureNotificationContent().LoadContent(profile.PreferredLocale, subjectKey, bodyKey);

            var notificationUser = new NotificationUser
            {
                Id           = (Guid)user.ProviderUserKey,
                CreationDate = user.CreationDate,
                Email        = user.Email,
                UserName     = user.UserName,
                DisplayName  = profile.DisplayName,
                FirstName    = profile.FirstName,
                LastName     = profile.LastName,
                IsApproved   = user.IsApproved
            };

            var data = new Dictionary <string, object> {
                { "User", notificationUser }
            };

            var emailSubject = nc.CultureContents
                               .First(p => p.ContentKey == subjectKey)
                               .FormatContent();

            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, null);
        }
示例#3
0
        /// <summary>
        /// Configures the logging.
        /// </summary>
        public static void ConfigureLogging()
        {
            ConfigureAdoNetAppender();

            //if email notification of errors are enabled create a SMTP logging appender.
            if (HostSettingManager.Get(HostSettingNames.EmailErrors, false))
            {
                ConfigureEmailLoggingAppender();
            }
        }
示例#4
0
        /// <summary>
        /// Sends the forgot password email.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="token">The token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// user
        /// or
        /// user
        /// </exception>
        public static void SendForgotPasswordEmail(MembershipUser user, string token)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (user.ProviderUserKey == null)
            {
                throw new ArgumentNullException("user");
            }

            IMailDeliveryService mailService = new SmtpMailDeliveryService();

            var          emailFormatType = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text);
            var          emailFormatKey  = (emailFormatType == EmailFormatType.Text) ? "" : "HTML";
            const string subjectKey      = "ForgotPasswordSubject";
            var          bodyKey         = string.Concat("ForgotPassword", emailFormatKey);
            var          profile         = new WebProfile().GetProfile(user.UserName);

            var nc = new CultureNotificationContent().LoadContent(profile.PreferredLocale, subjectKey, bodyKey);

            var notificationUser = new NotificationUser
            {
                Id           = (Guid)user.ProviderUserKey,
                CreationDate = user.CreationDate,
                Email        = user.Email,
                UserName     = user.UserName,
                DisplayName  = profile.DisplayName,
                FirstName    = profile.FirstName,
                LastName     = profile.LastName,
                IsApproved   = user.IsApproved
            };

            var data = new Dictionary <string, object>
            {
                { "Token", token }
            };

            var emailSubject = nc.CultureContents
                               .First(p => p.ContentKey == subjectKey)
                               .FormatContent();

            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, null);
        }
示例#5
0
        /// <summary>
        /// Clones the project.
        /// </summary>
        /// <param name="projectId">The project id.</param>
        /// <param name="projectName">Name of the project.</param>
        /// <returns></returns>
        public static int CloneProject(int projectId, string projectName)
        {
            if (projectId <= Globals.NEW_ID)
            {
                throw (new ArgumentOutOfRangeException("projectId"));
            }
            if (string.IsNullOrEmpty(projectName))
            {
                throw new ArgumentNullException("projectName");
            }

            var newProjectId = DataProviderManager.Provider.CloneProject(projectId, projectName, Security.GetUserName());

            if (newProjectId != 0)
            {
                var newProject = GetById(newProjectId);

                CustomFieldManager.UpdateCustomFieldView(newProjectId);

                try
                {
                    if (newProject.AllowAttachments && HostSettingManager.Get(HostSettingNames.AttachmentStorageType, 0) == (int)IssueAttachmentStorageTypes.FileSystem)
                    {
                        // set upload path to new Guid
                        newProject.UploadPath = Guid.NewGuid().ToString();

                        DataProviderManager.Provider.UpdateProject(newProject);

                        var fullPath = string.Concat(HostSettingManager.Get(HostSettingNames.AttachmentUploadPath), newProject.UploadPath);

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

                        Directory.CreateDirectory(fullPath);
                    }
                }
                catch (Exception ex)
                {
                    if (Log.IsErrorEnabled)
                    {
                        Log.Error(string.Format(LoggingManager.GetErrorMessageResource("CreateProjectUploadFolderError"), newProject.UploadPath, projectId), ex);
                    }
                }

                HttpContext.Current.Cache.Remove("RolePermission");

                return(newProjectId);
            }

            return(0);
        }
        ///// <summary>
        ///// Stewart Moss
        ///// Apr 14 2010
        /////
        ///// Performs a query containing any number of query clauses on a certain IssueID
        ///// </summary>
        ///// <param name="issueId"></param>
        ///// <param name="queryClauses"></param>
        ///// <returns></returns>
        //public static List<IssueAttachment> PerformQuery(int issueId, List<QueryClause> queryClauses)
        //{
        //    if (issueId < 0)
        //        throw new ArgumentOutOfRangeException("issueId", "must be bigger than 0");

        //    queryClauses.Add(new QueryClause("AND", "IssueId", "=", issueId.ToString(), SqlDbType.Int, false));

        //    return PerformQuery(queryClauses);
        //}

        ///// <summary>
        ///// Stewart Moss
        ///// Apr 14 2010 8:30 pm
        /////
        ///// Performs any query containing any number of query clauses
        ///// WARNING! Will expose the entire IssueAttachment table, regardless of
        ///// project level privileges. (that's why its private for now)
        ///// </summary>
        ///// <param name="queryClauses"></param>
        ///// <returns></returns>
        //private static List<IssueAttachment> PerformQuery(List<QueryClause> queryClauses)
        //{
        //    if (queryClauses == null)
        //        throw new ArgumentNullException("queryClauses");

        //    var lst = new List<IssueAttachment>();
        //    DataProviderManager.Provider.PerformGenericQuery(ref lst, queryClauses, @"SELECT a.*, b.UserName as CreatorUserName, a.Userid as CreatorUserID, b.Username as CreatorDisplayName from BugNet_IssueAttachment as a, aspnet_Users as b  WHERE a.UserId=b.UserID ", @" ORDER BY IssueAttachmentId DESC");

        //    return lst;
        //}


        /// <summary>
        /// Validate the file if we can attach it or not
        /// </summary>
        /// <param name="fileName">The file name to validate</param>
        /// <param name="inValidReason">The reason the validation failed</param>
        /// <returns>True if the file is valid, otherwise false</returns>
        public static bool IsValidFile(string fileName, out string inValidReason)
        {
            inValidReason = String.Empty;
            fileName      = fileName.Trim();
            fileName      = Path.GetFileName(fileName);

            // empty file name
            if (String.IsNullOrEmpty(fileName))
            {
                inValidReason = LoggingManager.GetErrorMessageResource("InvalidFileName");
                return(false);
            }

            var allowedFileTypes = HostSettingManager.Get(HostSettingNames.AllowedFileExtensions, String.Empty).Split(';');
            var fileExt          = Path.GetExtension(fileName);
            var fileOk           = false;

            if (allowedFileTypes.Length > 0 && String.CompareOrdinal(allowedFileTypes[0], "*.*") == 0)
            {
                fileOk = true;
            }
            else
            {
                if (allowedFileTypes.Select(fileType => fileType.Substring(fileType.LastIndexOf("."))).Any(newfileType => newfileType.CompareTo(fileExt) == 0))
                {
                    fileOk = true;
                }
            }

            // valid file type
            if (!fileOk)
            {
                inValidReason = String.Format(LoggingManager.GetErrorMessageResource("InvalidFileType"), fileName);
                return(false);
            }

            // illegal filename characters
            if (Path.GetInvalidFileNameChars().Any(invalidFileNameChar => fileName.Contains(invalidFileNameChar)))
            {
                inValidReason = String.Format(LoggingManager.GetErrorMessageResource("InvalidFileName"), fileName);
                return(false);
            }

            return(true);
        }
示例#7
0
        /// <summary>
        /// Adds the email logging appender.
        /// </summary>
        public static void ConfigureEmailLoggingAppender()
        {
            var hier =
                (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();

            if (hier == null)
            {
                return;
            }

            var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender();

            appender.Name           = "SmtpAppender";
            appender.From           = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty);
            appender.To             = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty);
            appender.Subject        = "BugNET Error";
            appender.SmtpHost       = HostSettingManager.SmtpServer;
            appender.Port           = int.Parse(HostSettingManager.Get(HostSettingNames.SMTPPort));
            appender.Authentication = SmtpAppender.SmtpAuthentication.None;
            appender.Username       = string.Empty;
            appender.Password       = string.Empty;
            appender.EnableSsl      = Boolean.Parse(HostSettingManager.Get(HostSettingNames.SMTPUseSSL));

            if (Convert.ToBoolean(HostSettingManager.Get(HostSettingNames.SMTPAuthentication)))
            {
                appender.Authentication = SmtpAppender.SmtpAuthentication.Basic;
                appender.Username       = String.Format("{0}\\{1}", HostSettingManager.Get(HostSettingNames.SMTPDomain, string.Empty), HostSettingManager.Get(HostSettingNames.SMTPUsername, string.Empty));
                appender.Password       = HostSettingManager.Get(HostSettingNames.SMTPPassword, string.Empty);
            }

            appender.Priority   = System.Net.Mail.MailPriority.High;
            appender.Threshold  = log4net.Core.Level.Error;
            appender.BufferSize = 0;

            //create patternlayout
            var patternLayout = new
                                log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline");

            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
            appender.ActivateOptions();

            //add appender to root logger
            hier.Root.AddAppender(appender);
        }
        /// <summary>
        /// Sends an email to all users that are subscribed to a issue
        /// </summary>
        /// <param name="issueId">The issue id.</param>
        public static void SendIssueNotifications(int issueId)
        {
            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 displayname = UserManager.GetUserDisplayName(Security.GetUserName());

            var          templateCache  = new List <CultureNotificationContent>();
            var          emailFormatKey = (emailFormatType == EmailFormatType.Text) ? "" : "HTML";
            const string subjectKey     = "IssueUpdatedSubject";
            var          bodyKey        = string.Concat("IssueUpdated", 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));
            }

            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>
        /// Sends an email to the user that is assigned to the issue
        /// </summary>
        /// <param name="notification"></param>
        public static void SendNewAssigneeNotification(IssueNotification notification)
        {
            if (notification == null)
            {
                throw (new ArgumentNullException("notification"));
            }
            if (notification.IssueId <= Globals.NEW_ID)
            {
                throw (new ArgumentOutOfRangeException("notification", "The issue id is not valid for this notification"));
            }

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

            var issue           = DataProviderManager.Provider.GetIssueById(notification.IssueId);
            var emailFormatType = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text);

            // data for template
            var data = new Dictionary <string, object> {
                { "Issue", issue }
            };
            var          emailFormatKey = (emailFormatType == EmailFormatType.Text) ? "" : "HTML";
            const string subjectKey     = "NewAssigneeSubject";
            var          bodyKey        = string.Concat("NewAssignee", emailFormatKey);

            var nc = new CultureNotificationContent().LoadContent(notification.NotificationCulture, subjectKey, bodyKey);

            try
            {
                //send notifications to everyone except who changed it.
                if (notification.NotificationUsername.ToLower() == Security.GetUserName().ToLower())
                {
                    return;
                }

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

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

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

                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);
            }
        }
示例#10
0
 /// <summary>
 /// Upgrades the database version.
 /// </summary>
 /// <param name="version">The version.</param>
 /// <returns></returns>
 public static bool UpdateDatabaseVersion(string version)
 {
     return(HostSettingManager.UpdateHostSetting(HostSettingNames.Version, version));
 }
示例#11
0
        /// <summary>
        /// Creates the repository.
        /// </summary>
        /// <param name="repositoryName">Name of the repository.</param>
        /// <returns></returns>
        public static string CreateRepository(string repositoryName)
        {
            var sb = new StringBuilder();

            var repoPath = HostSettingManager.Get(HostSettingNames.RepositoryRootPath) + repositoryName;

            var repoCheckoutPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) +
                                   Path.DirectorySeparatorChar + Guid.NewGuid().ToString();


            var repoUrl = new Uri(repoPath).AbsoluteUri;

            if (!repoUrl.EndsWith("/"))
            {
                repoUrl += "/";
            }

            try
            {
                Directory.CreateDirectory(repoPath);
                Directory.CreateDirectory(repoCheckoutPath);


                sb.AppendLine(RunCommand("svnadmin", "create \"" + repoPath + "\""));

                sb.AppendLine(RunCommand("svn", "mkdir \"" + repoUrl + "trunk\" \"" +
                                         repoUrl + "branches\" \"" + repoUrl + "tags\" \"" + repoUrl + "trunk/doc\" \"" +
                                         repoUrl + "trunk/src\" -m \"Creating initial directories\""));
                sb.AppendLine();


                sb.AppendLine(RunCommand("svn", "checkout \"" + repoUrl + "\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                // Add Issue tracker properties
                var url = HostSettingManager.Get(HostSettingNames.DefaultUrl).Trim();
                if (!url.EndsWith("/"))
                {
                    url += "/";
                }

                //\[?([A-Za-z]{3}-\d+)[\]:]{0,2}(\s((resolved)[,\s]+(fixed|invalid)?)|\s+(open|in progress)?)?
                //this regex locks up TortoiseSVN

                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:logregex \"\\[?([A-Za-z]{3}-\\d+)\\]?.+\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();


                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:label \"Issue Tracker Id:\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:url \"" + url + "Issues/IssueDetail.aspx?id=%BUGID%\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                //sb.AppendLine(RunCommand("svn", "propset -R bugtraq:message \"Issue Tracker Id: %BUGID%\" \"" + repoCheckoutPath + "\""));
                //sb.AppendLine();

                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:number \"false\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:warnifnoissue \"false\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                sb.AppendLine(RunCommand("svn", "propset -R bugtraq:append \"false\" \"" + repoCheckoutPath + "\""));
                sb.AppendLine();

                sb.AppendLine(RunCommand("svn", "commit -m \"Added Issue Tracker properties to the repository\" \"" + repoCheckoutPath + "\""));

                // Add post-commit for the integration.

                if (!repoPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    repoPath += Path.DirectorySeparatorChar;
                }

                if (!String.IsNullOrEmpty(HostSettingManager.Get(HostSettingNames.SvnHookPath)))
                {
                    using (var sw = File.CreateText(repoPath + "hooks" + Path.DirectorySeparatorChar + "post-commit.bat"))
                        sw.WriteLine(HostSettingManager.Get(HostSettingNames.SvnHookPath) + @" post-commit %1 %2");
                }

                return(sb.ToString());
            }
            catch (Exception ex)
            {
                if (Log.IsErrorEnabled)
                {
                    Log.Error("Subversion Repository Creation Error", ex); //TOOD: Localize
                }
                throw;
            }
            finally
            {
                DeleteDirectory(repoCheckoutPath);
            }
        }
示例#12
0
        /// <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);
        }
示例#13
0
        /// <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);
        }
示例#14
0
        /// <summary>
        /// Saves this instance.
        /// </summary>
        /// <returns></returns>
        public static bool SaveOrUpdate(Project entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            if (string.IsNullOrEmpty(entity.Name))
            {
                throw (new ArgumentException("The project name cannot be empty or null"));
            }

            if (entity.Id > 0)
            {
                return(Update(entity));
            }

            entity.UploadPath = Guid.NewGuid().ToString();
            var tempId = DataProviderManager.Provider.CreateNewProject(entity);

            if (tempId <= Globals.NEW_ID)
            {
                return(false);
            }

            entity.Id = tempId;

            CustomFieldManager.UpdateCustomFieldView(entity.Id);

            try
            {
                //create default roles for new project.
                RoleManager.CreateDefaultProjectRoles(entity.Id);
            }
            catch (Exception ex)
            {
                if (Log.IsErrorEnabled)
                {
                    Log.Error(
                        string.Format(
                            LoggingManager.GetErrorMessageResource("CouldNotCreateDefaultProjectRoles"),
                            string.Format("ProjectID= {0}", entity.Id)), ex);
                }
                return(false);
            }

            //create attachment directory
            if (HostSettingManager.Get(HostSettingNames.AttachmentStorageType, 0) == (int)IssueAttachmentStorageTypes.FileSystem)
            {
                var uploadPath = string.Concat(HostSettingManager.Get(HostSettingNames.AttachmentUploadPath), entity.UploadPath);
                if (uploadPath.StartsWith("~"))
                {
                    uploadPath = HttpContext.Current.Server.MapPath(uploadPath);
                }


                try
                {
                    // BGN-1909
                    // Better santization of Upload Paths
                    if (!Utilities.CheckUploadPath(uploadPath))
                    {
                        throw new InvalidDataException(LoggingManager.GetErrorMessageResource("UploadPathInvalid"));
                    }

                    Directory.CreateDirectory(uploadPath);
                }
                catch (Exception ex)
                {
                    if (Log.IsErrorEnabled)
                    {
                        Log.Error(
                            string.Format(
                                LoggingManager.GetErrorMessageResource("CouldNotCreateUploadDirectory"), uploadPath), ex);
                    }
                    return(false);
                }
            }

            return(true);
        }