Пример #1
0
        public static Slack.Message CreateSlackMessage(string header, IList <AttachmentField> fields, BotElement bot, string channel, string color)
        {
            if (header == null)
            {
                return(null);
            }

            var message = new Slack.Message()
            {
                Channel     = channel,
                Username    = bot.GetSetting("username"),
                Attachments = new[] {
                    new Attachment()
                    {
                        Fallback = header,
                        Pretext  = header,
                        Color    = color,
                        Fields   = fields
                    }
                }
            };

            if (!String.IsNullOrEmpty(bot.GetSetting("iconUrl")))
            {
                message.IconUrl = bot.GetSetting("iconUrl");
            }
            else if (!String.IsNullOrEmpty(bot.GetSetting("iconEmoji")))
            {
                message.IconEmoji = bot.GetSetting("iconEmoji");
            }

            return(message);
        }
        public Message ToSlackMessage(BuildCompletionNotification notification, BotElement bot, string channel)
        {
            var lines = notification.ToMessage(bot, s => s);
            var color = notification.IsSuccessful ? bot.GetSetting("successColor") : bot.GetSetting("errorColor");

            return(SlackHelper.CreateSlackMessage(lines, bot, channel, color));
        }
Пример #3
0
        public Task NotifyAsync(TeamFoundationRequestContext 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));
            }
        }
Пример #4
0
        private static JObject CreateHipChatMessage(INotification notification, BotElement bot, string color)
        {
            dynamic jobject = new JObject();

            if (bot.GetSetting("messageFormat") == "text")
            {
                var lines = notification.ToMessage(bot, s => s);
                if (lines == null || !lines.Any())
                {
                    return(null);
                }
                jobject.message_format = "text";
                jobject.message        = string.Join("\n", lines);
            }
            else
            {
                var lines = notification.ToMessage(bot, HttpUtility.HtmlEncode);
                if (lines == null || !lines.Any())
                {
                    return(null);
                }
                jobject.message_format = "html";
                jobject.message        = string.Join("<br/>", lines);
            }
            jobject.color  = color;
            jobject.notify = bot.GetSetting("notify").Equals("true", StringComparison.OrdinalIgnoreCase);

            return(jobject);
        }
Пример #5
0
        internal static Message CreateMsTeamsMessage(INotification notification, BotElement bot)
        {
            var lines = notification.ToMessage(bot, s => s);

            if (lines == null || !lines.Any())
            {
                return(null);
            }

            var sb = new StringBuilder();

            sb.Append("#####"); // Not using message.Title for now. It's displayed too small, doesn't handle markdown and is not shown at all on Android client.
            sb.AppendLine(lines.First());
            foreach (var line in lines.Skip(1))
            {
                sb.Append("* ");
                sb.AppendLine(line);
            }
            var     color   = bot.GetSetting("standardColor").Substring(1);
            Message message = new Message()
            {
                Text = sb.ToString(), ThemeColor = color
            };

            return(message);
        }
        public override async Task NotifyAsync(TeamFoundationRequestContext 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);
        }
        public async Task NotifyAsync(TeamFoundationRequestContext requestContext, INotification notification, BotElement bot)
        {
            var channels    = bot.GetSetting("channels").Split(',').Select(chan => chan.Trim());
            var tasks       = new List <Task>();
            var slackClient = new SlackClient();

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

            await Task.WhenAll(tasks);
        }
        public Message ToSlackMessage(WorkItemCommentNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();
            var    fields = new[] {
                new AttachmentField(bot.Text.Comment, notification.Comment, false)
            };

            return(SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor")));
        }
        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());
        }
Пример #10
0
        public static Message CreateSlackMessage(string header, IEnumerable <AttachmentField> fields, BotElement bot, string channel, string color, bool asUser)
        {
            if (header == null)
            {
                return(null);
            }
            IEnumerable <Attachment> attachments = null;

            if (fields.Any())
            {
                attachments = new[] {
                    new Attachment()
                    {
                        Fallback = header,
                        Color    = color,
                        Fields   = fields
                    }
                };
            }
            var message = new Message()
            {
                Channel     = channel,
                Text        = header,
                Attachments = attachments
            };

            message.Text = header;

            if (!asUser)
            {
                message.Username = bot.GetSetting("username");
                if (!String.IsNullOrEmpty(bot.GetSetting("iconUrl")))
                {
                    message.IconUrl = bot.GetSetting("iconUrl");
                }
                else if (!String.IsNullOrEmpty(bot.GetSetting("iconEmoji")))
                {
                    message.IconEmoji = bot.GetSetting("iconEmoji");
                }
            }

            return(message);
        }
        public Message ToSlackMessage(WorkItemChangedNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();
            var    fields = new[] {
                new AttachmentField(bot.Text.State, notification.State, true),
                new AttachmentField(bot.Text.AssignedTo, notification.AssignedTo, true)
            };

            return(SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor")));
        }
Пример #12
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()));
        }
Пример #13
0
        public void Notify(INotification notification, BotElement bot)
        {
            string servicEndpoint = bot.GetSetting("serviceEndpoint", "net.pipe://localhost/BotService");

            ChannelFactory <IBotService> factory = new ChannelFactory <IBotService>(new NetNamedPipeBinding(),
                                                                                    new EndpointAddress(servicEndpoint));
            IBotService service = factory.CreateChannel();

            foreach (string line in notification.ToMessage(bot))
            {
                service.SendMessage(line);
            }
        }
Пример #14
0
        internal static Message CreateMsTeamsMessage(BuildCompletionNotification notification, BotElement bot)
        {
            var lines = notification.ToMessage(bot, s => s);

            if (lines == null || !lines.Any())
            {
                return(null);
            }

            string color = notification.IsPartiallySucceeded ? bot.GetSetting("partiallySucceededColor") : (notification.IsSuccessful ? bot.GetSetting("successColor") : bot.GetSetting("errorColor"));

            return(CreateMsTeamsMessage(lines[0], new[] { new Fact(bot.Text.BuildStatus, $"**{lines[1]}**") }, color));
        }
Пример #15
0
        public Message ToSlackMessage(ReleaseEnvironmentCompletedNotification notification, BotElement bot, string channel, bool asUser)
        {
            string header = notification.ToMessage(bot, s => s).First();
            string color  = null;

            if (notification.EnvironmentStatus == EnvironmentStatus.Succeeded)
            {
                color = bot.GetSetting("successColor");
            }
            else if (notification.EnvironmentStatus == EnvironmentStatus.Rejected || notification.EnvironmentStatus == EnvironmentStatus.Canceled)
            {
                color = bot.GetSetting("errorColor");
            }
            else
            {
                color = bot.GetSetting("standardColor");
            }

            var fields = new[] {
                new AttachmentField(notification.EnvironmentName, notification.EnvironmentStatus.ToString(), false)
            };

            return(SlackHelper.CreateSlackMessage(header, fields, bot, channel, color, asUser));
        }
Пример #16
0
        public virtual async Task NotifyAsync(TeamFoundationRequestContext 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);
        }
Пример #17
0
        internal static Message CreateMsTeamsMessage(WorkItemChangedNotification notification, BotElement bot)
        {
            string heading = notification.ToMessage(bot, s => s).First();

            var facts = new List <Fact>();

            var searchType       = notification.IsNew ? SearchFieldsType.Core : SearchFieldsType.Changed;
            var displayFieldsKey = notification.IsNew ? "wiCreatedDisplayFields" : "wiChangedDisplayFields";

            foreach (var fieldId in bot.GetCsvSetting(displayFieldsKey, Defaults.WorkItemFields))
            {
                var field = notification.GetUnifiedField(fieldId, searchType);
                if (field != null)
                {
                    var fieldrep = notification.IsNew ? field.NewValue : bot.Text.WorkItemFieldTransitionFormat.FormatWith(field);
                    facts.Add(new Fact(field.Name, fieldrep));
                }
            }

            return(CreateMsTeamsMessage(heading, facts, bot.GetSetting("standardColor")));
        }
        public Message ToSlackMessage(WorkItemChangedNotification notification, BotElement bot, string channel)
        {
            string header = notification.ToMessage(bot, s => s).First();

            var fields = new List <AttachmentField>();

            var searchType       = notification.IsNew ? SearchFieldsType.Core : SearchFieldsType.Changed;
            var displayFieldsKey = notification.IsNew ? "wiCreatedDisplayFields" : "wiChangedDisplayFields";

            foreach (var fieldId in bot.GetCsvSetting(displayFieldsKey, Defaults.WorkItemFields))
            {
                var field = notification.GetUnifiedField(fieldId, searchType);
                if (field != null)
                {
                    var fieldrep = notification.IsNew ? field.NewValue : bot.Text.WorkItemFieldTransitionFormat.FormatWith(field);
                    fields.Add(new AttachmentField(field.Name, fieldrep, true));
                }
            }

            return(SlackHelper.CreateSlackMessage(header, fields, bot, channel, bot.GetSetting("standardColor")));
        }
        public async Task NotifyAsync(TeamFoundationRequestContext requestContext, INotification notification, BotElement bot, EventRuleElement matchingRule)
        {
            string URL        = bot.GetSetting("spiraURL");
            string user       = bot.GetSetting("spiraUser");
            string password   = bot.GetSetting("spiraPassw");
            string projVers   = bot.GetSetting("spiraPvers");
            string projNumber = bot.GetSetting("spiraPnumber");
            int    status     = 0;
            int    projectId;

            Int32.TryParse(projNumber, out projectId);

            //Check that it is the correct kind of notification
            if (notification is BuildCompletionNotification)
            {
                BuildCompletionNotification buildCompletionNotification = (BuildCompletionNotification)notification;

                if (buildCompletionNotification.IsSuccessful)
                {
                    status = 2;  //sucess
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "Failed")
                {
                    status = 1; //failed
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "PartiallySucceeded")
                {
                    status = 3; //unstable
                }
                else if (buildCompletionNotification.BuildStatus.ToString() == "Stopped")
                {
                    status = 4; //aborted
                }
                else
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS:: The current build finished with a not supported" +
                                                      " status, please check TFS logs to see detailed information.", 0, EventLogEntryType.Warning);
                }


                DateTime date        = buildCompletionNotification.StartTime;
                String   sname       = buildCompletionNotification.ProjectName + " #" + buildCompletionNotification.BuildNumber;
                String   description = ("Information retrieved from TFS : Build requested by " +
                                        buildCompletionNotification.UserName + "<br/> from Team " +
                                        buildCompletionNotification.TeamNames + "<br/> and project collection " +
                                        buildCompletionNotification.TeamProjectCollection + "<br/> for " + sname +
                                        "<br/> with URL " + buildCompletionNotification.BuildUrl +
                                        "<br/> located at " + buildCompletionNotification.DropLocation +
                                        "<br/> Build Started at " + buildCompletionNotification.StartTime +
                                        "<br/> Build finished at " + buildCompletionNotification.FinishTime +
                                        "<br/> Status " + buildCompletionNotification.BuildStatus);
                //List<int> incidentIds;
                var    locationService = requestContext.GetService <TeamFoundationLocationService>();
                string baseUrl         = String.Format("{0}/", locationService.GetAccessMapping(requestContext,
                                                                                                "PublicAccessMapping").AccessPoint);
                TfsTeamProjectCollection tpc           = new TfsTeamProjectCollection(new Uri(baseUrl));
                VersionControlServer     sourceControl = tpc.GetService <VersionControlServer>();
                int revisionId = sourceControl.GetLatestChangesetId();

                //SPIRA CODE
                Uri uri = new Uri(URL + URL_SUFFIX);
                ImportExportClient spiraClient = SpiraClientFactory.CreateClient(uri);
                bool success = spiraClient.Connection_Authenticate2(user, password, "TFS Notifier for SpiraTeam v. 1.0.0");
                if (!success)
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: Unable to connect to the Spira server, please verify" +
                                                      " the provided information in the configuration file.", 0, EventLogEntryType.Error);
                }
                success = spiraClient.Connection_ConnectToProject(projectId);
                if (!success)
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: The project Id you specified either does not exist," +
                                                      "or your user does not have access to it! Please verify the configuration file.", 0, EventLogEntryType.Error);
                }

                RemoteRelease[] releases = spiraClient.Release_Retrieve(true);
                RemoteRelease   release  = releases.FirstOrDefault(r => r.VersionNumber == projVers);
                if (release != null)
                {
                    List <RemoteBuildSourceCode> revisions = new List <RemoteBuildSourceCode>();
                    RemoteBuildSourceCode        revision  = new RemoteBuildSourceCode();
                    revision.RevisionKey = revisionId.ToString();
                    revisions.Add(revision);

                    RemoteBuild newBuild = new RemoteBuild();
                    newBuild.Name          = sname;
                    newBuild.BuildStatusId = status;
                    newBuild.Description   = description;
                    newBuild.CreationDate  = date;
                    newBuild.Revisions     = revisions.ToArray();
                    newBuild.ReleaseId     = release.ReleaseId.Value;
                    spiraClient.Build_Create(newBuild);
                    await Task.Delay(10);
                }
                else
                {
                    TeamFoundationApplicationCore.Log(requestContext, ":: SpiraTeam Plugin for TFS :: The release version number you specified does not " +
                                                      "exist in the current project! Please verify the configuration file.", 0, EventLogEntryType.Error);
                }
            }
        }
        public Message ToSlackMessage(INotification notification, BotElement bot, string channel)
        {
            var lines = notification.ToMessage(bot, s => s);

            return(SlackHelper.CreateSlackMessage(lines, bot, channel, bot.GetSetting("standardColor")));
        }
Пример #21
0
        private string ToJson(BuildCompletionNotification notification, BotElement bot)
        {
            var color = notification.IsSuccessful ? bot.GetSetting("successColor") : bot.GetSetting("errorColor");

            return(CreateHipChatMessage(notification, bot, color).ToString());
        }
Пример #22
0
 private string ToJson(INotification notification, BotElement bot)
 {
     return(CreateHipChatMessage(notification, bot, bot.GetSetting("standardColor")).ToString());
 }
Пример #23
0
        internal static Message CreateMsTeamsMessage(ICommentNotification notification, BotElement bot)
        {
            string heading = notification.ToMessage(bot, s => s).First();

            return(CreateMsTeamsMessage(heading, new[] { new Fact(bot.Text.Comment, notification.Comment) }, bot.GetSetting("standardColor")));
        }