Ejemplo n.º 1
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.º 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
        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.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
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.º 23
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.º 24
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.Bitbucket.ToString()
                }, false);
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                if (response.ContentLength == -1 && response.ResponseUri.AbsoluteUri.Contains("bitbucket.org/account/signin", StringComparison.InvariantCultureIgnoreCase))
                {
                    GeminiApp.LogException(new UnauthorizedAccessException(response.Content)
                    {
                        Source = SourceControlProvider.Bitbucket.ToString()
                    }, false);

                    throw new UnauthorizedAccessException(response.Content);
                }
                else
                {
                    return(response);
                }
            }

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

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

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

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

                throw new Exception(response.Content);
            }
        }
Ejemplo n.º 25
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 }));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Add the domain to the custom field, and create an auditlog if it hasn't just been created.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="createAudit"></param>
        /// <returns></returns>
        private IssueDto AddDomain(IssueDtoEventArgs args, bool createAudit)
        {
            try
            {
                IssueDto issue  = args.Issue;
                Helper   helper = new Helper();
                if ((issue.CustomFields.Count > 0) && (!issue.CustomFields.Find(field => field.Name.Equals(helper.GetAppConfigValue("customFieldNameDomain"))).ToString().Equals(null)))
                {
                    CustomFieldDataDto erstellerOEField = issue.CustomFields.Find(field => field.Name.Equals(helper.GetAppConfigValue("customFieldNameDomain")));

                    // If there is no domain in the OE-Field yet
                    // Depending on whether you want users to manually change the OE-Field or not, .FormattedData or .Entity.Data could be chosen.
                    if (string.IsNullOrEmpty(erstellerOEField.Entity.Data))
                    {
                        string maildomain = helper.FindDomain(issue.OriginatorData);

                        // If no email address in OriginatorData present, take email address from creator user
                        if (string.IsNullOrEmpty(maildomain))
                        {
                            UserManager userManager = new UserManager(GeminiApp.Cache(), GeminiApp.UserContext(), args.Context);
                            int         userId;

                            // If created via another user
                            if (issue.Entity.ReportedBy > 0)
                            {
                                userId = issue.Entity.ReportedBy;
                            }
                            // If not
                            else
                            {
                                userId = args.User.Id;
                            }
                            UserDto creatorUser = userManager.Get(userId);
                            maildomain = helper.FindDomain(creatorUser.Entity.Email);
                        }
                        // OriginatorData has email address, no more actions required

                        string beforeValue = erstellerOEField.FormattedData;
                        erstellerOEField.Entity.Data   = maildomain;
                        erstellerOEField.FormattedData = maildomain;
                        // Keep in mind that args.Issue / issue / erstellerOEField are reference types, not value types

                        // Create auditlog if being called from BeforeUpdateFull with the auditlog flag
                        if (createAudit)
                        {
                            // beforeValue -> previous value (args.Issue FormattedData -> previous value)
                            // issue FormattedData -> new value (alternatively erstellerOEField.FormattedData)
                            if (!beforeValue.Equals(helper.GetFormattedDataErstellerOE(issue)))
                            {
                                IssueManager issueManager = new IssueManager(GeminiApp.Cache(), GeminiApp.UserContext(), args.Context);
                                helper.CreateAuditlog(args.Context, args.Issue.Entity.Id, args.Issue.Entity.ProjectId, erstellerOEField, beforeValue, erstellerOEField.FormattedData, args.User.Id, args.User.Fullname);
                            }
                        }
                    }
                    return(issue);
                }
                return(args.Issue);
            }
            catch (Exception exception)
            {
                GeminiApp.LogException(exception, false, exception.Message);
                return(args.Issue);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// This method sends the E-mail with the appropriate user language.
        /// First is to get the locked timestamp and the last run time from the app.
        /// To send an email the locked timestamp has to be greater than the last run time app.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="language"></param>
        public void SendMail(User entity, DateTime currentTime, DateTime unlockTime, IssueManager issueManager)
        {
            string log;
            IGlobalConfigurationWidgetStore dataStore = issueManager.GeminiContext.GlobalConfigurationWidgetStore;
            int intervalMinutes = Convert.ToInt32(GetInterval(dataStore).IntervalInMinutes);

            string   language        = entity.Language;
            DateTime lockedTimeStamp = entity.Revised.ToLocalTime();
            DateTime lastRunTime     = currentTime - new TimeSpan(0, intervalMinutes, 0);

            if (lockedTimeStamp > lastRunTime)
            {
                LogDebugMessage("Benutzer: " + entity.Fullname + " gesperrt.");
                string timeToUnlock = unlockTime.ToString(@"HH\:mm");
                KeyValueConfigurationElement mailbodyLanguageSettings    = GetAppConfigSettings(string.Concat("mailbody_", language));
                KeyValueConfigurationElement mailSubjectLanguageSettings = GetAppConfigSettings(string.Concat("mailSubject_", language));

                if (mailbodyLanguageSettings == null || mailSubjectLanguageSettings == null)
                {
                    UserManager    usermanager = new UserManager(issueManager);
                    List <UserDto> users       = usermanager.GetActiveUsers();
                    foreach (UserDto user in users)
                    {
                        if (user.IsGlobalAdmin)
                        {
                            if (!EmailHelper.Send(GeminiApp.Config, "Unlock User App: failure in App.config file", string.Concat(@"<style>
div.container {
background-color: #ffffff;
}
div.container p {
font-family: Arial;
font-size: 14px;
font-style: normal;
font-weight: normal;
text-decoration: none;
text-transform: none;
color: #000000;
background-color: #ffffff;
}
</style>

<div class='container'>
<p>Please create a key for mailbody_ and mailSubject_ in app.config file for user language >>", language, @"</p><p></p><p>Also Unlock user: ", entity.Username, "</p></div>"), user.Entity.Email, string.Empty, true, out log))
                            {
                                GeminiApp.LogException(new Exception(log)
                                {
                                    Source = "Notification"
                                }, false);
                            }
                            LogDebugMessage("E-Mail Benachrichtigung an " + entity.Fullname + " versendet.");
                        }
                    }
                }
                else
                {
                    string mailBody = string.Format(mailbodyLanguageSettings.Value, GetAppConfigSettings("unlockTime").Value, "(" + timeToUnlock + ")");

                    if (!EmailHelper.Send(GeminiApp.Config, string.Concat(mailSubjectLanguageSettings.Value),
                                          mailBody,
                                          entity.Email, string.Empty, true, out log))
                    {
                        GeminiApp.LogException(new Exception(log)
                        {
                            Source = "Notification"
                        }, false);
                    }
                    LogDebugMessage("E-Mail Benachrichtigung an " + entity.Fullname + " versendet.");
                }
            }
        }
Ejemplo n.º 28
0
        public string Commit(CommitObject commits, [FromUri] string token)
        {
            string apikey = string.Empty;
            string result = string.Empty;

            CurrentUser = new UserDto(new User()
            {
                ProjectGroups = new List <ProjectGroupMembership>()
                {
                    new ProjectGroupMembership()
                    {
                        ProjectGroupId = Countersoft.Gemini.Commons.Constants.GlobalGroupAdministrators, UserId = 0
                    }
                }
            });
            UserContext.User               = CurrentUser;
            PermissionsManager             = PermissionsManager.Copy(CurrentUser);
            UserContext.PermissionsManager = PermissionsManager;

            if (Request.Headers.Authorization != null && Request.Headers.Authorization.Parameter != null)
            {
                var authDetails = Encoding.Default.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
                if (authDetails.Length == 2)
                {
                    apikey = authDetails[0];
                }
            }
            else if (token != null)
            {
                apikey = token;
            }

            if (apikey.Length == 0 || GeminiApp.Config.ApiKey.Length == 0 || !apikey.StartsWith(GeminiApp.Config.ApiKey, StringComparison.InvariantCultureIgnoreCase))
            {
                string error;

                if (GeminiApp.Config.ApiKey.Length == 0)
                {
                    error = "Web.config is missing API key";
                }
                else
                {
                    error = "Wrong API key: " + apikey;
                }

                GeminiApp.LogException(new Exception(error)
                {
                    Source = SourceControlProvider.GitHub.ToString()
                }, false);

                return(error);
            }

            if (commits == null)
            {
                try
                {
                    var body = Request.Content.ReadAsStringAsync();
                    body.Wait();
                    GeminiApp.LogException("Null CodeCommit", string.Concat("Null CodeCommit - ", body.Result), false);
                }
                catch
                {
                    try
                    {
                        GeminiApp.LogException("Null CodeCommit", "Null CodeCommit - Empty!", false);
                    }
                    catch
                    {
                    }
                }
                return(string.Empty);
            }

            foreach (var commit in commits.commits)
            {
                Regex           ex      = new Regex("GEM:(?<issueid>[0-9]+)", RegexOptions.IgnoreCase);
                MatchCollection matches = ex.Matches(commit.message);

                if (matches.Count > 0)
                {
                    var baseUrl = commits.repository.url.ReplaceIgnoreCase("https://github.com/", "https://api.github.com/");

                    List <string> filesModified = new List <string>();

                    var commitIndex = commit.url.IndexOf("commit");
                    if (commitIndex != -1)
                    {
                        var url = string.Concat(commit.url.Remove(commitIndex, commit.url.Length - commitIndex), "blob/master/");

                        for (int i = 0; i < commit.added.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.added[i], "\", \"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\" }"));
                        }

                        for (int i = 0; i < commit.modified.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.modified[i], "\",\"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\"}"));
                        }

                        for (int i = 0; i < commit.removed.Length; i++)
                        {
                            filesModified.Add(string.Concat("{\"Filename\":\"", commit.removed[i], "\",\"FileId\":\"", string.Empty, "\",\"PreviousFileRevisionId\":\"", string.Empty, "\"}"));
                        }
                    }

                    CodeCommit codeCommit = new CodeCommit();
                    codeCommit.Provider = SourceControlProvider.GitHub;
                    codeCommit.Comment  = commit.message;
                    codeCommit.Fullname = commit.author.name;
                    codeCommit.Data     = string.Concat("{\"RevisionId\":\"", commit.id, "\",\"PreviousRevisionId\":\"", string.Empty, "\",\"Files\":[", string.Join(",", filesModified.ToArray()), "],\"RepositoryName\":\"", commits.repository.name, "\",\"RepositoryUrl\":\"", baseUrl, "\",\"IsPrivate\":\"", commits.repository.PRIVATE, "\"}");

                    commit.message = ex.Replace(commit.message, string.Empty);

                    List <int> issuesAlreadyProcessed = new List <int>();

                    foreach (Match match in matches)
                    {
                        var issue = IssueManager.Get(match.ToString().Remove(0, 4).ToInt());

                        if (issue != null && !issuesAlreadyProcessed.Contains(issue.Id))
                        {
                            codeCommit.IssueId = issue.Id;
                            GeminiContext.CodeCommits.Create(codeCommit);
                            issuesAlreadyProcessed.Add(issue.Id);

                            try
                            {
                                if (match.Index + match.Length + 1 + 5 <= codeCommit.Comment.Length)
                                {
                                    var time   = codeCommit.Comment.Substring(match.Index + match.Length + 1, 5);
                                    var timeEx = new System.Text.RegularExpressions.Regex("[0-9][0-9]:[0-9][0-9]");
                                    var m      = timeEx.Match(time);
                                    if (m.Success)
                                    {
                                        // Okay, log time!
                                        var timeTypes = MetaManager.TimeTypeGetAll(issue.Project.TemplateId);
                                        if (timeTypes.Count > 0)
                                        {
                                            // Let's try and find the user
                                            var user = commit.author.email.HasValue() ? Cache.Users.Find(u => u.Username.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                         u.Email.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                         u.Fullname.Equals(commit.author.email, StringComparison.InvariantCultureIgnoreCase)) : null;

                                            if (user == null)
                                            {
                                                user = commit.author.name.HasValue() ? Cache.Users.Find(u => u.Username.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                        u.Email.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                        u.Fullname.Equals(commit.author.name, StringComparison.InvariantCultureIgnoreCase)) : null;
                                            }
                                            var timeEntry = new IssueTimeTracking();
                                            timeEntry.IssueId    = issue.Id;
                                            timeEntry.ProjectId  = issue.Entity.ProjectId;
                                            timeEntry.Comment    = codeCommit.Comment.ToMax(1990);
                                            timeEntry.EntryDate  = DateTime.Now;
                                            timeEntry.Hours      = m.Value.Substring(0, 2).ToInt();
                                            timeEntry.Minutes    = m.Value.Substring(3, 2).ToInt();
                                            timeEntry.TimeTypeId = timeTypes[0].Entity.Id;
                                            timeEntry.UserId     = user == null ? Countersoft.Gemini.Commons.Constants.SystemAccountUserId : user.Id;
                                            TimeTrackingManager.Create(timeEntry);
                                        }
                                    }
                                }
                            }
                            catch (Exception timeEx)
                            {
                                LogManager.LogError(timeEx, "GitHub - Time log");
                            }
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 29
0
        public string GetFileContent(GeminiContext gemini, int issueid, string filename, string fullfilename, string workspace, string changesetid, string fileid, string repositoryUrl, bool getPreviousRevision = false)
        {
            ConnectByImplementingCredentialsProvider connect = new ConnectByImplementingCredentialsProvider();

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, workspace);

            connect.GetCredentials(new Uri(Uri), iCred);

            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(Uri));

            configurationServer.Credentials = iCred;


            if (TFS2012.IsBasicAuth)
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
            }
            else
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
            }

            configurationServer.EnsureAuthenticated();

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);

                TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);

                if (TFS2012.IsBasicAuth)
                {
                    tpc.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                }

                VersionControlServer versionControl = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));

                Item file = null;

                try
                {
                    //IF file was just added in tfs
                    if (fileid.ToInt() == 0)
                    {
                        Item tmpFile = null;
                        //Need to catch error if file was deleted, we'll get an error and call the file with parameters as below.
                        //This would only happen to newly added file, which will not have a itemid as we wouldn't know what it is on first commit of a file
                        try
                        {
                            tmpFile = versionControl.GetItem(string.Concat(fullfilename, "/", filename));
                        }
                        catch (VersionControlException ex)
                        {
                            tmpFile = versionControl.GetItem(fullfilename + "/" + filename, VersionSpec.Latest, DeletedState.Deleted);
                        }

                        if (tmpFile != null)
                        {
                            fileid = tmpFile.ItemId.ToString();
                        }
                    }

                    if (fileid.ToInt() > 0)
                    {
                        if (getPreviousRevision)
                        {
                            if (changesetid.ToInt() > 1)
                            {
                                file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt() - 1, true);
                            }
                        }
                        else
                        {
                            file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt());
                        }

                        if (file != null)
                        {
                            if (file.DeletionId > 0)
                            {
                                return(string.Empty);
                            }
                            else
                            {
                                using (Stream stream = file.DownloadFile())
                                {
                                    StreamReader rdr = new StreamReader(stream);

                                    return(rdr.ReadToEnd());
                                }
                            }
                        }
                    }
                }
                catch (VersionControlException ex)
                {
                    GeminiApp.LogException(ex, false);

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

                    return(string.Empty);
                }
            }

            return(string.Empty);
        }
Ejemplo n.º 30
0
        public string GetFileContent(GeminiContext gemini, int issueid, string repositoryUrl, string filename, string revisionId, bool getPreviousRevision = false)
        {
            if (filename.IsEmpty())
            {
                return(string.Empty);
            }


            var allIssueCommits = gemini.CodeCommits.GetAll(issueid);

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

            var fileCommits = allIssueCommits.Where(f => f.Provider == SourceControlProvider.Git && 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>();

            var currentFile = fileCommitsJson.Files.Where(s => s.FullFilename == filename);



            if (getPreviousRevision)
            {
                if (currentFile.Count() > 0 && currentFile.First().PreviousFileRevisionId.Equals("deleted", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(string.Empty);
                }

                revisionId = fileCommitsJson.PreviousRevisionId;
            }
            else if (currentFile.Count() > 0 && currentFile.First().FileId.IsEmpty())
            {
                //If fileId is empty means the file was deleted
                return(string.Empty);
            }

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


            RestSharp.IRestResponse response;

            try
            {
                response = GetResponse(string.Format("{0}/Raw/{1}/{2}?display=True", repositoryUrl, revisionId, Uri.EscapeDataString(filename)), 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);
        }