Thursday, March 14, 2019

Office 365 – Teams - Useful functions

Office 365 – Teams

·       Get teams

·       Get channels

·       Get channel email

 

using Microsoft.IdentityModel.Clients.ActiveDirectory;

using System;

using System.Linq;

using System.Collections.Generic;

using System.Threading.Tasks;

using System.Threading;

using Newtonsoft.Json;

using System.Text;

using System.Net;

using System.IO;

using Newtonsoft.Json.Serialization;

 

namespace Office365.Planner.Extension

{

    public class MyTeams

    {

        public static readonly JsonSerializerSettings jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

        public static string TeamsJoinedTeam = "https://graph.microsoft.com/v1.0/me/joinedTeams";

        public static string TeamsChannels = "https://graph.microsoft.com/v1.0/teams/{0}/channels";

        public static string TeamsChannelInfo = "https://graph.microsoft.com/beta/teams/{0}/channels/{1}";

 

        /// <summary>

        /// Get Teams

        /// </summary>

        /// <returns></returns>

        public async static Task<List<TeamData>> GetTeamsUsingWebClient()

        {

            List<TeamData> teamData = new List<TeamData>();

            StringBuilder logInfo = new StringBuilder();

            try

            {

                string accessToken = GetAccessToken();

                if (accessToken != null)

                {

                    string response = await GetResponse(accessToken, TeamsJoinedTeam);

                    if (response != null)

                    {

                        ResultList<Team> teams = JsonConvert.DeserializeObject<ResultList<Team>>(response, MyTeams.jsonSettings);

                        foreach (Team team in teams.value)

                        {

                            TeamData td = new TeamData(team.id, team.displayName);

                            List<Channel> channel = await GetChannelsUsingWebClient(team.id, accessToken);

 

                            foreach (Channel ch in channel)

                            {

                                Channel tempChannel = await GetChannelInfoUsingWebClient(team.id, ch.id, accessToken);

 

                                logInfo.AppendLine(string.Format("Team Name:{0} <br> Channel DisplayName:{1} <br> Email:{2} <br>", team.displayName, tempChannel.displayName, tempChannel.email));

 

                                td.Channels.Add(tempChannel);

                            }

 

                            teamData.Add(td);

                        }

                    }

                    else

                        throw new Exception("HttpResponse is null");

 

                }

                else

                    throw new Exception("AccessToken is null");

            }

            catch (Exception)

            {

            }

            finally

            {

            }

            return teamData;

        }

 

        /// <summary>

        /// Get Channel based on team id

        /// </summary>

        /// <param name="teamId"></param>

        /// <param name="accessToken"></param>

        /// <returns></returns>

        public async static Task<List<Channel>> GetChannelsUsingWebClient(string teamId, string accessToken)

        {

            string endpointUrl = string.Format(TeamsChannels, teamId);

            string response = await GetResponse(accessToken, endpointUrl);

            if (response != null)

            {

                return JsonConvert.DeserializeObject<ResultList<Channel>>(response, MyTeams.jsonSettings).value.ToList();

            }

            else

                throw new Exception("HttpResponse is null");

 

        }

 

        /// <summary>

        /// Get Channel Info based on team id and channel id

        /// </summary>

        /// <param name="teamId"></param>

        /// <param name="channelId"></param>

        /// <param name="accessToken"></param>

        /// <returns></returns>

        public async static Task<Channel> GetChannelInfoUsingWebClient(string teamId, string channelId, string accessToken)

        {

            string endpointUrl = string.Format(TeamsChannelInfo, teamId, channelId);

            string response = await GetResponse(accessToken, endpointUrl);

            if (response != null)

            {

                Channel channelInfo = JsonConvert.DeserializeObject<Channel>(response);

                if (channelInfo != null)

                {

                    return channelInfo;

                }

            }

            else

                throw new Exception("HttpResponse is null");

 

            return null;

        }

 

        /// <summary>

        /// Get WebClient Response

        /// </summary>

        /// <param name="accessToken"></param>

        /// <param name="url"></param>

        /// <returns></returns>

        public async static Task<string> GetResponse(string accessToken, string url)

        {

            string response = null;

            try

            {

                using (WebClient wc = new WebClient())

                {

                    wc.Headers[HttpRequestHeader.ContentType] = "application/json";

                    wc.Headers[HttpRequestHeader.Authorization] = "Bearer " + accessToken;

 

                    response = await Task.Run(() => wc.DownloadString(url));

 

                    //Fallback mechanism

                    if (string.IsNullOrEmpty(response))

                    {

                        Thread.Sleep(30000);

                        response = wc.DownloadString(url);

                    }

                }

            }

            catch (WebException)

            {

            }

            return response;

        }

 

        /// <summary>

        /// Get WebClient Exception Response String

        /// </summary>

        /// <param name="ex"></param>

        /// <returns></returns>

        private static string GetWebExceptionResponseString(WebException ex)

        {

            HttpWebResponse response = ex.Response as HttpWebResponse;

            using (Stream stream = response.GetResponseStream())

            {

                StreamReader reader = new StreamReader(stream, Encoding.UTF8);

                return reader.ReadToEnd();

            }

        }

 

        /// <summary>

        /// JSON SerializeObject

        /// </summary>

        /// <param name="payLoad"></param>

        /// <returns></returns>

        public static string ToJson(string payLoad)

        {

            string jsonToReturn = JsonConvert.SerializeObject(payLoad,

                              Newtonsoft.Json.Formatting.None,

                              new JsonSerializerSettings

                              {

                                  NullValueHandling = NullValueHandling.Ignore

 

                              });

            return jsonToReturn;

        }

 

        /// <summary>

        ///  Get AAD Access Token

        /// </summary>

        /// <returns></returns>

        public static string GetAccessToken()

        {

            string AppId = "";

            string TenantId = "";

            string GraphResourceUrl = "https://graph.microsoft.com";

            string AuthorityUrl = "https://login.microsoftonline.com/" + TenantId;

            string RedirectUri = "http://localhost:12345/";

 

            try

            {

                AuthenticationContext authContext = new AuthenticationContext(AuthorityUrl, true);

                AuthenticationResult authResult = authContext.AcquireTokenAsync(GraphResourceUrl, AppId, new Uri(RedirectUri), new PlatformParameters(PromptBehavior.Auto)).Result;

                return authResult.AccessToken;

 

            }

            catch (Exception ex)

            {

            }

            return null;

        }

 

 

    }

 

    public class TeamData

    {

        public string TeamId { get; set; }

        public string TeamTitle { get; set; }

 

        public List<Channel> Channels { get; set; }

        public TeamData()

        { }

 

        public TeamData(string id, string title)

        {

            TeamId = id;

            TeamTitle = title;

            Channels = new List<Channel>();

        }

    }

 

    public class Channel

    {

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]

        public string id { get; set; }

        public string displayName { get; set; }

        public string description { get; set; }

        public string email { get; set; }

    }

 

    public class Team

    {

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]

        public string id { get; set; }

 

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]

        public string displayName { get; set; }

    }

 

    public class ResultList<T>

    {

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]

        public T[] value { get; set; }

    }

}