public async Task <Boolean> DeleteUcwaApps(HttpClient httpClient, OAuthTokenRoot authToken, TelemetryClient tc)
        {
            try
            {
                string ucwaApplicationRootUrl = DI._config.GetSection("UCWA:ucwa_applications_host").Value + UCWAConfiguration.ucwaApplication;
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.access_token);
                var httpResponseMessage = await httpClient.DeleteAsync(ucwaApplicationRootUrl);

                string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                if (result == String.Empty)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                tc.TrackEvent("DeleteUcwaApps-Exception");
                Console.WriteLine("Failed to delete application on the UCWA server.");
                throw new CustomException("Error occured in " + MethodBase.GetCurrentMethod().Name + ":" + ex.Message +
                                          " TargetSite:" + ex.TargetSite + " StackTrace: " + ex.StackTrace);
            }
        }
 // Constructor dependency injection
 public UCWASetTyping(HttpClient httpClient, OAuthTokenRoot authToken, String setTypingUrl, TelemetryClient tc)
 {
     UCWAConfiguration._httpClient = httpClient;
     _setTypingUrl         = setTypingUrl;
     _authToken            = authToken;
     UCWAConfiguration._tc = tc;
 }
Beispiel #3
0
 // Constructor dependency injection
 public UCWAReceiveMessage(HttpClient httpClient, TelemetryClient tc, OAuthTokenRoot authToken, bool isNextMsg = false)
 {
     UCWAConfiguration._httpClient = httpClient;
     UCWAConfiguration._tc         = tc;
     _authToken = authToken;
     _isNextMsg = isNextMsg;
 }
        public async Task <Boolean> MakeMeAvailable(HttpClient httpClient, OAuthTokenRoot authToken, String ucwaMakeMeAvailableRootUrl,
                                                    BotAttributes botAttributes, TelemetryClient tc)
        {
            try
            {
                string makeMeAvailableResults = string.Empty;

                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var makeMeAvailablePostData = JsonConvert.SerializeObject(botAttributes);
                //Successfull response is Http 204 No content
                var httpResponseMessage = await
                                          httpClient.PostAsync(ucwaMakeMeAvailableRootUrl, new StringContent(makeMeAvailablePostData, Encoding.UTF8,
                                                                                                             "application/json"));

                string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                if (result == String.Empty)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to set the status of the bot as Online");
                tc.TrackTrace("Failed to set the status of the bot as Online");
                tc.TrackException(ex);
                throw new CustomException("Error occured in " + MethodBase.GetCurrentMethod().Name + ":" + ex.Message +
                                          " TargetSite:" + ex.TargetSite + " StackTrace: " + ex.StackTrace);
            }
        }
 // Constructor dependency injection
 public UCWAApplication(HttpClient httpClient, OAuthTokenRoot authToken, string ucwaApplicationsRootUrl,
                        UCWAMyApps ucwaAppsObject, TelemetryClient tc)
 {
     UCWAConfiguration._httpClient = httpClient;
     _ucwaApplicationsRootUrl      = ucwaApplicationsRootUrl;
     _authToken            = authToken;
     _ucwaAppsObject       = ucwaAppsObject;
     UCWAConfiguration._tc = tc;
 }
 // Constructor dependency injection
 public UCWAMakeMeAvailable(HttpClient httpClient, OAuthTokenRoot authToken, String ucwaMakeMeAvailableRootUrl,
                            BotAttributes botAttributes, TelemetryClient tc)
 {
     UCWAConfiguration._httpClient = httpClient;
     _ucwaMakeMeAvailableRootUrl   = ucwaMakeMeAvailableRootUrl;
     _authToken            = authToken;
     _botAttributes        = botAttributes;
     UCWAConfiguration._tc = tc;
 }
 // Constructor dependency injection
 public UCWAReportMyActivity(HttpClient httpClient, OAuthTokenRoot authToken, String ucwaKeepMeOnlineUrl,
                             BotAttributes botAttributes, TelemetryClient tc)
 {
     UCWAConfiguration._httpClient = httpClient;
     _keepMeOnlineUrl      = ucwaKeepMeOnlineUrl;
     _authToken            = authToken;
     _botAttributes        = botAttributes;
     UCWAConfiguration._tc = tc;
 }
Beispiel #8
0
        public static string CreateUcwaApps(HttpClient httpClient, OAuthTokenRoot authToken, string ucwaApplicationsRootUri,
                                            UcwaMyApps ucwaAppsObject, TelemetryClient tc)
        {
            try
            {
                string createUcwaAppsResults = string.Empty;

                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var createUcwaPostData  = JsonConvert.SerializeObject(ucwaAppsObject);
                var httpResponseMessage =
                    httpClient.PostAsync(ucwaApplicationsRootUri, new StringContent(createUcwaPostData, Encoding.UTF8,
                                                                                    "application/json")).Result;
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    tc.TrackTrace("Application on the UCWA server created successfully.");
                    Console.WriteLine("Application on the UCWA server created successfully.");
                    createUcwaAppsResults = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    ApplicationRoot obj = new ApplicationRoot();
                    JsonConvert.PopulateObject(createUcwaAppsResults, obj);
                    if (obj != null)
                    {
                        ConfigData.ucwaApplication = obj._links.self.href;
                        // ConfigData.ucwaApplications += ConfigData.ucwaApplication;
                        ConfigData.ucwaEvents = obj._links.events.href;
                    }
                }
                else
                {
                    tc.TrackTrace("Failed to create application on the UCWA server.");
                    tc.TrackEvent("CreateUcwaApps-Failed");
                    Console.WriteLine("Failed to create application on the UCWA server.");
                }
                return(createUcwaAppsResults);
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                tc.TrackEvent("CreateUcwaApps-Exception");
                Console.WriteLine("Failed to create application on the UCWA server.");
                throw new CustomException("Error occured in " + MethodBase.GetCurrentMethod().Name + ":" + ex.Message +
                                          " TargetSite:" + ex.TargetSite + " StackTrace: " + ex.StackTrace);
            }
        }
Beispiel #9
0
        public async Task <OAuthTokenRoot> GetOAuthToken(HttpClient httpClient, string userName, string password, string domain,
                                                         string lyncOAuthUri, TelemetryClient tc)
        {
            //Console.WriteLine("Write Message called from AppInsightsLogger - ");
            //return Task.FromResult(0);
            try
            {
                OAuthTokenRoot oAuthTokenResult = new OAuthTokenRoot();
                httpClient.DefaultRequestHeaders.Clear();
                var authDic = new Dictionary <string, string>();
                authDic.Add("grant_type", "password");
                authDic.Add("username", domain + "\\" + userName);
                authDic.Add("password", password);
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(lyncOAuthUri,
                                                                                     new FormUrlEncodedContent(authDic));

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    var getOAuthTokenResult = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    // Add reference to Newtonsoft.Json
                    JsonConvert.PopulateObject(getOAuthTokenResult, oAuthTokenResult);
                    tc.TrackTrace("Authentication token for the Skype Id received successfully.");
                    Console.WriteLine("Authentication token for the Skype Id received successfully.");
                }
                else
                {
                    tc.TrackTrace("Failed to receive authentication token for the Skype Id. " + httpResponseMessage.ToString());
                    tc.TrackEvent("GetOAuthToken-Failed");
                    Console.WriteLine("Unable to get the authentication token.");
                }
                // oAuthTokenResult;
                return(oAuthTokenResult);
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                tc.TrackEvent("GetOAuthToken-Exception");
                Console.WriteLine("Failed to acquire authentication token for the Skype Id.");
                throw new CustomException("Error occured in " + MethodBase.GetCurrentMethod().Name + ":" + ex.Message +
                                          " TargetSite:" + ex.TargetSite + " StackTrace: " + ex.StackTrace);
            }
        }
        public async Task SetTyping(HttpClient httpClient, OAuthTokenRoot authToken, String setTypingUrl, TelemetryClient tc)
        {
            try
            {
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Successfull response is Http 204 No content
                var httpResponseMessage = await httpClient.PostAsync(setTypingUrl, new StringContent(string.Empty));

                string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                if (result != String.Empty)
                {
                    tc.TrackTrace("Failed to set the typing status.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to set the typing status.");
                tc.TrackTrace("Failed to set the typing status. More details can be found in the exception.");
                tc.TrackException(ex);
            }
        }
Beispiel #11
0
 public async Task GetMessage(HttpClient httpClient, TelemetryClient tc, OAuthTokenRoot authToken, bool isNextMsg = false)
 {
     await GetIM_Step01_Application(httpClient, tc);
 }
 async public static void GetMessage(HttpClient httpClient, TelemetryClient tc, OAuthTokenRoot authToken, bool IsNextMsg = false)
 {
     GetIM_Step01_Application(httpClient, tc);
 }
        public async Task KeepMeOnline(HttpClient httpClient, OAuthTokenRoot authToken, String ucwaKeepMeOnlineUrl,
                                       TelemetryClient tc)
        {
            try
            {
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Successfull response is Http 204 No content
                var httpResponseMessage = await
                                          httpClient.PostAsync(ucwaKeepMeOnlineUrl, new StringContent(string.Empty, Encoding.UTF8,
                                                                                                      "application/json"));

                string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                if (result != String.Empty)
                {
                    //Trace the response message if reportMyActivity fails. Also send the response message why it failed.
                    tc.TrackTrace("Failed to set the bot status active. " + httpResponseMessage.ToString());
                    //Retry 3 times by calling the method recursively with an interval of 20 seconds
                    if (counter < 3)
                    {
                        //If the status code is 401, get the token again
                        if (httpResponseMessage.ToString().Contains("StatusCode: 401"))
                        {
                            tc.TrackEvent("Retry-401");
                            //Send email reporting this error
                            // Generic GetService< T> method is an extension method. Add namespace Microsoft.Extensions.DependencyInjection
                            var notificationService = DI._serviceProvider.GetService <INotification>();
                            await notificationService.SendMail("Bot Error 401", httpResponseMessage.ToString(), tc);

                            // Get the authentication token from Lync Server.
                            // Generic GetService< T> method is an extension method. Add namespace Microsoft.Extensions.DependencyInjection
                            var lyncAuthenticationService = DI._serviceProvider.GetService <ILyncAuthentication>();
                            UCWAConfiguration.authToken = await lyncAuthenticationService.GetOAuthToken(UCWAConfiguration._httpClient, DI._config.GetSection("Skypebot:user_name").Value,
                                                                                                        DI._config.GetSection("Skypebot:password").Value, DI._config.GetSection("Skypebot:domain").Value, DI._config.GetSection("UCWA:lync_oauth_url").Value, UCWAConfiguration._tc);

                            tc.TrackEvent("BotRecovered-401");
                            // Recursively call itself
                            await KeepMeOnline(httpClient, UCWAConfiguration.authToken, ucwaKeepMeOnlineUrl, tc);
                        }
                        // Address 404 Not found - Added below if statement
                        else if (httpResponseMessage.ToString().Contains("StatusCode: 404"))
                        {
                            tc.TrackEvent("Retry-404");
                            //Delete the exisiting UCWA application. The UCWA application identifier is the GUID (EndpointID),
                            //but to delete the ucwa application, you need the root application url.
                            //The UCWA application url will be of format /ucwa/oauth/v1/applications/103004647364
                            var ucwaApplicationService = DI._serviceProvider.GetService <IUCWAApplication>();
                            await ucwaApplicationService.DeleteUcwaApps(httpClient, UCWAConfiguration.authToken, tc);

                            //Get the Authentication token
                            //LyncAuth.GetOAuthToken(httpClient, ConfigData.userName, ConfigData.password,
                            //    ConfigData.domain, ConfigData.lyncOAuthUri, tc);

                            //Create an application on the UCWA server
                            List <string> Modalities = new List <string>();
                            Modalities.Add("PhoneAudio");
                            Modalities.Add("Messaging");
                            //Set the properties for the applications resource
                            UCWAMyApps ucwaMyAppsObject = new UCWAMyApps()
                            {
                                UserAgent  = "Skypebot",
                                EndpointId = Guid.NewGuid().ToString(),
                                Culture    = "en-US"
                            };
                            //Create an application on the Skype UCWA server and register it.
                            string createUcwaAppsResults;
                            createUcwaAppsResults = await ucwaApplicationService.CreateUcwaApps(UCWAConfiguration._httpClient,
                                                                                                UCWAConfiguration.authToken, DI._config.GetSection("UCWA:ucwa_applications_url").Value, ucwaMyAppsObject, UCWAConfiguration._tc);

                            //Invoke MakeMeAvailable else it will give 409 conflict error i.e. invoking a resource before setting the status "online"
                            //Set IM status as online
                            var manageIMStatusService = DI._serviceProvider.GetService <IManageIMStatus>();
                            await manageIMStatusService.SetIMStatus(UCWAConfiguration._httpClient, UCWAConfiguration._tc);

                            //Start listening to messages
                            var ucwaReceiveMessageService = DI._serviceProvider.GetService <IUCWAReceiveMessage>();
                            await ucwaReceiveMessageService.GetMessage(UCWAConfiguration._httpClient, tc, UCWAConfiguration.authToken, false);

                            Console.WriteLine("Bot recovered. Bot is listening to messages...");
                            tc.TrackEvent("BotRecovered-404");

                            if (counter < 3)
                            {
                                //increment the counter so that it doesn't send infinite emails
                                counter++;
                                //Send email reporting this error
                                // Generic GetService< T> method is an extension method. Add namespace Microsoft.Extensions.DependencyInjection
                                var notificationService = DI._serviceProvider.GetService <INotification>();
                                await notificationService.SendMail("Bot Error 404", httpResponseMessage.ToString(), tc);
                            }
                        }
                        else
                        {
                            Thread.Sleep(20000);
                            counter++;
                            tc.TrackTrace("Retrying to set the bot status active. Attempt # " + counter);
                            tc.TrackEvent("Retry-KeepOnline");
                            // Recursively call itself
                            await KeepMeOnline(httpClient, UCWAConfiguration.authToken, ucwaKeepMeOnlineUrl, tc);
                        }
                    }
                }
                else
                {
                    //set counter back to zero
                    counter = 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to set the bot status active." + ex.Message);
                tc.TrackTrace("Failed to set the bot status active. More details can be found in the exception.");
                tc.TrackException(ex);
            }
        }