コード例 #1
0
        private async Task <TimeRegistrationModel> TimeRegistrationCompleted(IBotContext context, TimeRegistrationModel model)
        {
            var message = "Booking your hours in Exact, just a sec...";
            await context.PostAsync(message);

            ExactOnlineConnector connector = ExactOnlineHelper.GetConnector();

            TimeRegistrationConnector timeConnector = new TimeRegistrationConnector();

            Guid projectId  = String.IsNullOrEmpty(model.Project) || model.Project == "none" ? Guid.Empty : new Guid(model.Project);
            Guid customerId = String.IsNullOrEmpty(model.Customer) ? Guid.Empty : new Guid(model.Customer);
            Guid hourTypeId = String.IsNullOrEmpty(model.HourType) ? Guid.Empty : new Guid(model.HourType);

            try
            {
                // the user will have booked time for either this week or for a specific date
                if (!model.ThisWeek)
                {
                    timeConnector.BookHours(connector.EmployeeId, customerId, hourTypeId, projectId, model.Date, model.Amount, connector);
                }
                else
                {
                    // if the hours were booked for the entire will, there will be 5 numbers in the string that need to be split
                    // out and entered for each day of the week individually
                    int      dayOfWeek  = DateTimeUtils.GetISODayOfWeek(DateTime.Now);
                    DateTime currentDay = DateTime.Now.AddDays((dayOfWeek - 1) * -1);

                    string[] hours = model.AmountPerDay.Trim().Split(' ');

                    for (int i = 0; i < 5; i++)
                    {
                        double amount = Double.Parse(hours[i]);

                        if (amount > 0)
                        {
                            timeConnector.BookHours(connector.EmployeeId, customerId, hourTypeId, projectId, currentDay, amount, connector);
                        }

                        currentDay = currentDay.AddDays(1);
                    }
                }
            }
            catch (RequestFailedException ex)
            {
                await context.PostAsync($"Hmm, that didn't work. The request failed, it returned the following:");

                await context.PostAsync($"\"{ ex.Message}\"");

                await context.PostAsync($"Sorry about that. Please try again or notify my maker.");

                return(null);
            }

            await context.PostAsync("All set! Anything else I can do for you?");

            return(model);
        }
コード例 #2
0
        private static async Task CompleteForm(IBotContext context, IAwaitable <RootForm> result)
        {
            try
            {
                var completed = await result;

                await context.PostAsync($"Enjoy {completed.Destination}!");
            }
            catch (FormCanceledException <RootForm> ex)
            {
                await context.PostAsync($"Exception: {ex.Message}");
            }
        }
コード例 #3
0
 private static async Task ShowRefunds(IBotContext context, List <Refund> refunds)
 {
     if (refunds.Count == 0)
     {
         await context.PostAsync("You don't have any pending refund");
     }
     else
     {
         var message = context.MakeMessage();
         var user    = context.UserData.GetValue <User>("user");
         message.AddRefundCard(user.Name, refunds);
         await context.PostAsync(message);
     }
 }
コード例 #4
0
 private static async Task ShowAppointments(IBotContext context, List <Appointment> appointments)
 {
     if (appointments.Count == 0)
     {
         await context.PostAsync("You don't have any pending appointment");
     }
     else
     {
         var usuario = context.UserData.GetValue <User>("user");
         var message = context.MakeMessage();
         message.AddAppointmentsCard(usuario.Name, appointments);
         await context.PostAsync(message);
     }
 }
コード例 #5
0
        public async Task RemoveReminder(IBotContext context)
        {
            string username = context.Activity.From.Name;

            if (_store.GetReminder(username) == null)
            {
                await context.PostAsync("Were you actually getting reminders? I couldn't find an entry with your name.");
            }
            else
            {
                _store.DeleteReminder(username);

                await context.PostAsync("Done. Just let me know if you want this to be enabled again.");
            }
        }
コード例 #6
0
        private static async Task OnProfileComplete(IBotContext context, IAwaitable <PathwaysProfile> profileDialog)
        {
            var profile  = await profileDialog;
            var response = await profile.PostAsJsonToApi("ProfileCompleteApi");

            await context.PostAsync("Logic App returned: " + response);
        }
コード例 #7
0
        public static async Task <string> GetADALAccessToken(this IBotContext context, string resource)
        {
            AuthenticationSettings authenticationSettings = AuthenticationSettings.GetFromAppSettings();
            AuthenticationResult   authenticationResult;

            string authenticationKey = AuthenticationConstants.AuthDialogId_AzureAD + '_' + AuthenticationConstants.AuthResultKey;

            if (context.UserData.TryGetValue(authenticationKey, out authenticationResult))
            {
                try
                {
                    var tokenCache = TokenCacheFactory.SetADALTokenCache(authenticationResult.TokenCache);

                    var result = await AzureADHelper.GetToken(authenticationResult.UserUniqueId, authenticationSettings, resource);

                    authenticationResult.AccessToken       = result.AccessToken;
                    authenticationResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                    authenticationResult.TokenCache        = tokenCache.Serialize();
                    context.StoreAuthResult(authenticationResult);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout(authenticationSettings);

                    return(null);
                }
                return(authenticationResult.AccessToken);
            }
            return(null);
        }
コード例 #8
0
 public static async Task<string> GetAccessToken(this IBotContext context, string resourceId)
 {
     AuthResult authResult;
     if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
     {
         try
         {
             InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
             var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, resourceId);
             authResult.AccessToken = result.AccessToken;
             authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
             authResult.TokenCache = tokenCache.Serialize();
             context.StoreAuthResult(authResult);
         }
         catch (Exception ex)
         {
             Trace.TraceError("Failed to renew token: " + ex.Message);
             await context.PostAsync("Your credentials expired and could not be renewed automatically!");
             await context.Logout();
             return null;
         }
         return authResult.AccessToken;
     }
     return null;
 }
コード例 #9
0
        public static async Task <string> GetSharePointAccessToken(this IBotContext context, string resource)
        {
            SharePointSettings   sharepointSettings = SharePointSettings.GetFromAppSettings();
            AuthenticationResult authenticationResult;

            if (context.UserData.TryGetValue(AuthenticationConstants.AuthResultKey, out authenticationResult))
            {
                try
                {
                    // here needs to come an implementation that automatically renews the refresh token we get from SharePoint
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout(sharepointSettings);

                    return(null);
                }

                return(authenticationResult.AccessToken);
            }

            return(null);
        }
コード例 #10
0
        public async Task SetReminder(IBotContext context, int contractHours, ConversationReference conversation)
        {
            string username = context.Activity.From.Name;

            if (_store.GetReminder(username) != null)
            {
                await context.PostAsync("I tried to set-up a reminder for you, but it was already there!");
            }
            else
            {
                TokenCache         tokenCache = TokenCacheFactory.GetTokenCache();
                HoursReminderModel model      = new HoursReminderModel(username, conversation, contractHours, tokenCache);
                _store.AddReminder(model);

                await context.PostAsync("Sure thing! I will remind you about booking your hours at the end of every week.");
            }
        }
コード例 #11
0
 public static async Task Logout(this IBotContext context)
 {
     context.UserData.RemoveValue(ContextConstants.AuthResultKey);
     context.UserData.RemoveValue(ContextConstants.MagicNumberKey);
     context.UserData.RemoveValue(ContextConstants.MagicNumberValidated);
     string signoutURl = "https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=" + System.Net.WebUtility.UrlEncode(AuthSettings.RedirectUrl);
     await context.PostAsync($"In order to finish the sign out, please click at this [link]({signoutURl}).");
 }
コード例 #12
0
 public static async Task Logout(this IBotContext context, AuthenticationSettings authenticationSettings)
 {
     context.UserData.RemoveValue(AuthenticationConstants.AuthDialogId_ExactOnline + '_' + AuthenticationConstants.AuthResultKey);
     context.UserData.RemoveValue(AuthenticationConstants.AuthDialogId_ExactOnline + '_' + AuthenticationConstants.MagicNumberKey);
     context.UserData.RemoveValue(AuthenticationConstants.AuthDialogId_ExactOnline + '_' + AuthenticationConstants.MagicNumberValidated);
     string signoutURl = "https://start.exactonline.nl/api/oauth2/logout?post_logout_redirect_uri=" + System.Net.WebUtility.UrlEncode(authenticationSettings.RedirectUrl);
     await context.PostAsync($"In order to finish the sign out, please click at this [link]({signoutURl}).");
 }
コード例 #13
0
        public static async Task <string> GetAccessToken(this IBotContext context, string resourceId)
        {
            AuthResult authResult;

            if (context.Activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
            {
                string token = null;
                if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
                {
                    //we have credential
                }
                else
                {
                    token = GetCortanaAccessToken(context);
                    var jwt = new JwtSecurityToken(token);
                    if (authResult == null)
                    {
                        authResult = new AuthResult();
                    }

                    authResult.AccessToken = token;
                    long tick = long.MinValue;
                    long.TryParse(jwt.Payload.Claims.Where(c => c.Type.Equals("exp", StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault()?.Value, out tick);
                    authResult.ExpiresOnUtcTicks = tick;
                    InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(Encoding.ASCII.GetBytes(token));
                    authResult.TokenCache = tokenCache.Serialize();
                    context.StoreAuthResult(authResult);
                }
                return(authResult.AccessToken);
            }
            else
            {
                if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
                {
                    try
                    {
                        InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, resourceId);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        context.StoreAuthResult(authResult);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Failed to renew token: " + ex.Message);
                        await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                        await context.Logout();

                        return(null);
                    }
                    return(authResult.AccessToken);
                }
                return(null);
            }
        }
コード例 #14
0
ファイル: LuisDialog.cs プロジェクト: Guztrap/BOTASPNET
 private static async Task EmitTraceInfo(IBotContext context, LuisResult luisResult, ILuisOptions luisOptions, ILuisModel luisModel)
 {
     var luisTraceInfo = new LuisTraceInfo
     {
         LuisResult  = luisResult,
         LuisOptions = luisOptions,
         LuisModel   = RemoveSensitiveData(luisModel)
     };
     var activity = Activity.CreateTraceActivityReply(context.Activity as Activity, LuisTraceName, LuisTraceType, luisTraceInfo, LuisTraceLabel) as IMessageActivity;
     await context.PostAsync(activity);
 }
コード例 #15
0
ファイル: ContextExtensions.cs プロジェクト: harshini1/Totry
        public static async Task <string> GetAlias(this IBotContext context)
        {
            AuthResult authResult;
            string     validated = null;

            if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult) &&
                context.UserData.TryGetValue(ContextConstants.MagicNumberValidated, out validated) &&
                validated == "true")
            {
                try
                {
                    if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, AuthSettings.Scopes);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        authResult.Alias             = result.Alias;
                        context.StoreAuthResult(authResult);
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new NotImplementedException();
                    }
                    else if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache);
                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();
                        authResult.Alias             = result.Alias;
                        context.StoreAuthResult(authResult);
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout();

                    return(null);
                }
                return(authResult.Alias.Split('@')[0]);
            }

            return(null);
        }
コード例 #16
0
        private async Task PostNotStartedReportReply(IBotContext context, Activity activity)
        {
            Activity reply = activity.CreateReply("You have not started a report yet");

            reply.SuggestedActions = new SuggestedActions
            {
                Actions = new List <CardAction> {
                    new CardAction("imBack", "Start working", null, "in")
                }
            };

            await context.PostAsync(reply);
        }
コード例 #17
0
        private static async Task <LeaveRequestModel> LeaveRequestDialogCompleted(IBotContext context, LeaveRequestModel model)
        {
            LeaveRequest request = new LeaveRequest()
            {
                StartTime = model.StartTime,
                EndTime   = model.EndTime,
                Title     = model.Title
            };

            string token = await context.GetADALAccessToken(_resourceUriSharePoint);

            await SharePointConnector.CreateLeaveRequest(request, token, SharePointSettings.GetFromEnvironment());

            var message = "I've saved your leave request in SharePoint! An approval request will be sent out automatically. Enjoy!";
            await context.PostAsync(message);

            return(model);
        }
コード例 #18
0
        public static async Task <string> GetAccessToken(this IBotContext context, string[] scopes)
        {
            AuthResult authResult;

            if (context.UserData.TryGetValue(ContextConstants.AuthResultKey, out authResult))
            {
                try
                {
                    if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
                    {
                        InMemoryTokenCacheMSAL tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);

                        var result = await AzureActiveDirectoryHelper.GetToken(authResult.UserUniqueId, tokenCache, scopes);

                        authResult.AccessToken       = result.AccessToken;
                        authResult.ExpiresOnUtcTicks = result.ExpiresOnUtcTicks;
                        authResult.TokenCache        = tokenCache.Serialize();

                        context.StoreAuthResult(authResult);
                    }
                    else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new NotImplementedException();
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);

                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                    await context.Logout();

                    return(null);
                }


                return(authResult.AccessToken);
            }

            return(null);
        }
コード例 #19
0
        private static async Task <SickLeaveModel> SickLeaveDialogCompleted(IBotContext context, SickLeaveModel model)
        {
            LeaveRequest request = new LeaveRequest()
            {
                StartTime = model.StartTime,
                EndTime   = model.EndTime,
                Title     = $"Leave Request"
            };

            string token = await context.GetADALAccessToken(_resourceUriSharePoint);

            await SharePointConnector.CreateLeaveRequest(request, token, SharePointSettings.GetFromEnvironment());

            var message = "Done! I've saved your sick leave in SharePoint.";

            if (model.StillSick)
            {
                message += " Get well soon!";
            }

            await context.PostAsync(message);

            return(model);
        }
コード例 #20
0
ファイル: LUISDialog.cs プロジェクト: dward330/CharlotteCafe
        private async static Task <IDialog <string> > AfterNewOrder(IBotContext context, IAwaitable <object> item)
        {
            await context.PostAsync("Your order is received! Pay for it at the cafe counter");

            return(null);
        }