Ejemplo n.º 1
0
        //called when the timeout has expired which was waiting for pending changes.
        private static void PostChangesToSlack(IssueDtoEventArgs args, GlobalConfigurationWidgetData <SlackConfigData> data, string channel, DateTime createDate)
        {
            var issueManager = GeminiApp.GetManager <IssueManager>(args.User);
            var userManager  = GeminiApp.GetManager <UserManager>(args.User);
            var userDto      = userManager.Convert(args.User);
            var issue        = issueManager.Get(args.Issue.Id);
            //get the changelog of all changes since the create date (minus a second to avoid missing the initial change)
            var changelog = issueManager.GetChangeLog(issue, userDto, userDto, createDate.AddSeconds(-1));

            changelog.RemoveAll(c => c.Entity.AttributeChanged == ItemAttributeVisibility.AssociatedComments); // No need to show comments in updates as we already do that in the AfterComment event.
            if (changelog.Count == 0)
            {
                return;                   // No changes made!
            }
            var fields = changelog
                         .Select(a => new
            {
                title  = a.Field,
                value  = StripHTML(a.FullChange),
                _short = a.Entity.AttributeChanged != ItemAttributeVisibility.Description && a.Entity.AttributeChanged != ItemAttributeVisibility.AssociatedComments
            });

            QuickSlack.Send(data.Value.SlackAPIEndpoint, channel, string.Format("{0} updated issue <{1}|{2} - {3}>"
                                                                                , args.User.Fullname, args.BuildIssueUrl(args.Issue), args.Issue.IssueKey, args.Issue.Title),
                            "details attached",
                            "good",             //todo colors here based on something
                            fields.ToArray());
        }
Ejemplo n.º 2
0
            public ActionResult Authenticate(string code, int state)
            {
                GitHub gitHub = new GitHub(); //Creates a new GitHub object

                UserWidgetData <List <UserWidgetDataDetails> > userDataRaw = GeminiContext.UserWidgetStore.Get <List <UserWidgetDataDetails> >(CurrentUser.Entity.Id, Constants.AppId, Constants.ControlId);

                if (userDataRaw != null)
                {
                    var data = userDataRaw.Value.Find(f => f.Provider == SourceControlProvider.GitHub && f.AccessToken.IsEmpty());

                    // Need to check that state is the same as we've sent otherwise ABORT (cross-site request forgery attacks) !
                    if (!code.IsEmpty() && CurrentUser.Entity.Id == state)
                    {
                        if (data != null)
                        {
                            var password = SecretsHelper.Decrypt(data.Password, SecretsHelper.EncryptionKey);

                            try
                            {
                                var response = gitHub.GetResponse(string.Format("https://github.com/login/oauth/access_token?client_id={0}&client_secret={1}&code={2}&state={3}", data.Username, password, code, state), RestSharp.Method.GET);

                                if (response != null)
                                {
                                    var token = response.Content.FromJson <AuthenticateToken>();

                                    if (token.access_token.IsNullOrWhiteSpace())
                                    {
                                        GeminiApp.LogException(new Exception(response.Content.FromJson <Error>().error)
                                        {
                                            Source = "GitHub Authentication"
                                        }, false);
                                        gitHub.DeleteLoginDetails(CurrentUser, data, GeminiContext);
                                        //If request fails we need to make sure we delete the record associated with this authentication request from DB. Otherwise we'll have several records with empty access token
                                    }
                                    else
                                    {
                                        data.AccessToken = token.access_token;
                                        gitHub.SaveLoginDetails(CurrentUser, data, GeminiContext);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                GeminiApp.LogException(ex, false);
                            }
                        }
                    }
                    else
                    {
                        GeminiApp.LogException(new UnauthorizedAccessException("Code/State invalid")
                        {
                            Source = SourceControlProvider.GitHub.ToString()
                        }, false);

                        gitHub.DeleteLoginDetails(CurrentUser, data, GeminiContext);
                    }
                }

                return(Redirect(CurrentProject.HomePageUrl));
            }
Ejemplo n.º 3
0
        /// <summary>
        /// This creates an auditlog (history) for the watcher and custom field manipulations
        /// </summary>
        /// <param name="context"></param>
        /// <param name="issueId"></param>
        /// <param name="issueProjectId"></param>
        /// <param name="customField"></param>
        /// <param name="beforeValue"></param>
        /// <param name="afterValue"></param>
        /// <param name="userId"></param>
        /// <param name="username"></param>
        public void CreateAuditlog(GeminiContext context, int issueId, int issueProjectId, CustomFieldDataDto customField, string beforeValue, string afterValue, int userId, string username)
        {
            try
            {
                IssueAuditManager issueAuditManager = new IssueAuditManager(GeminiApp.Cache(), GeminiApp.UserContext(), context);
                UserManager       userManager       = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), context);
                IssueAudit        audit             = issueAuditManager.GetIssueAuditObject(issueId, issueProjectId);
                audit.UserId   = userId;
                audit.Fullname = username;

                if (customField == null)
                {
                    issueAuditManager.LogChange(audit, ItemAttributeVisibility.AssociatedWatchers,
                                                string.Empty, string.Empty, beforeValue, afterValue);
                }
                else
                {
                    issueAuditManager.LogChange(audit, ItemAttributeVisibility.AssociatedCustomFields, customField.Entity.CustomFieldId.ToString(),
                                                string.Empty, string.Empty, beforeValue, afterValue);
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
        }
Ejemplo n.º 4
0
        public IRestResponse GetResponse(string url, RestSharp.Method method)
        {
            RestClient client = new RestClient(url);

            RestSharp.RestRequest request = new RestSharp.RestRequest(method);
            var response = client.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                GeminiApp.LogException(new ApplicationException(response.Content)
                {
                    Source = "GitHub"
                }, false);
                throw new ApplicationException(response.Content);
            }

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                GeminiApp.LogException(new UnauthorizedAccessException(response.Content)
                {
                    Source = "GitHub"
                }, false);
                throw new UnauthorizedAccessException(response.Content);
            }

            return(response);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Adds a watcher if it has the same domain as the email address. Only if user is not watcher as on this task.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="domain"></param>
        /// <param name="issueParam"></param>
        /// <param name="userId"></param>
        /// <param name="username"></param>
        /// <param name="createAudit"></param>
        private void AddWatcherFromDomain(GeminiContext context, string domain, IssueDto issueParam, int userId, string username, bool createAudit)
        {
            try
            {
                IssueDto       issue       = issueParam;
                Helper         helper      = new Helper();
                UserManager    usermanager = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), context);
                List <UserDto> users       = usermanager.GetActiveUsers();

                foreach (UserDto user in users)
                {
                    // Only if not already watcher on this task
                    if (!issue.Entity.Watchers.Contains(user.Entity.Id.ToString()))
                    {
                        string activeUserDomain = helper.FindDomain(user.Entity.Email);
                        if (domain == activeUserDomain)
                        {
                            issue.Entity.AddWatcher(user.Entity.Id);

                            if (createAudit)
                            {
                                string watcher = user.Entity.Fullname;
                                helper.CreateAuditlog(context, issue.Id, issue.Project.Id, null, "", watcher, userId, username);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Add user with the same domain (superuser) as watcher.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="issueParam"></param>
        /// <param name="user"></param>
        /// <param name="createAudit"></param>
        private void AddSuperuser(GeminiContext context, IssueDto issueParam, User user, bool createAudit)
        {
            try
            {
                IssueDto issue  = issueParam;
                Helper   helper = new Helper();
                if ((issue.CustomFields.Count > 0) && (!issue.CustomFields.Find(field => field.Name.Equals(helper.GetAppConfigValue("customFieldNameDomain"))).ToString().Equals(null)))
                {
                    // Alternatively .Entity.Data could be chosen.
                    string domain = helper.GetFormattedDataErstellerOE(issue);

                    // If there is something to consider
                    if (helper.GetAppConfigValue("blacklist") != null)
                    {
                        // It has to be considered that we already are the superusers of erz.be.ch (and potentially other domains)
                        string   forbiddenDomains = helper.GetAppConfigValue("blacklist");
                        string[] domains          = forbiddenDomains.Split(',');

                        if (!Array.Exists(domains, element => element == domain))
                        {
                            AddWatcherFromDomain(context, domain, issue, user.Id, user.Fullname, createAudit);
                        }
                    }
                    else
                    {
                        AddWatcherFromDomain(context, domain, issue, user.Id, user.Fullname, createAudit);
                    }
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
        }
Ejemplo n.º 7
0
        public IRestResponse GetResponse(string url, RestSharp.Method method)
        {
            RestClient client = new RestClient(url);

            client.Authenticator = new HttpBasicAuthenticator(Username, Password);

            RestSharp.RestRequest request = new RestSharp.RestRequest(method);

            var response = client.Execute(request);

            if (DebugConstant.DebugModeState)
            {
                GeminiApp.LogException(new Exception(string.Format("Content: {0} FileUrl: {1}", response.Content, url))
                {
                    Source = SourceControlProvider.Git.ToString()
                }, false);
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return(response);
            }

            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                GeminiApp.LogException(new ApplicationException(response.Content)
                {
                    Source = SourceControlProvider.Git.ToString()
                }, false);

                throw new ApplicationException(response.Content);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                GeminiApp.LogException(new UnauthorizedAccessException(response.Content)
                {
                    Source = SourceControlProvider.Git.ToString()
                }, false);

                throw new UnauthorizedAccessException(response.Content);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                GeminiApp.LogException(new FileNotFoundException(response.Content)
                {
                    Source = SourceControlProvider.Git.ToString()
                }, false);

                throw new FileNotFoundException(response.Content);
            }
            else
            {
                GeminiApp.LogException(new Exception(response.Content)
                {
                    Source = SourceControlProvider.Git.ToString()
                }, false);

                throw new Exception(response.Content);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Get all Workspaces and it filters by "Url = items" and "BadgeCount > 0"
        /// If there are Items in the workspace, it updates the BadgeCount.
        /// If there are no Items in the workspace, it resets the BadgeCount.
        /// </summary>
        /// <param name="issueManager"></param>
        public void GetWorkspaceItems(IssueManager issueManager)
        {
            try
            {
                NavigationCardsManager navigationCardsManager = new NavigationCardsManager(issueManager);
                List <NavigationCard>  workspaces             = navigationCardsManager.GetAll();
                foreach (NavigationCard workspace in workspaces.ToList())
                {
                    if (workspace.Url == "items" && workspace.BadgeCount > 0)
                    {
                        IssuesFilter    filter         = ChangeSystemFilterTypesMe(workspace.Filter, (int)workspace.UserId, false);
                        List <IssueDto> workspaceItems = issueManager.GetFiltered(filter, true);

                        if (workspaceItems.Count() > 0)
                        {
                            UpdateBadgeCount(workspace, workspaceItems, navigationCardsManager, false);
                        }
                        else
                        {
                            UpdateBadgeCount(workspace, workspaceItems, navigationCardsManager, true);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, string.Concat("Run Method GetWorkspaceItems: ", exception.Message));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This creates an auditlog for the custom field manipulations
        /// </summary>
        /// <param name="context"></param>
        /// <param name="issueId"></param>
        /// <param name="issueProjectId"></param>
        /// <param name="customField"></param>
        /// <param name="beforeValue"></param>
        /// <param name="afterValue"></param>
        public void CreateAuditlog(GeminiContext context, int issueId, int issueProjectId, CustomFieldDataDto customField, string beforeValue, string afterValue)
        {
            IssueAuditManager issueAuditManager = new IssueAuditManager(GeminiApp.Cache(), GeminiApp.UserContext(), context);
            IssueAudit        audit             = issueAuditManager.GetIssueAuditObject(issueId, issueProjectId);

            issueAuditManager.LogChange(audit, ItemAttributeVisibility.AssociatedCustomFields, customField.Entity.CustomFieldId.ToString(),
                                        string.Empty, string.Empty, beforeValue, afterValue);
        }
Ejemplo n.º 10
0
        public string GetFileContent(GeminiContext gemini, int issueid, string repositoryUrl, string filename, string revisionId, bool getPreviousRevision = false)
        {
            if (filename.IsEmpty())
            {
                return(string.Empty);
            }

            if (getPreviousRevision)
            {
                var allIssueCommits = gemini.CodeCommits.GetAll(issueid);

                if (allIssueCommits == null || allIssueCommits.Count() == 0)
                {
                    return(string.Empty);
                }

                var fileCommits = allIssueCommits.Where(f => f.Provider == SourceControlProvider.SVN && f.Data.Contains(repositoryUrl) && f.Data.Contains(filename) && f.Data.Contains(string.Concat("\"RevisionId\":", revisionId)));

                if (fileCommits == null || fileCommits.Count() != 1)
                {
                    return(string.Empty);
                }

                var fileCommitsJson = fileCommits.First().Data.FromJson <SourceControlCommit>();

                revisionId = fileCommitsJson.Files.Where(f => f.Filename == filename).First().PreviousFileRevisionId;

                if (revisionId.IsEmpty())
                {
                    return(string.Empty);
                }
            }

            RestSharp.IRestResponse response;

            try
            {
                response = GetResponse(string.Format("{0}{1}?p={2}", repositoryUrl, filename, revisionId), RestSharp.Method.GET);
            }
            catch (FileNotFoundException ex)
            {
                GeminiApp.LogException(ex, false);

                return(string.Empty);
            }
            catch (UnauthorizedAccessException)
            {
                throw;
            }
            catch (Exception ex)
            {
                GeminiApp.LogException(ex, false);

                return(string.Empty);
            }

            return(response.Content);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Checks the disabled users and executes the MergeAndDelete-Method
        /// </summary>
        /// <param name="issueManager"></param>
        public void CheckDisabledUsers(IssueManager issueManager)
        {
            UserManager userManager = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), issueManager.GeminiContext);
            var         allUsers    = userManager.GetAll();
            DateTime    currentDate = DateTime.Now;
            var         time        = GetAppConfigSettings("disabledForDays").Value;
            int         days        = Convert.ToInt32(time);

            foreach (var user in allUsers)
            {
                if (user.Entity.Active == false)
                {
                    var      activeUserIndex         = GetActiveUsersFromOrganisation(issueManager, user.Entity);
                    DateTime lastupdateIncludeMonths = user.Entity.Revised.AddDays(days);
                    int      disabledUserId          = user.Entity.Id;
                    if (activeUserIndex.Count != 0 && lastupdateIncludeMonths < DateTime.Now)
                    {
                        string firstActiveUserOrganisation = activeUserIndex[0];

                        foreach (var activeUser in allUsers)
                        {
                            if (activeUser.Entity.Username == firstActiveUserOrganisation)
                            {
                                try
                                {
                                    MergeAndDelete(activeUser.Entity, user.Entity, disabledUserId, userManager);
                                    break;
                                }
                                catch (Exception e)
                                {
                                    string message = string.Format("Folgender User konnte nicht gemerged oder gelöscht werden: {0} ", user.Entity.Fullname);
                                    GeminiApp.LogException(e, false, message);
                                }
                            }
                        }
                    }
                    else if (lastupdateIncludeMonths < DateTime.Now)
                    {
                        foreach (var activeUser in allUsers)
                        {
                            if (activeUser.Entity.Username == GetAppConfigSettings("defaultUser").Value)
                            {
                                try
                                {
                                    MergeAndDelete(activeUser.Entity, user.Entity, disabledUserId, userManager);
                                    break;
                                }
                                catch (Exception e)
                                {
                                    string message = string.Format("Folgender User konnte nicht gemerged oder gelöscht werden: {0} ", user.Entity.Fullname);
                                    GeminiApp.LogException(e, false, message);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public string GetFileContent(GeminiContext gemini, int issueid, string repositoryUrl, string revisionId, string filename, string fileId, bool getPreviousRevision = false)
        {
            if (filename.IsEmpty() || repositoryUrl.IsEmpty())
            {
                return(string.Empty);
            }

            var result = string.Empty;

            if (getPreviousRevision)
            {
                var allIssueCommits = gemini.CodeCommits.GetAll(issueid);

                if (allIssueCommits == null || allIssueCommits.Count() == 0)
                {
                    return(string.Empty);
                }

                var fileCommits = allIssueCommits.Where(f => f.Provider == SourceControlProvider.GitHub && f.Data.Contains(repositoryUrl) && f.Data.Contains(filename) && f.Data.Contains(string.Concat("\"RevisionId\":\"", revisionId, "\"")));

                if (fileCommits == null || fileCommits.Count() != 1)
                {
                    return(string.Empty);
                }

                var fileCommitsJson = fileCommits.First().Data.FromJson <SourceControlCommit>();

                fileId = fileCommitsJson.Files.Where(f => f.Filename == filename).First().PreviousFileRevisionId;
            }

            if (fileId.IsEmpty())
            {
                return(string.Empty);
            }

            RestSharp.IRestResponse response;

            repositoryUrl = repositoryUrl.Replace("https://api.github.com", "https://api.github.com/repos");

            try
            {
                response = GetResponse(string.Format("{0}/git/blobs/{1}", repositoryUrl, fileId), RestSharp.Method.GET);

                result = Encoding.Default.GetString(Convert.FromBase64String(response.Content.FromJson <GitHubFileContent>().content));
            }
            catch (Exception ex)
            {
                GeminiApp.LogException(ex, false);

                return(string.Empty);
            }

            return(result);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Before a task will be created, the description will be reformatted.
 /// </summary>
 /// <param name="args"></param>
 /// <returns></returns>
 public Issue BeforeCreate(IssueEventArgs args)
 {
     try
     {
         args.Entity.Description = FormatHtmlString(args.Entity.Description);
     }
     catch (Exception e)
     {
         int    issueID = args.Entity.Id;
         string message = string.Format("IssueID: {0}", issueID);
         GeminiApp.LogException(e, false, message);
     }
     return(args.Entity);
 }
Ejemplo n.º 14
0
 public override IssueDto BeforeUpdateFull(IssueDtoEventArgs args)
 {
     try
     {
         IssueDto issue = AddDomain(args, true);
         AddSuperuser(args.Context, issue, args.User, true);
         return(issue);
     }
     catch (Exception exception)
     {
         GeminiApp.LogException(exception, false, exception.Message);
         return(args.Issue);
     }
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Before a comment will be created, the comment will be reformatted.
 /// </summary>
 /// <param name="args"></param>
 /// <returns></returns>
 public IssueComment BeforeComment(IssueCommentEventArgs args)
 {
     try
     {
         args.Entity.Comment = FormatHtmlString(args.Entity.Comment);
     }
     catch (Exception e)
     {
         int    issueID = args.Entity.Id;
         string message = string.Format("Exception BeforeComment: {0}. IssueID: {1}", e.Message, issueID);
         GeminiApp.LogException(e, false, message);
     }
     return(args.Entity);
 }
Ejemplo n.º 16
0
        public string GetFormattedDataErstellerOE(IssueDto issue)
        {
            string formattedData = null;

            try
            {
                formattedData = issue.CustomFields.Find(field => field.Name.Equals(GetAppConfigValue("customFieldNameDomain"))).FormattedData;
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
            return(formattedData);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// The complete procedure to find, notify and unlock the locked user.
        /// </summary>
        /// <param name="issueManager"></param>
        /// <returns></returns>
        public override bool Run(IssueManager issueManager)
        {
            UserManager    userManager = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), issueManager.GeminiContext);
            List <UserDto> users       = userManager.GetActiveUsers();

            foreach (UserDto user in users)
            {
                if (user.Entity.Locked == true)
                {
                    DateTime currentTime = DateTime.Now;
                    SendMail(user.Entity, currentTime, GetUnlockTime(user.Entity), issueManager);
                    UnlockUser(issueManager, user.Entity, currentTime);
                }
            }
            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This method filters an email address with a regex pattern to get domain
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public string FindDomain(string email)
        {
            string domain = null;

            try
            {
                string pattern = "(?<=@)(.*)";
                Regex  regex   = new Regex(pattern);
                Match  match   = regex.Match(email);
                domain = match.Value;
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
            return(domain);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Search in "text" after ID with a Regex Pattern
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string FindID(string text)
        {
            string id = null;

            try
            {
                string pattern = GetAppConfigValue("regex");
                Regex  regex   = new Regex(pattern);
                Match  match   = regex.Match(text);
                id = match.Value;
            }
            catch (Exception e)
            {
                GeminiApp.LogException(e, false, e.Message);
            }
            return(id);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// This method filters an email address with a regex pattern to get its domain
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public string FindDomain(string email)
        {
            string domain = null;

            try
            {
                // RFC 5322 Official Standard
                string pattern = "(?<=@)(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)])";
                Regex  regex   = new Regex(pattern);
                Match  match   = regex.Match(email);
                domain = match.Value;
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
            return(domain);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Check if the "Fremd-ID"-field is ""
        /// Then it checks if the ID is in the description
        /// if there is no ID, then it checks in the comment section
        /// </summary>
        /// <param name="args">Properties of the task</param>
        /// <returns>args.Issue</returns>
        public IssueDto BeforeUpdateFull(IssueDtoEventArgs args)
        {
            try
            {
                List <IssueCommentDto> comments = args.Issue.Comments;
                string             description  = args.Issue.Description;
                string             fieldName    = GetAppConfigValue("customFieldName");
                CustomFieldDataDto fremdIDField = args.Issue.CustomFields.Find(field => field.Name.Equals(fieldName));

                if (fremdIDField.Entity.Data == "")
                {
                    if (FindID(description) != "")
                    {
                        string beforeValue        = fremdIDField.Entity.Data;
                        string valueIdDescription = FindID(description);
                        string fieldValue         = fremdIDField.Entity.Data = valueIdDescription;
                        CreateAuditlog(args.Context, args.Issue.Entity.Id, args.Issue.Entity.ProjectId, fremdIDField, beforeValue, fieldValue);
                    }
                    else
                    {
                        foreach (IssueCommentDto comment in comments)
                        {
                            string valueIdComment = FindID(comment.Entity.Comment);
                            if (valueIdComment != "")
                            {
                                string       fieldValue   = fremdIDField.Entity.Data = valueIdComment;
                                IssueManager issueManager = new IssueManager(GeminiApp.Cache(), GeminiApp.UserContext(), args.Context);
                                issueManager.Update(args.Issue);
                                CreateAuditlog(args.Context, args.Issue.Entity.Id, args.Issue.Entity.ProjectId, fremdIDField, "", fieldValue);
                                break;
                            }
                        }
                    }
                }
            }

            catch (Exception e)
            {
                int    issueID = args.Issue.Id;
                string message = string.Format("IssueID: {0}", issueID);
                GeminiApp.LogException(e, false, message);
            }
            return(args.Issue);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Get value from different AppConfig settings
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        public string GetAppConfigValue(string settings)
        {
            AppSettingsSection appSettings = null;

            try
            {
                ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
                string assemblyFolder    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string appConfigFileName = Path.Combine(assemblyFolder, "App.config");
                configFile.ExeConfigFilename = appConfigFileName;
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
                appSettings = (AppSettingsSection)config.GetSection("appSettings");
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
            return(appSettings.Settings[settings].Value);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Get active users from the same domain/organisation as the disabled user
        /// </summary>
        /// <param name="issueManager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public List <string> GetActiveUsersFromOrganisation(IssueManager issueManager, User user)
        {
            UserManager    userManager        = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), issueManager.GeminiContext);
            List <UserDto> activeUsers        = userManager.GetActiveUsers();
            string         DisabledUserDomain = FindDomain(user.Email);
            List <string>  activeUserList     = new List <string>();

            foreach (var activeUser in activeUsers)
            {
                string ActiveUserDomain = FindDomain(activeUser.Entity.Email);

                if (DisabledUserDomain == ActiveUserDomain)
                {
                    activeUserList.Add(activeUser.Entity.Username);
                }
            }
            activeUserList.Sort();
            return(activeUserList);
        }
Ejemplo n.º 24
0
        private ActionResult GetSummaryByVersion(ReportOptions options)
        {
            var reportManager = new ReportManager(GeminiApp.Cache(), UserContext, GeminiContext);

            var list = new List <ProjectDto>(options.ProjectIds.Count());

            list.AddRange(options.ProjectIds.Select(id => ProjectManager.Get(id)));
            var SummaryByVersion = reportManager.GetSummaryByVersion(list);

            foreach (var Summary in SummaryByVersion)
            {
                Summary.FilterName = "versions";
            }
            var resultModel = new ReportResultModel {
                UserContext = UserContext, Results = SummaryByVersion, Title = GetResource(ResourceKeys.Versions), Flag = options.SummaryChart.GetValueOrDefault(), ProjectIds = options.ProjectIds
            };                                                                                                                                                                                                                               //TODO add new key for this

            return(Json(JsonResponse(options, RenderPartialViewToString(this, AppManager.Instance.GetAppUrl(AppGuid, "views/_SummaryItem.cshtml"), resultModel))));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// This method updates the BadgeCount.
        /// In the first foreach, every items that should not be deleted, will be in the list "elementsNotToDelete".
        /// The second foreach, compares the elements in BadgeCount with the list "elementsNotToDelete"
        /// and filters the items that should be deleted in the "elementsToDelete".
        /// In the last foreach, the items in the BadgeCount, that exist in "elementsToDelete", will be deleted.
        /// </summary>
        /// <param name="workspace"></param>
        /// <param name="workspaceItems"></param>
        /// <param name="navigationCardsManager"></param>
        /// <param name="reset"></param>
        public void UpdateBadgeCount(NavigationCard workspace, List <IssueDto> workspaceItems, NavigationCardsManager navigationCardsManager, bool reset)
        {
            try
            {
                bool change = false;

                workspace = navigationCardsManager.Get(workspace.Id);
                if (reset)
                {
                    change = true;
                    workspace.CardData.Badges.RemoveAll(item => item > 0);
                    LogDebugMessage("Reset Badge Count in Workspace: " + workspace.Id + " " + workspace.Title);
                }
                else
                {
                    foreach (int badge in workspace.CardData.Badges.ToList())
                    {
                        if (!workspaceItems.Exists(item => item.Entity.Id == badge))
                        {
                            change = true;
                            workspace.CardData.Badges.RemoveAll(id => id == badge);
                            LogDebugMessage(string.Concat("Update Badge Count in Workspace: ", workspace.Key, " (", workspace.Id, ") ", workspace.Title, " >> Issue: ", badge));
                        }
                    }
                }


                if (change)
                {
                    //it's possible workspace change at time of runing timerapp get new data and don't overwrite user changes.
                    List <int> newBadges = workspace.CardData.Badges;
                    workspace.Filter          = ChangeSystemFilterTypesMe(workspace.Filter, (int)workspace.UserId, true);
                    workspace                 = navigationCardsManager.Get(workspace.Id);
                    workspace.CardData.Badges = newBadges;
                    navigationCardsManager.Update(workspace, true, false);
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, string.Concat("Run Method UpdateBadgeCount: ", exception.Message));
            }
        }
Ejemplo n.º 26
0
 public static void InitiateSSLTrust()
 {
     try
     {
         if (!_sslInitialised)
         {
             _sslInitialised = true;
             //Change SSL checks so that all checks pass
             ServicePointManager.ServerCertificateValidationCallback =
                 new RemoteCertificateValidationCallback(
                     delegate
                     { return(true); }
                     );
         }
     }
     catch (Exception ex)
     {
         GeminiApp.LogException(ex, false);
     }
 }
Ejemplo n.º 27
0
        private void ProcessWatcherAlerts()
        {
            IConfiguration    configuration = GeminiApp.Container.Resolve <IConfiguration>();
            var               inputConfig   = configuration.Get();
            SchedulerSettings settings      = inputConfig.SchedulerSettings.HasValue() ? inputConfig.SchedulerSettings.FromJson <SchedulerSettings>() : new SchedulerSettings();

            DateTime lastChecked = settings.LastCheckedWatchers.HasValue ? settings.LastCheckedWatchers.Value : DateTime.UtcNow;

            IssuesFilter filter = new IssuesFilter();

            filter.RevisedAfter = lastChecked.ToString();

            filter.IncludeClosed = true;

            LogDebugMessage("Last checked for watched item alerts: " + lastChecked);

            settings.LastCheckedWatchers = DateTime.UtcNow;

            List <IssueDto> issues = _issueManager.GetFiltered(filter);

            LogDebugMessage("Item that have changed: " + issues.Count);

            if (issues.Count > 0)
            {
                ProcessWatchers(issues, lastChecked);
            }

            GeminiConfiguration config = configuration.Get();

            config.SchedulerSettings = settings.ToJson();

            ConfigurationItem item = new ConfigurationItem();

            item.SettingId = GeminiConfigurationOption.SchedulerSettings.ToString();

            item.SettingValue = config.SchedulerSettings;

            configuration.Update(item);

            GeminiApp.RefreshConfig(config);
        }
Ejemplo n.º 28
0
        public void AfterUserCreated(UserEventArgs args)
        {
            if (!GeminiApp.Config.EmailAlertsEnabled)
            {
                return;
            }

            if (!GeminiApp.Config.GeminiAdmins.StartsWith(args.User.Email, StringComparison.InvariantCultureIgnoreCase))
            {
                string log;

                if (!EmailHelper.Send(GeminiApp.Config, string.Concat("New user created - ", args.Entity.Username),
                                      string.Format("Just to let you know that a new user has been created\nUsername: {0}\n Name: {1}\n", args.Entity.Username, args.Entity.Fullname),
                                      GeminiApp.Config.GeminiAdmins, string.Empty, false, out log))
                {
                    GeminiApp.LogException(new Exception(log)
                    {
                        Source = "Email on user creation plugin"
                    }, false);
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// This method unlocks the user
        /// It sets the user.entity.locked status to false, when the next run time is greater than the unlock time.
        /// </summary>
        /// <param name="issueManager"></param>
        /// <param name="entity"></param>
        public void UnlockUser(IssueManager issueManager, User entity, DateTime currentTime)
        {
            try
            {
                IGlobalConfigurationWidgetStore dataStore = issueManager.GeminiContext.GlobalConfigurationWidgetStore;
                int      intervalMinutes = Convert.ToInt32(GetInterval(dataStore).IntervalInMinutes);
                DateTime timeToUnlock    = GetUnlockTime(entity);
                DateTime nextRunTime     = currentTime + new TimeSpan(0, intervalMinutes, 0);

                if (timeToUnlock < nextRunTime)
                {
                    UserManager userManager = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), issueManager.GeminiContext);
                    entity.Locked = false;
                    userManager.Update(entity);
                    LogDebugMessage("Benutzer: " + entity.Fullname + " entsperrt.");
                }
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
            }
        }
Ejemplo n.º 30
0
        public ActionResult GetFileDiff(int issueId)
        {
            string newFile = string.Empty;

            string oldFile = string.Empty;

            string fileName = Request["filename"] ?? string.Empty;

            string fullfilename = Request["fullfilename"] ?? string.Empty;

            string provider = Request["provider"] ?? string.Empty;

            string revisionid = Request["revisionid"] ?? string.Empty;

            string fileid = Request["fileid"] ?? string.Empty;

            string repositoryUrl = Request["repositoryurl"] ?? string.Empty;

            string workspace = Request["workspace"] ?? string.Empty;

            fileName = fileName.Trim();

            fullfilename = fullfilename.Trim();

            provider = provider.Trim();

            revisionid = revisionid.Trim();

            fileid = fileid.Trim();

            repositoryUrl = repositoryUrl.Trim();

            workspace = workspace.Trim();

            //Authentication details
            string authenticateForm = string.Empty;

            bool IsUserAuthorized = false;

            bool isFileIdMissing = false;

            string data = string.Empty;

            string errorMessage = string.Empty;

            if (!repositoryUrl.IsEmpty())
            {
                if (provider == SourceControlProvider.GitHub.ToString())
                {
                    GitHub github = new GitHub();

                    if (github.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            if (fileid.IsEmpty())
                            {
                                isFileIdMissing = true;
                                // Need to do this, because when github sends back the committed data there is no fileid(which we need to get the file content) for the files.
                                // This will go and get the fileids once for each commit where fileid's are empty
                                fileid = github.updateFileIds(GeminiContext, repositoryUrl, revisionid, fileName, issueId);
                            }

                            newFile = github.GetFileContent(GeminiContext, issueId, repositoryUrl, revisionid, fileName, fileid);

                            oldFile = github.GetFileContent(GeminiContext, issueId, repositoryUrl, revisionid, fileName, fileid, true);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = github.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                    }
                    else
                    {
                        authenticateForm = github.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                        errorMessage = "Invalid login details";
                    }
                }
                else if (provider == SourceControlProvider.TFS2012.ToString())
                {
                    TFS2012 tfs2012 = new TFS2012();

                    if (tfs2012.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            oldFile = tfs2012.GetFileContent(GeminiContext, issueId, fileName, fullfilename, workspace, revisionid, fileid, repositoryUrl, true);

                            newFile = tfs2012.GetFileContent(GeminiContext, issueId, fileName, fullfilename, workspace, revisionid, fileid, repositoryUrl);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = tfs2012.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                        catch (TeamFoundationServerUnauthorizedException ex)
                        {
                            authenticateForm = tfs2012.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = ex.Message;
                        }
                    }
                    else
                    {
                        authenticateForm = tfs2012.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);
                    }
                }
                else if (provider == SourceControlProvider.TFS2010.ToString())
                {
                    TFS2010 tfs2010 = new TFS2010();

                    if (tfs2010.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            oldFile = tfs2010.GetFileContent(GeminiContext, issueId, fileName, fullfilename, workspace, revisionid, fileid, repositoryUrl, true);

                            newFile = tfs2010.GetFileContent(GeminiContext, issueId, fileName, fullfilename, workspace, revisionid, fileid, repositoryUrl);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = tfs2010.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                        catch (TeamFoundationServerUnauthorizedException ex)
                        {
                            authenticateForm = tfs2010.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = ex.Message;
                        }
                    }
                    else
                    {
                        authenticateForm = tfs2010.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);
                    }
                }
                else if (provider == SourceControlProvider.SVN.ToString())
                {
                    SVN svn = new SVN();

                    if (svn.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            oldFile = svn.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid, true);

                            newFile = svn.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = svn.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                    }
                    else
                    {
                        authenticateForm = svn.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                        errorMessage = "Invalid login details";
                    }
                }
                else if (provider == SourceControlProvider.Git.ToString())
                {
                    Git git = new Git();

                    if (git.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            oldFile = git.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid, true);

                            newFile = git.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = git.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                    }
                    else
                    {
                        authenticateForm = git.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                        errorMessage = "Invalid login details";
                    }
                }
                else if (provider == SourceControlProvider.Bitbucket.ToString())
                {
                    Bitbucket bitbucket = new Bitbucket();

                    if (bitbucket.AuthenticateUser(CurrentUser, repositoryUrl, GeminiContext))
                    {
                        try
                        {
                            oldFile = bitbucket.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid, true);

                            newFile = bitbucket.GetFileContent(GeminiContext, issueId, repositoryUrl, fileName, revisionid);

                            IsUserAuthorized = true;
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            authenticateForm = bitbucket.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                            errorMessage = "Invalid login details";
                        }
                    }
                    else
                    {
                        authenticateForm = bitbucket.CreateAuthenticationForm(UserContext.Url, repositoryUrl, fileName);

                        errorMessage = "Invalid login details";
                    }
                }
            }
            else
            {
                errorMessage = "ERROR: Repository Url is missing";
            }

            if (IsUserAuthorized)
            {
                // Handle BOM markers
                oldFile = oldFile.Replace("\x00EF\x00BB\x00BF", "");

                newFile = newFile.Replace("\x00EF\x00BB\x00BF", "");

                // Diff
                var tmpModel = diffBuilder.BuildDiffModel(oldFile ?? string.Empty, newFile ?? string.Empty);

                IssueWidgetData <List <Comment> > tmpData = GeminiContext.IssueWidgetStore.Get <List <Comment> >(issueId, Constants.AppId, Constants.ControlId);

                DiffplexComments model = new DiffplexComments();

                if (tmpData != null)
                {
                    SourceControlProvider enumProvider;

                    try
                    {
                        enumProvider = (SourceControlProvider)Enum.Parse(typeof(SourceControlProvider), provider, true);
                    }
                    catch (ArgumentException ex)
                    {
                        enumProvider = 0;

                        GeminiApp.LogException(new Exception(ex.Message)
                        {
                            Source = "Saucery"
                        }, false);
                    }

                    var comments = tmpData.Value.FindAll(f => f.FileName == fileName && f.RepositoryUrl == repositoryUrl && f.Provider == enumProvider && f.ChangesetId == revisionid);

                    if (comments != null)
                    {
                        model.data = tmpModel;

                        model.comments = comments;
                    }
                }
                else
                {
                    model.data = tmpModel;

                    model.comments = new List <Comment>();
                }

                data = RenderPartialViewToString(this, AppManager.Instance.GetAppUrl("F473D13E-19B7-45F3-98ED-6ED77B6BAB0A", "views/diff.cshtml"), model);
            }
            else
            {
                data = authenticateForm;
            }

            return(JsonSuccess(new { authenticationSuccess = IsUserAuthorized, fileid = fileid, data = data, isFileIdMissing = isFileIdMissing, errorMessage = errorMessage }));
        }