0

I have this code that notifies a slack channel after a build has completed. In certain cases, whenever the build fails, I want to add a notification to myself so I can quickly turn issues around. How can I update this to include a notification to someone using the @ symbol?

Some examples I see online use the SlackMessage constructor to add a userName, but for some reason I can not overload this constructor.

public static void PostToSlack()
        {
            string url= "...";
            string slackUrl = GlobalData.slackUrl;
            string buildName = TestContext.Parameters["BuildName"];
            string buildID = TestContext.Parameters["BuildID"];
            string testName = TestContext.CurrentContext.Test.Name;
            string outcome = TestContext.CurrentContext.Result.Outcome.ToString();

            //If tests failed but the suite actually completed, set more understandable outcome message
            if (outcome == "Failed(Child)")
            {
                outcome = "Completed with Issues";
            }

            //Build the text string to post to slack
            string postText = "Build Completed";

            SlackMessage message = new SlackMessage
            {
                text = postText
            };


            //Convert serializable object to JSON
            string json = JsonConvert.SerializeObject(message, Newtonsoft.Json.Formatting.Indented);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(slackUrl);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            //Send to Slack
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            //Error checking if Slack sends back a 404 or 400
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

        }
Tree55Topz
  • 1,102
  • 4
  • 20
  • 51

0 Answers0