Post ServiceNow Incidents for a group to a Microsoft Teams channel using C#.NET

We will be using MS Teams incoming webhook to POST ServiceNow Incidents assigned to a specific group into a MS Teams channel.
 
To make things simpler, we will create a .net core console app.
 
One advantage of a console app is it is very lightweight and you can take advantage of the scheduled task or job to configure the app to run at a specific time of the day.
 
Here are our main steps,
  1. Create console app in C#.
  2. Create necessary classes for messages.
  3. Create class for notification.
Let us get started...
 

Create console app in C# 

  • Start Visual Studio 2019 and Click on Create a new project



  • Pick Console Application that can run on .NET Core using C#


  • Configure your new project. Give it a good name.



  • Pick your target framework. We will pick .net 5.0 for this example

We will start working on our classes. We will create classes for serialization/deserialization logic for the results coming back from ServiceNow API call. The de-serialized object will used for our adaptive card that will eventually be posted to a Microsoft Teams channel. This will all be in our Messages.cs file.
 
We will be using TableAPIs in ServiceNow, specifically incidents for this example. Basic authentication will be connecting to ServiceNow APIs. Please make sure you have an account with enough rights that you can use for this connectivity.
 
We will also create a Notification class with methods to retrieve ServiceNow incidents assigned to a specific group and then push the incidents as adaptive cards to a MS Teams channel. We will have this all in our Notify method which will be called from our entry point method (Main) in program.cs.
 
Please note:
 
I have made the following changes inside the entry point Main method in Program.cs file.
  • Added logic to configure appsettings.json to store our configuration entries.
    • Never store any critical or sensitive information exposed in configuration file. For this example, I have stored the configuration entries, including the bearer token required for ServiceNow authentication. It is best to encrypt and store any sensitive information in env files or use key vault services.
      1. /// <summary>  
      2. /// setupConfiguration  
      3. /// To enable appsettings.json configuration  
      4. /// </summary>  
      5.   
      6. private static void SetupConfiguration()  
      7. {  
      8.   var builder = new ConfigurationBuilder()  
      9.   .AddJsonFile($"appsettings.json"truetrue);  
      10.   
      11.   var config = builder.Build();  
      12.   _config = config;  
      13. }
  • Added logic in our entry point Main method to call into SetupConfiguration() method. Also used Task.Wait() call to wait for our async Notify call to complete execution. Please note that I am also passing in _config object to Notification class to read the configuration object from our Notification class.
    1. private static IConfigurationRoot _config;    
    2. static void Main(string[] args)    
    3. {    
    4.   SetupConfiguration();    
    5. u    
    6.   Console.WriteLine("Hello! Here are the active incidents for our team.");    
    7.   Notification notification = new(_config);    
    8.   Task t = notification.Notify();    
    9.   t.Wait();    
    10. } 
Notification (Notification.cs):
  1. private readonly IConfigurationRoot _config;  
  2. public Notification(IConfigurationRoot config)  
  3. {  
  4.   _config = config;  
  5. }   

Create necessary classes for messages

 
We will add all our classes necessary for our deserialization and adaptive cards inside our Messages.cs file.
 
Messages.cs 
  1. /// <summary>  
  2. /// Teams Message for Adaptive Cards  
  3. /// </summary>  
  4. class TeamsMessage  
  5. {  
  6.   [JsonProperty("type")]  
  7.   public string Type { getset; }  
  8.   
  9.   [JsonProperty("themeColor")]  
  10.   public string ThemeColor { getset; }  
  11.   
  12.   [JsonProperty("summary")]  
  13.   public string Summary { getset; }  
  14.   
  15.   [JsonProperty("sections")]  
  16.   public TeamsMessageSections[] Sections { getset; }  
  17. }  
  18.   
  19. /// <summary>  
  20. /// Teams Message for Adaptive Cards  
  21. /// </summary>  
  22. public class TeamsMessageSections  
  23. {  
  24.   [JsonProperty("activityTitle")]  
  25.   public string ActivityTitle { getset; }  
  26.   
  27.   [JsonProperty("activitySubtitle")]  
  28.   public string ActivitySubtitle { getset; }  
  29.   
  30.   [JsonProperty("activityImage")]  
  31.   public string ActivityImage { getset; }  
  32.   
  33.   [JsonProperty("markdown")]  
  34.   public bool Markdown { getset; }  
  35. }  
  36.   
  37. /// <summary>  
  38. /// ServiceNow Table API Return Object Arrsy  
  39. /// </summary>  
  40. public class ServiceNowReturn  
  41. {  
  42.   [JsonProperty("result")]  
  43.   public ServiceNowReturnMessage[] Result { getset; }  
  44. }  
  45.   
  46. /// <summary>  
  47. /// ServiceNow Table API Return Object for Teams Adaptive Card  
  48. /// </summary>  
  49. public class ServiceNowReturnMessage  
  50. {  
  51.   [JsonProperty("number")]  
  52.   public string Number { getset; }  
  53.   
  54.   [JsonProperty("u_best_contact_email")]  
  55.   public string ContactEmail { getset; }  
  56.   
  57.   [JsonProperty("sys_id")]  
  58.   public string SysID { getset; }  
  59.   
  60.   [JsonProperty("short_description")]  
  61.   public string ShortDescription { getset; }  
  62.   
  63.   [JsonProperty("description")]  
  64.   public string Description { getset; }  
  65. } 
TeamsMessage and TeamsMessagesSections are for our adaptive cards. We will only use a subset of data retrieved from our ServiceNow API call on our card.
ServiceNowReturn and ServiceNowReturnMessage class objects will be used for deserializing results coming from ServiceNow API calls.
 
Notification.cs
 
Notify() : method will makes calls into GetServiceNowIncidents() and PostToTeamsChannel() methods.
  1. /// <summary>  
  2. /// Call to ServiceNow using Table APIs and Post to Teams Channel using Webhooks  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public async Task<bool> Notify()  
  6. {  
  7.   var snowResults = await GetServiceNowIncidents();  
  8.   var posted = await PostToTeamsChannel(snowResults);  
  9.   return posted;  
  10. }
GetServiceNowIncidents(): method will use ServiceNow Table API to retrieve incidents and deserialize the results to our ServiceNowReturn class object. We will use basic authentication for connecting to ServiceNow Table APIs for this example. 
  1. /// <summary>  
  2. /// Get ServiceNow Incidents for a specific Assignment Group Using Table APIs (for Incidents)  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. private async Task<ServiceNowReturn> GetServiceNowIncidents()  
  6. {  
  7.   ServiceNowReturn snowReturn = null;  
  8.   var sNowIncidentsTableAPI = _config["SNowInstance"];  
  9.   using (var client = new HttpClient())  
  10.   {  
  11.     client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", _config["SNowBearerToken"]);  
  12.     var response = await client.GetAsync(sNowIncidentsTableAPI);  
  13.     var contents = await response.Content.ReadAsStringAsync();  
  14.     snowReturn = JsonConvert.DeserializeObject<ServiceNowReturn>(contents);  
  15.   }  
  16.   return snowReturn;  
  17. } 
https://<SNowInstance>.service-now.com/api/now/table/incident?sysparm_query=assignment_group=<assignmentgroup>^stateNOT IN6,7 
 
The entries for ServiceNow API end point are in configuration file Please replace SNowInstance with your ServiceNow instance and assignmentgroup to the workgroup id of the group in ServiceNow. The assignment group id can be retrieved from ServiceNow portal. Please note that we have applied the filters to retrieve only active incidents (stateNOTIN6,7)
 
PostToTeamsChannel(ServiceNowReturn snowResults): method will parse ServiceNow return object array and populate TeamsMessage object required for the adaptive card and then POST into MS Teams channel. 
  1. /// <summary>  
  2. /// Post ServiceNow Incidents as individual Adaptive Cards to a MS Teams Channel using Webhook URL  
  3. /// </summary>  
  4. /// <param name="snowResults"></param>  
  5. /// <returns></returns>  
  6. private async Task<bool> PostToTeamsChannel(ServiceNowReturn snowResults)  
  7. {  
  8.   bool success = false;  
  9.   using (var client = new HttpClient())  
  10.   {  
  11.     foreach (var snowIncident in snowResults.Result)  
  12.     {  
  13.       TeamsMessage teamsMessage = new();  
  14.       teamsMessage.Type = "MessageCard";  
  15.       teamsMessage.ThemeColor = "0076D7";  
  16.       teamsMessage.Summary = snowIncident.Number;  
  17.       TeamsMessageSections sections = new()  
  18.       {  
  19.         ActivityTitle = string.Format("{0} - {1}", snowIncident.Number, snowIncident.ShortDescription),  
  20.         ActivitySubtitle = string.Format("{2} contact email: {1}, [View]({3}{0}) ", snowIncident.SysID, snowIncident.ContactEmail, snowIncident.Description,             _config["SNowIncidentLink"]),  
  21.         ActivityImage = _config["AdaptiveCardImageURL"],  
  22.         Markdown = true  
  23.       };  
  24.       teamsMessage.Sections = new TeamsMessageSections[] { sections };  
  25.   
  26.       var teamsPayload = JsonConvert.SerializeObject(teamsMessage);  
  27.   
  28.       var response = await client.PostAsync(  
  29.       _config["TeamsWebhookURL"],  
  30.       new StringContent(teamsPayload, Encoding.UTF8, "application/json"));  
  31.   
  32.      var contents = await response.Content.ReadAsStringAsync();  
  33.   
  34.      if (response.IsSuccessStatusCode)  
  35.      {  
  36.        success = true;  
  37.      }  
  38.    }  
  39.  }  
  40.  return success;  
  41. } 
If you have not configured an incoming webhook in Microsoft Teams Channel, please use the instructions below to configure one.
 

Configure an incoming webhook in Microsoft Teams Channel

 
Right the channel of interest in MS Teams and choose Connectors.
 
 
 
Configure Incoming Webhook
 
 
 
Provide a name for the Webhook and if you prefer, upload a custom image and then click Create. Please copy the Webhook URL and update appsettings.json TeamsWebhookURL key value to this URL.
 
Please update appsettings.json key values. Please note, SNowIncidentLink value is provided as a link in the card that deep links into ServiceNow incident if user prefers to get a detailed view of the incident.
 
"SNowInstance": "https://<SNowInstance>.service-now.com/api/now/table/incident?sysparm_query=assignment_group=<assignmentgroup>^stateNOT IN6,7",
"SNowIncidentLink": "https://<SNowInstance>.service-now.com/nav_to.do?uri=incident.do?sys_id=",
"SNowBearerToken": "<Bearer Token>",
"TeamsWebhookURL": "<TeamsIncomingWebhookUrl>",
"AdaptiveCardImageURL": "<link to a pretty image for displaying in adaptive card>"
 
That is it. If you have the configuration file updated with relevant values for your ServiceNow instance, Bearer token, Teams webhook, a good image link to show up in the card, you can go ahead with the build and run process. You should see the cards getting posted to the channel, if you have active incidents for your group in ServiceNow.
 
Here's a sample card posted to my teams channel. Please note, I have wiped out some entries, just so you don't get to see the incident descriptions :). 
 
 
 
That is it. Happy Coding!


Similar Articles