protected override IEnumerable<Notifications.INotification> CreateNotifications(IVssRequestContext requestContext, object notificationEventArgs, int maxLines)
        {
            var repositoryService = requestContext.GetService<ITeamFoundationGitRepositoryService>();
            var identityService = requestContext.GetService<ITeamFoundationIdentityService>();
            var commonService = requestContext.GetService<CommonStructureService>();
            var locationService = requestContext.GetService<ILocationService>();

            string baseUrl = String.Format("{0}/{1}/",
                        locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                        requestContext.ServiceHost.Name);

            var gitNotification = notificationEventArgs as GitNotification;

            Notifications.RepositoryNotification notification = null;

            if (gitNotification is RepositoryCreatedNotification)
            {
                var ev = notificationEventArgs as RepositoryCreatedNotification;
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, ev.Creator.Identifier);

                notification = new Notifications.RepositoryCreatedNotification();
                notification.UniqueName = identity.UniqueName;
                notification.DisplayName = identity.DisplayName;
                notification.TeamNames = GetUserTeamsByProjectUri(requestContext, gitNotification.TeamProjectUri, identity.Descriptor);
                using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, gitNotification.RepositoryId))
                {
                    notification.RepoUri = repository.GetRepositoryUri();
                    notification.RepoName = repository.Name;
                }
            }
            else if (gitNotification is RepositoryRenamedNotification)
            {
                notification = new Notifications.RepositoryRenamedNotification();
                notification.RepoName = gitNotification.RepositoryName;
                using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, gitNotification.RepositoryId))
                {
                    notification.RepoUri = repository.GetRepositoryUri();
                    notification.RepoName = repository.Name;
                }
                notification.TeamNames = Enumerable.Empty<string>();
            }
            else if (gitNotification is RepositoryDeletedNotification)
            {
                var repoInfo = repositoryService
                    .QueryDeletedRepositories(requestContext, gitNotification.TeamProjectUri)
                    .Single(r => r.RepositoryId == gitNotification.RepositoryId);
                var identity = identityService.ReadIdentities(requestContext, new[] { repoInfo.DeletedBy }).First();
                notification = new Notifications.RepositoryDeletedNotification();
                notification.UniqueName = identity.UniqueName;
                notification.DisplayName = identity.DisplayName;
                notification.TeamNames = GetUserTeamsByProjectUri(requestContext, gitNotification.TeamProjectUri, identity.Descriptor);
                notification.RepoName = repoInfo.Name;
            }

            notification.TeamProjectCollection = requestContext.ServiceHost.Name;
            notification.ProjectName = commonService.GetProject(requestContext, gitNotification.TeamProjectUri).Name;
            notification.ProjectUrl = baseUrl + notification.ProjectName;

            yield return notification;
        }
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, ReleaseCreatedServerEvent ev, int maxLines)
        {
            var projectService  = requestContext.GetService <IProjectService>();
            var identityService = requestContext.GetService <ITeamFoundationIdentityService>();

            var release = ev.Release;
            var creator = identityService.ReadIdentities(requestContext, new[] { release.CreatedBy }).First();

            string projectName = projectService.GetProjectName(requestContext, ev.ProjectId);
            var    releaseUrl  = WebAccessUrlBuilder.GetReleaseWebAccessUri(requestContext, projectName, release.Id);

            var notification = new ReleaseCreatedNotification
            {
                TeamProjectCollection = requestContext.ServiceHost.Name,
                ProjectName           = projectName,
                ReleaseDefinition     = release.ReleaseDefinitionName,
                ReleaseName           = release.Name,
                ReleaseReason         = release.Reason,
                ReleaseStatus         = release.Status,
                ReleaseUrl            = releaseUrl,
                CreatedOn             = release.CreatedOn,
                CreatedByUniqueName   = creator.UniqueName,
                CreatedByDisplayName  = creator.DisplayName,
                TeamNames             = GetUserTeamsByProjectName(requestContext, projectName, creator.Descriptor)
            };

            yield return(notification);
        }
示例#3
0
        private static CommitRow CreateCommitRow(IVssRequestContext requestContext, ITeamFoundationGitCommitService commitService,
                                                 ITfsGitRepository repository, TfsGitCommit gitCommit, CommitRowType rowType, PushNotification pushNotification, Dictionary <Sha1Id, List <GitRef> > refLookup)
        {
            var    commitManifest = commitService.GetCommitManifest(requestContext, repository, gitCommit.ObjectId);
            string repoUri        = repository.GetRepositoryUri();

            var commitRow = new CommitRow()
            {
                CommitId     = gitCommit.ObjectId,
                Type         = rowType,
                CommitUri    = repoUri + "/commit/" + gitCommit.ObjectId.ToHexString(),
                AuthorTime   = gitCommit.GetAuthor().LocalTime,
                Author       = gitCommit.GetAuthor().NameAndEmail,
                AuthorName   = gitCommit.GetAuthor().Name,
                AuthorEmail  = gitCommit.GetAuthor().Email,
                Comment      = gitCommit.GetComment(),
                ChangeCounts = commitManifest.ChangeCounts
            };
            List <GitRef> refs;

            refLookup.TryGetValue(gitCommit.ObjectId, out refs);
            commitRow.Refs = refs;

            return(commitRow);
        }
        public override async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var token = bot.GetSetting("token");

            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Missing token!");
            }

            var tasks       = new List <Task>();
            var slackClient = new SlackClient();

            foreach (string tfsUserName in notification.TargetUserNames)
            {
                var userId = bot.GetMappedUser(tfsUserName);

                if (userId != null)
                {
                    Message slackMessage = ToSlackMessage((dynamic)notification, bot, null, true);
                    if (slackMessage != null)
                    {
                        slackMessage.AsUser = true;
                        var t = Task.Run(async() =>
                        {
                            var response = await slackClient.SendApiMessageAsync(slackMessage, token, userId);
                            response.EnsureSuccessStatusCode();
                            var content = await response.Content.ReadAsStringAsync();
                        });
                        tasks.Add(t);
                    }
                }
            }

            await Task.WhenAll(tasks);
        }
示例#5
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, BuildCompletionNotificationEvent buildNotification, int maxLines)
        {
            BuildDetail build           = buildNotification.Build;
            var         locationService = requestContext.GetService <ILocationService>();
            var         buildService    = requestContext.GetService <TeamFoundationBuildService>();

            using (var buildReader = buildService.QueryQueuedBuildsById(requestContext, build.QueueIds, new[] { "*" }, QueryOptions.None))
            {
                var         result   = buildReader.Current <BuildQueueQueryResult>();
                QueuedBuild qb       = result.QueuedBuilds.FirstOrDefault();
                string      buildUrl = string.Format("{0}/{1}/{2}/_build#_a=summary&buildId={3}",
                                                     locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                                                     requestContext.ServiceHost.Name, build.TeamProject, qb.BuildId);

                var notification = new BuildCompletionNotification()
                {
                    TeamProjectCollection = requestContext.ServiceHost.Name,
                    BuildUrl                = buildUrl,
                    ProjectName             = build.TeamProject,
                    BuildNumber             = build.BuildNumber,
                    BuildStatus             = build.Status,
                    BuildReason             = build.Reason,
                    StartTime               = build.StartTime,
                    FinishTime              = build.FinishTime,
                    RequestedForUniqueName  = qb.RequestedFor,
                    RequestedForDisplayName = qb.RequestedForDisplayName,
                    BuildDefinition         = build.Definition.Name,
                    DropLocation            = build.DropLocation,
                    TeamNames               = GetUserTeamsByProjectName(requestContext, build.TeamProject, qb.RequestedFor)
                };

                yield return(notification);
            }
        }
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, BuildCompletedEvent notificationEventArgs, int maxLines)
        {
            var build = notificationEventArgs.Build;

            var converter = new Build2Converter();

            var notification = new Build2015CompletionNotification()
            {
                TeamProjectCollection = requestContext.ServiceHost.Name,
                BuildUrl                = ((ReferenceLink)build.Links.Links["web"]).Href,
                ProjectName             = build.Project.Name,
                BuildNumber             = build.BuildNumber,
                BuildStatus             = converter.ConvertBuildStatus(build.Status, build.Result),
                BuildReason             = converter.ConvertReason(build.Reason),
                StartTime               = build.StartTime.Value,
                FinishTime              = build.FinishTime.Value,
                RequestedForUniqueName  = build.RequestedFor.UniqueName,
                RequestedForDisplayName = build.RequestedFor.DisplayName,
                BuildDefinition         = build.Definition.Name,
                DropLocation            = "",
                TeamNames               = GetUserTeamsByProjectName(requestContext, build.Project.Name, build.RequestedFor.UniqueName)
            };

            yield return(notification);
        }
示例#7
0
        protected override PolicyEvaluationResult EvaluateInternal(IVssRequestContext requestContext, PushNotification push)
        {
            var newBranches    = push.RefUpdateResults.Where(r => r.OldObjectId == Sha1Id.Empty && r.Name.StartsWith(Constants.BranchPrefix));
            var newBranchNames = newBranches.Select(r => r.Name.Substring(Constants.BranchPrefix.Length));

            var badBranchNames = newBranchNames
                                 .Where(name => !WhiteListedBranchNames.Contains(name))
                                 .Where(name => !Regex.IsMatch(name, BranchPattern) ||
                                        Regex.IsMatch(name, "^feat[/-]") ||
                                        Regex.IsMatch(name, "^feature[^/]") ||
                                        Regex.IsMatch(name, "^bug[/-]") ||
                                        name == "dev" ||
                                        name == "development" ||
                                        name == "feature"
                                        );

            if (badBranchNames.Any())
            {
                Logger.Log("pushNotification:", push);
                var statusMessage = string.Format("Branch naming violation [{0}]. See {1}/guidelines/scm/git-conventions/#branch-naming.",
                                                  string.Join(", ", badBranchNames), Settings.DocsBaseUrl);
                Logger.Log(statusMessage);
                return(new PolicyEvaluationResult(false, push.Pusher, statusMessage));
            }

            return(new PolicyEvaluationResult(true));
        }
            internal Mailer(IVssRequestContext requestContext)
            {
                this.Enabled = false;
                try
                {
                    TeamFoundationRegistryService service = requestContext.GetService <TeamFoundationRegistryService>();
                    Microsoft.TeamFoundation.Framework.Server.RegistryEntryCollection registryEntryCollection = service.ReadEntriesFallThru(requestContext, FrameworkServerConstants.NotificationRootPath + "/*");
                    if (registryEntryCollection["EmailEnabled"].GetValue <bool>(true))
                    {
                        this.SmtpServer  = registryEntryCollection["SmtpServer"].GetValue(string.Empty);
                        this.SmtpPort    = registryEntryCollection["SmtpPort"].GetValue <int>(-1);
                        this.EnableSsl   = registryEntryCollection["SmtpEnableSsl"].GetValue <bool>(false);
                        this.FromAddress = null;

                        string value = registryEntryCollection["EmailNotificationFromAddress"].GetValue(string.Empty);
                        if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(this.SmtpServer))
                        {
                            this.FromAddress = new MailAddress(value);
                            this.Enabled     = true;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"SendMail failed: {ex.Message}");
                }
            }
示例#9
0
        public static bool IsDescendantOf(this TfsGitCommit commit, IVssRequestContext requestContext, Sha1Id ancestorId)
        {
            Queue <TfsGitCommit> q       = new Queue <TfsGitCommit>();
            HashSet <Sha1Id>     visited = new HashSet <Sha1Id>();

            q.Enqueue(commit);

            while (q.Count > 0)
            {
                TfsGitCommit current = q.Dequeue();
                if (!visited.Add(current.ObjectId))
                {
                    continue;
                }

                if (current.ObjectId.Equals(ancestorId))
                {
                    return(true);
                }

                foreach (var c in current.GetParents())
                {
                    q.Enqueue(c);
                }
            }
            return(false);
        }
示例#10
0
        public static bool IsForceRequired(this PushNotification pushNotification, IVssRequestContext requestContext, ITfsGitRepository repository)
        {
            foreach (var refUpdateResult in pushNotification.RefUpdateResults.Where(r => r.Succeeded))
            {
                // Don't bother with new or deleted refs
                if (refUpdateResult.OldObjectId.IsEmpty || refUpdateResult.NewObjectId.IsEmpty)
                {
                    continue;
                }

                TfsGitObject gitObject = repository.LookupObject(refUpdateResult.NewObjectId);
                if (gitObject.ObjectType != GitObjectType.Commit)
                {
                    continue;
                }
                TfsGitCommit gitCommit = (TfsGitCommit)gitObject;

                if (!gitCommit.IsDescendantOf(requestContext, refUpdateResult.OldObjectId))
                {
                    return(true);
                }
            }

            return(false);
        }
        public override async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var token = bot.GetSetting("token");
            if (string.IsNullOrEmpty(token)) throw new ArgumentException("Missing token!");

            var tasks = new List<Task>();
            var slackClient = new SlackClient();

            foreach (string tfsUserName in notification.TargetUserNames)
            {
                var userId = bot.GetMappedUser(tfsUserName);

                if (userId != null)
                {
                    Message slackMessage = ToSlackMessage((dynamic)notification, bot, null, true);
                    if (slackMessage != null)
                    {
                        slackMessage.AsUser = true;
                        var t = Task.Run(async () =>
                        {
                            var response = await slackClient.SendApiMessageAsync(slackMessage, token, userId);
                            response.EnsureSuccessStatusCode();
                            var content = await response.Content.ReadAsStringAsync();
                        });
                        tasks.Add(t);
                    }
                }
            }

            await Task.WhenAll(tasks);
        }
示例#12
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType,
                                                    object notificationEventArgs, out int statusCode, out string statusMessage,
                                                    out Microsoft.TeamFoundation.Common.ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            properties    = null;
            statusMessage = String.Empty;
            try
            {
                BuildUpdatedEvent updatedEvent = (BuildUpdatedEvent)notificationEventArgs;
                Build             build        = updatedEvent.Build;
                Log.Info($"ProcessEvent {notificationEventArgs.GetType().Name} for build {updatedEvent.BuildId} (Build Number : {updatedEvent.Build.BuildNumber}, Build Definition: {updatedEvent.Build.Definition.Name})");

                CiEvent ciEvent = CiEventUtils.ToCiEvent(build);
                if (notificationEventArgs is BuildStartedEvent)
                {
                    ciEvent.EventType = CiEventType.Started;
                    _pluginManager.GeneralEventsQueue.Add(ciEvent);
                }
                else if (notificationEventArgs is BuildCompletedEvent)
                {
                    ciEvent.EventType = CiEventType.Finished;
                    _pluginManager.HandleFinishEvent(ciEvent);
                }
            }
            catch (Exception e)
            {
                var msg = $"ProcessEvent {notificationEventArgs.GetType().Name} failed {e.Message}";
                Log.Error(msg, e);
                TeamFoundationApplicationCore.LogException(requestContext, msg, e);
            }
            return(EventNotificationStatus.ActionPermitted);
        }
 public void EnterMethod(IVssRequestContext requestContext)
 {
     using (StreamWriter w = File.AppendText(@"c:\Logs\EnterRequestLog.txt"))
     {
         Log($"Enter Request - {requestContext.RawUrl()}", w);
     }
 }
示例#14
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, PolicyViolationEvent policyViolation, int maxLines)
        {
            var commonService   = requestContext.GetService <CommonStructureService>();
            var identityService = requestContext.GetService <ITeamFoundationIdentityService>();
            var identity        = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, policyViolation.Identity.Identifier);

            var notification = new PolicyViolationNotification()
            {
                TeamProjectCollection = requestContext.ServiceHost.Name,
                ProjectName           = string.Empty,
                PolicyType            = policyViolation.PolicyType,
                Message     = policyViolation.Message,
                UniqueName  = identity.UniqueName,
                DisplayName = identity.DisplayName
            };

            var push = policyViolation.OriginalEvent as PushNotification;

            if (push != null)
            {
                notification.ProjectName = commonService.GetProject(requestContext, push.TeamProjectUri).Name;
            }


            yield return(notification);
        }
示例#15
0
        public Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            if (!notification.TargetUserNames.Any())
            {
                return(Task.FromResult(0));
            }

            var    config             = TfsNotificationRelaySection.Instance;
            string host               = bot.GetSetting("host", "127.0.0.1");
            int    port               = bot.GetIntSetting("port", 25);
            string fromAddress        = bot.GetSetting("fromAddress");
            string fromName           = bot.GetSetting("fromName");
            string subjectTextId      = bot.GetSetting("subjectTextId", "plaintext");
            bool   isHtml             = bot.GetSetting("isHtml") == "true";
            var    subjectTextElement = config.Texts.FirstOrDefault(t => t.Id == subjectTextId) ?? bot.Text;
            string subject            = notification.ToMessage(bot, subjectTextElement, s => s).First();

            var client = new SmtpClient(host, port);

            var message = new MailMessage();

            message.From            = new MailAddress(fromAddress, fromName, Encoding.UTF8);
            message.SubjectEncoding = Encoding.UTF8;
            message.Subject         = subject;
            message.IsBodyHtml      = isHtml;
            message.BodyEncoding    = Encoding.UTF8;
            message.Body            = string.Join(isHtml ? "<br/>": "\n", notification.ToMessage(bot, s => s));

            var identityService = requestContext.GetService <ITeamFoundationIdentityService>();

            foreach (var username in notification.TargetUserNames)
            {
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.AccountName, username);
                var email    = identityService.GetPreferredEmailAddress(requestContext, identity.TeamFoundationId);
                if (string.IsNullOrEmpty(email))
                {
                    string errmsg = $"TfsNotificationRelay.Smtp.SmtpNotifier: User {username} doesn't have an email address.";
                    TeamFoundationApplicationCore.Log(requestContext, errmsg, 0, EventLogEntryType.Warning);
                }
                else
                {
                    message.To.Add(email);
                }
            }

            if (message.To.Any())
            {
                requestContext.Trace(0, TraceLevel.Info, Constants.TraceArea, "SmtpNotifier",
                                     string.Format("Sending {0} email notification to: {1}.", notification.GetType(), string.Join(", ", message.To.Select(m => m.Address))));

                return(client.SendMailAsync(message));
            }
            else
            {
                requestContext.Trace(0, TraceLevel.Warning, Constants.TraceArea, "SmtpNotifier",
                                     string.Format("No recipients to send {0} email notification to.", notification.GetType()));

                return(Task.FromResult(0));
            }
        }
示例#16
0
 private static IVssRequestContext CreateServicingContext(IVssDeploymentServiceHost deploymentServiceHost, Guid instanceId)
 {
     using (IVssRequestContext requestContext = deploymentServiceHost.CreateSystemContext(true))
     {
         TeamFoundationHostManagementService host = requestContext.GetService <TeamFoundationHostManagementService>();
         return(host.BeginRequest(requestContext, instanceId, RequestContextType.ServicingContext));
     }
 }
        public void BeginRequest(IVssRequestContext requestContext)
        {
            try
            {
                if (!requestContext.ServiceHost.HostType.HasFlag(TeamFoundationHostType.ProjectCollection))
                {
                    return;
                }

                if (HttpContext.Current.Request.Url.ToString().Contains("/_api/_wit/updateWorkItems"))
                {
                    string content = ReadHttpContextInputStream(HttpContext.Current.Request.InputStream);
                    content = content.Replace("\0", "");
                    Log(content, "BeginRequest");
                    dynamic Workitem = Json.Decode(Json.Decode(content).updatePackage);

                    Log("New Request Started", "BeginRequest");
                    string Url = HttpContext.Current.Request.Url.ToString();
                    Log(Url, "BeginRequest");
                    string projectId     = Workitem[0].projectId;
                    string collectionUrl = new Regex(@"(http(s)?://?)\w+(:\d{4})?/tfs/\w+collection").Match(Url).Value;
                    string workItemId    = Workitem[0].Id.ToString();
                    Log(workItemId, "BeginRequest");
                    Log($"Collection: {collectionUrl}", "BeginRequest");
                    //string Username = ConfigurationManager.AppSettings["Username"];
                    //string Password = ConfigurationManager.AppSettings["Password"];
                    //Log($"{Username} | {Password}", "BeginRequest");
                    //NetworkCredential credential = new NetworkCredential(Username,Password);
                    TfsTeamProjectCollection tfsTeamProjectCollection = new TfsTeamProjectCollection(new Uri(collectionUrl));
                    //tfsTeamProjectCollection.Authenticate();
                    Guid    p = new Guid(projectId);
                    var     workItemInstance = tfsTeamProjectCollection.GetService <WorkItemStore>();
                    Project teamProject      = workItemInstance.Projects[p];

                    var parentWorkItem = GetParent(workItemId, workItemInstance);
                    var childs         = GetChilds(parentWorkItem, workItemInstance);

                    bool parentDone = !childs.Any(x => x.State == "In Progress" || x.State == "To Do");

                    if (parentDone)
                    {
                        parentWorkItem.Open();
                        parentWorkItem.State = "Done";
                        parentWorkItem.Save();
                    }
                    else
                    {
                        parentWorkItem.Open();
                        parentWorkItem.State = "Committed";
                        parentWorkItem.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                Log($"Throwing Exception: {ex.Message}", "Exceptions");
            }
        }
示例#18
0
        public Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            if (!notification.TargetUserNames.Any())
                return Task.FromResult(0);

            var config = TfsNotificationRelaySection.Instance;
            string host = bot.GetSetting("host", "127.0.0.1");
            int port = bot.GetIntSetting("port", 25);
            string fromAddress = bot.GetSetting("fromAddress");
            string fromName = bot.GetSetting("fromName");
            string subjectTextId = bot.GetSetting("subjectTextId", "plaintext");
            bool isHtml = bot.GetSetting("isHtml") == "true";
            var subjectTextElement = config.Texts.FirstOrDefault(t => t.Id == subjectTextId) ?? bot.Text;
            string subject = notification.ToMessage(bot, subjectTextElement, s => s).First();

            var client = new SmtpClient(host, port);

            var message = new MailMessage();
            message.From = new MailAddress(fromAddress, fromName, Encoding.UTF8);
            message.SubjectEncoding = Encoding.UTF8;
            message.Subject = subject;
            message.IsBodyHtml = isHtml;
            message.BodyEncoding = Encoding.UTF8;
            message.Body = string.Join(isHtml ? "<br/>": "\n", notification.ToMessage(bot, s => s));

            var identityService = requestContext.GetService<ITeamFoundationIdentityService>();

            foreach (var username in notification.TargetUserNames)
            {
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.AccountName, username);
                var email = identityService.GetPreferredEmailAddress(requestContext, identity.TeamFoundationId);
                if (string.IsNullOrEmpty(email))
                {
                    string errmsg = $"TfsNotificationRelay.Smtp.SmtpNotifier: User {username} doesn't have an email address.";
                    TeamFoundationApplicationCore.Log(requestContext, errmsg, 0, EventLogEntryType.Warning);
                }
                else
                {
                    message.To.Add(email);
                }
            }

            if (message.To.Any())
            {
                requestContext.Trace(0, TraceLevel.Info, Constants.TraceArea, "SmtpNotifier",
                    string.Format("Sending {0} email notification to: {1}.", notification.GetType(), string.Join(", ", message.To.Select(m => m.Address))));

                return client.SendMailAsync(message);
            }
            else
            {
                requestContext.Trace(0, TraceLevel.Warning, Constants.TraceArea, "SmtpNotifier",
                    string.Format("No recipients to send {0} email notification to.", notification.GetType()));

                return Task.FromResult(0);
            }
        }
示例#19
0
        public virtual Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string webHookUrl = bot.GetSetting("webhookUrl");

            var msTeamsClient = new MsTeamsClient(webHookUrl);

            Message message = MsTeamsHelper.CreateMsTeamsMessage((dynamic)notification, bot);

            return(msTeamsClient.SendWebhookMessageAsync(message).ContinueWith(t => t.Result.EnsureSuccessStatusCode()));
        }
示例#20
0
 protected override void Initialize(IVssRequestContext requestContext, string databaseCategory, int serviceVersion, ITFLogger logger)
 {
     // LockingComponent and LockingComponent2 work on a single tenant dbs. PartitionId must be set to 1.
     // We need to set PartitionId excplicitly, otherwise upgrade from Orcas will fail,
     // because prc_QueryPartition sproc is not installed yet.
     if (serviceVersion < 3)
     {
         PartitionId = 1;
     }
 }
示例#21
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            statusMessage = string.Empty;
            properties    = null;

            Logger.Log("notificationType: " + notificationType);
            Logger.Log("event: " + notificationEventArgs.GetType());
            Logger.Log("eventargs", notificationEventArgs);

            return(EventNotificationStatus.ActionApproved);
        }
 public static void MapAndLoadCustomConfig(IVssRequestContext vssRequestContext)
 {
     if (config == null)
     {
         var basePath  = vssRequestContext != null ? vssRequestContext.RootContext.ServiceHost.PlugInDirectory + "\\TfsJira\\" : "";
         var configMap = new ExeConfigurationFileMap
         {
             ExeConfigFilename = basePath + "TfsJira.Plugin.config"
         };
         config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
     }
 }
示例#23
0
        public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
        {
            statusCode = 0;
            statusMessage = string.Empty;
            properties = null;

            Logger.Log("notificationType: " + notificationType);
            Logger.Log("event: " + notificationEventArgs.GetType());
            Logger.Log("eventargs", notificationEventArgs);

            return EventNotificationStatus.ActionApproved;
        }
示例#24
0
        protected override PolicyEvaluationResult Evaluate(IVssRequestContext requestContext, PushNotification notificationEventArgs)
        {
            var commonService = requestContext.GetService <ICommonStructureService>();
            var push          = (PushNotification)notificationEventArgs;
            var projectName   = commonService.GetProject(requestContext, push.TeamProjectUri).Name;

            if (projectName == "TestCompany")
            {
                return(new PolicyEvaluationResult(true));
            }

            return(EvaluateInternal(requestContext, notificationEventArgs));
        }
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, TFVC.CheckinNotification checkin, int maxLines)
        {
            var locationService = requestContext.GetService <ILocationService>();

            string baseUrl = String.Format("{0}/{1}/",
                                           locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                                           requestContext.ServiceHost.Name);

            var teamNames = new HashSet <string>();
            var projects  = new Dictionary <string, string>();

            var submittedItems = checkin.GetSubmittedItems(requestContext).ToList();

            const string pattern = @"^\$\/([^\/]*)\/";

            foreach (string item in submittedItems)
            {
                Match match = Regex.Match(item, pattern);
                if (match.Success)
                {
                    string projectName = match.Groups[1].Value;
                    if (projects.ContainsKey(projectName))
                    {
                        continue;
                    }

                    string projectUrl = baseUrl + projectName;
                    projects.Add(projectName, projectUrl);

                    foreach (var team in GetUserTeamsByProjectName(requestContext, projectName, checkin.ChangesetOwner.Descriptor))
                    {
                        teamNames.Add(team);
                    }
                }
            }

            var notification = new CheckinNotification()
            {
                TeamProjectCollection = requestContext.ServiceHost.Name,
                UniqueName            = checkin.ChangesetOwner.UniqueName,
                DisplayName           = checkin.ChangesetOwner.DisplayName,
                ChangesetUrl          = $"{baseUrl}_versionControl/changeset/{checkin.Changeset}",
                ChangesetId           = checkin.Changeset,
                Projects       = projects,
                Comment        = TextHelper.Truncate(checkin.Comment, Settings.CommentMaxLength, true),
                TeamNames      = teamNames,
                SubmittedItems = submittedItems
            };

            yield return(notification);
        }
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, ProjectDeletedEvent ev, int maxLines)
        {
            string projectName;

            if (ProjectsNames.TryGetValue(ev.Uri, out projectName))
            {
                ProjectsNames.Remove(ev.Uri);
            }

            yield return(new ProjectDeletedNotification()
            {
                TeamProjectCollection = requestContext.ServiceHost.Name, ProjectUri = ev.Uri, ProjectName = projectName
            });
        }
        public async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string room = bot.GetSetting("room");
            string baseUrl = bot.GetSetting("apiBaseUrl");
            string authToken = bot.GetSetting("roomNotificationToken");

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            string json = ToJson((dynamic)notification, bot);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            string url = baseUrl + "/room/" + room + "/notification";
            requestContext.Trace(0, TraceLevel.Verbose, Constants.TraceArea, "HipChatNotifier", "Sending notification to {0}\n{1}", url, json);

            await httpClient.PostAsync(url, content).ContinueWith(t => t.Result.EnsureSuccessStatusCode());
        }
示例#28
0
        public static bool IsForceRequired(this PushNotification pushNotification, IVssRequestContext requestContext, ITfsGitRepository repository)
        {
            foreach (var refUpdateResult in pushNotification.RefUpdateResults.Where(r => r.Succeeded))
            {
                // Don't bother with new or deleted refs
                if (refUpdateResult.OldObjectId.IsEmpty || refUpdateResult.NewObjectId.IsEmpty) continue;

                TfsGitObject gitObject = repository.LookupObject(refUpdateResult.NewObjectId);
                if (gitObject.ObjectType != GitObjectType.Commit) continue;
                TfsGitCommit gitCommit = (TfsGitCommit)gitObject;

                if (!gitCommit.IsDescendantOf(requestContext, refUpdateResult.OldObjectId))
                    return true;
            }

            return false;
        }
 public void BeginRequest(IVssRequestContext requestContext)
 {
     if (!requestContext.ServiceHost.HostType.HasFlag(TeamFoundationHostType.ProjectCollection))
     {
         return;
     }
     if (HttpContext.Current.Request.Url.ToString().Contains("/_api/_wit/updateWorkItems"))
     {
         string content = ReadHttpContextInputStream(HttpContext.Current.Request.InputStream);
         content = content.Replace("\0", "");
         dynamic Workitem = Json.Decode(Json.Decode(content).updatePackage);
         if (Workitem[0].fields["10015"] > 2)
         {
             throw new ValidationRequestFilterException("Priorities grater than 2 are not allowed.");
         }
     }
 }
示例#30
0
        public virtual async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var channels = bot.GetCsvSetting("channels");
            var tasks = new List<Task>();
            var slackClient = new SlackClient();

            foreach (string channel in channels)
            {
                Message slackMessage = ToSlackMessage((dynamic)notification, bot, channel, false);
                if (slackMessage != null)
                {
                    tasks.Add(slackClient.SendWebhookMessageAsync(slackMessage, bot.GetSetting("webhookUrl")).ContinueWith(t => t.Result.EnsureSuccessStatusCode()));
                }
            }

            await Task.WhenAll(tasks);
        }
示例#31
0
        public virtual async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            var channels    = bot.GetCsvSetting("channels");
            var tasks       = new List <Task>();
            var slackClient = new SlackClient();

            foreach (string channel in channels)
            {
                Message slackMessage = ToSlackMessage((dynamic)notification, bot, channel, false);
                if (slackMessage != null)
                {
                    tasks.Add(slackClient.SendWebhookMessageAsync(slackMessage, bot.GetSetting("webhookUrl")).ContinueWith(t => t.Result.EnsureSuccessStatusCode()));
                }
            }

            await Task.WhenAll(tasks);
        }
示例#32
0
        private static void RunFeatureEnablement(IVssDeploymentServiceHost deploymentServiceHost, Microsoft.TeamFoundation.WorkItemTracking.Client.Project project, Guid instanceId, StreamWriter file)
        {
            try
            {
                Console.WriteLine("Running feature enablement for '{0}'", project.Name);

                using (IVssRequestContext context = CreateServicingContext(deploymentServiceHost, instanceId))
                {
                    ProvisionProjectFeatures(context, project, file);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Feature enablement failed for project '{0}': see log for details.", project.Name);
                file.WriteLine(">>> Feature enablement failed for project '{0}': {1}", project.Name, ex);
            }
        }
        public async Task NotifyAsync(IVssRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string room      = bot.GetSetting("room");
            string baseUrl   = bot.GetSetting("apiBaseUrl");
            string authToken = bot.GetSetting("roomNotificationToken");

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

            string json    = ToJson((dynamic)notification, bot);
            var    content = new StringContent(json, Encoding.UTF8, "application/json");
            string url     = baseUrl + "/room/" + room + "/notification";

            requestContext.Trace(0, TraceLevel.Verbose, Constants.TraceArea, "HipChatNotifier", "Sending notification to {0}\n{1}", url, json);

            await httpClient.PostAsync(url, content).ContinueWith(t => t.Result.EnsureSuccessStatusCode());
        }
        public EventNotificationStatus ProcessEvent(
            IVssRequestContext requestContext,
            NotificationType notificationType,
            object notificationEventArgs,
            out int statusCode,
            out string statusMessage,
            out ExceptionPropertyCollection properties)
        {
            statusCode    = 0;
            statusMessage = string.Empty;
            properties    = null;

            if (notificationType == NotificationType.DecisionPoint && notificationEventArgs is PushNotification)
            {
                var pushNotification = notificationEventArgs as PushNotification;

                var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();

                using (var gitRepository = repositoryService.FindRepositoryById(
                           requestContext,
                           pushNotification.RepositoryId))
                {
                    // TODO: gitRepository.Name should probably equal "Estream". Company wide TFS instance!
                    // TODO: Also, this name should not be hard coded and should be a collection.

                    foreach (var item in pushNotification.IncludedCommits)
                    {
                        var gitCommit = (TfsGitCommit)gitRepository.LookupObject(item);

                        var comment = gitCommit.GetComment(requestContext);

                        if (!CommitRules.IsCommitAcceptable(comment))
                        {
                            statusMessage =
                                $"Non-merge commits must contain links to TFS (i.e. #12345) [Repository Name: {gitRepository.Name}].";
                            return(EventNotificationStatus.ActionDenied);
                        }
                    }
                }
            }

            return(EventNotificationStatus.ActionApproved);
        }
示例#35
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, ProjectCreatedEvent ev, int maxLines)
        {
            var locationService = requestContext.GetService <ILocationService>();

            string projectUrl = String.Format("{0}/{1}/{2}",
                                              locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                                              requestContext.ServiceHost.Name,
                                              ev.Name);

            if (!ProjectsNames.ContainsKey(ev.Uri))
            {
                ProjectsNames.Add(ev.Uri, ev.Name);
            }

            yield return(new ProjectCreatedNotification()
            {
                TeamProjectCollection = requestContext.ServiceHost.Name, ProjectUrl = projectUrl, ProjectName = ev.Name
            });
        }
示例#36
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, StatusUpdateNotification ev, int maxLines)
        {
            var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();
            var identityService   = requestContext.GetService <ITeamFoundationIdentityService>();
            var commonService     = requestContext.GetService <ICommonStructureService>();

            var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, ev.Updater.Descriptor.Identifier);

            using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, ev.RepositoryId))
            {
                var pullRequestService = requestContext.GetService <ITeamFoundationGitPullRequestService>();
                TfsGitPullRequest pullRequest;
                if (pullRequestService.TryGetPullRequestDetails(requestContext, repository, ev.PullRequestId, out pullRequest))
                {
                    string repoUri      = repository.GetRepositoryUri();
                    var    creator      = identityService.ReadIdentities(requestContext, new[] { pullRequest.Creator }).First();
                    var    reviewers    = identityService.ReadIdentities(requestContext, pullRequest.Reviewers.Select(r => r.Reviewer).ToArray());
                    var    notification = new PullRequestStatusUpdateNotification()
                    {
                        TeamProjectCollection = requestContext.ServiceHost.Name,
                        CreatorUniqueName     = creator.UniqueName,
                        Status            = ev.Status,
                        UniqueName        = identity.UniqueName,
                        DisplayName       = identity.DisplayName,
                        ProjectName       = commonService.GetProject(requestContext, ev.TeamProjectUri).Name,
                        RepoUri           = repoUri,
                        RepoName          = ev.RepositoryName,
                        PrId              = pullRequest.PullRequestId,
                        PrUrl             = $"{repoUri}/pullrequest/{ev.PullRequestId}#view=discussion",
                        PrTitle           = pullRequest.Title,
                        TeamNames         = GetUserTeamsByProjectUri(requestContext, ev.TeamProjectUri, ev.Updater.Descriptor),
                        SourceBranch      = new GitRef(pullRequest.SourceBranchName),
                        TargetBranch      = new GitRef(pullRequest.TargetBranchName),
                        ReviewerUserNames = reviewers.Select(r => r.UniqueName)
                    };
                    yield return(notification);
                }
                else
                {
                    throw new TfsNotificationRelayException("Unable to get pull request " + ev.PullRequestId);
                }
            }
        }
示例#37
0
        private static void ProvisionProjectFeatures(IVssRequestContext context, Microsoft.TeamFoundation.WorkItemTracking.Client.Project project, StreamWriter logFile)
        {
            // Get the Feature provisioning service ("Configure Features")
            var projectFeatureProvisioningService = context.GetService <ProjectFeatureProvisioningService>();

            if (!projectFeatureProvisioningService.GetFeatures(context, project.Uri.ToString()).Where(f => (f.State == ProjectFeatureState.NotConfigured && !f.IsHidden)).Any())
            {
                // When the team project is already fully or partially configured, report it
                Console.WriteLine("\t{0}: Project is up to date.", project.Name);
                logFile.WriteLine(">>> Team Project is now already up to date");
            }
            else
            {
                // Find valid process templates
                var projectFeatureProvisioningDetails = projectFeatureProvisioningService.ValidateProcessTemplates(context, project.Uri.ToString());

                var validProcessTemplateDetails = projectFeatureProvisioningDetails.Where(d => d.IsValid);

                switch (validProcessTemplateDetails.Count())
                {
                case 0:
                    Console.WriteLine("\t{0}: No valid process templates found.", project.Name);
                    logFile.WriteLine(">>> No valid process templates found, the team project cannot be configured/upgraded automatically to adopt the latest features.");
                    break;

                case 1:
                    var projectFeatureProvisioningDetail = projectFeatureProvisioningDetails.ElementAt(0);
                    Console.WriteLine(">>> Upgrading Team Project with template " + projectFeatureProvisioningDetail.ProcessTemplateDescriptorName);
                    logFile.WriteLine(">>> Upgrading Team Project with template " + projectFeatureProvisioningDetail.ProcessTemplateDescriptorName);
                    ProvisionProject(context, project, projectFeatureProvisioningService, projectFeatureProvisioningDetail);
                    break;

                default:
                    // Try to upgrade using the recommended process template
                    var newRecommendedTemplate = validProcessTemplateDetails.FirstOrDefault(ptd => ptd.IsRecommended);
                    Console.WriteLine(">>> Multiple valid process templates found. Upgrading Team Project with recommended template " + newRecommendedTemplate.ProcessTemplateDescriptorName);
                    logFile.WriteLine(">>> Multiple valid process templates found. Upgrading Team Project with recommended template " + newRecommendedTemplate.ProcessTemplateDescriptorName);
                    ProvisionProject(context, project, projectFeatureProvisioningService, newRecommendedTemplate);
                    break;
                }
            }
        }
示例#38
0
        public static bool IsDescendantOf(this TfsGitCommit commit, IVssRequestContext requestContext, Sha1Id ancestorId)
        {
            Queue<TfsGitCommit> q = new Queue<TfsGitCommit>();
            HashSet<Sha1Id> visited = new HashSet<Sha1Id>();

            q.Enqueue(commit);

            while (q.Count > 0)
            {
                TfsGitCommit current = q.Dequeue();
                if (!visited.Add(current.ObjectId))
                    continue;

                if (current.ObjectId.Equals(ancestorId)) return true;

                foreach (var c in current.GetParents(requestContext))
                    q.Enqueue(c);

            }
            return false;
        }