Пример #1
0
        /// <summary>
        /// Sets the current vsts profile.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <param name="profile">The profile.</param>
        public static void SetProfile(this IBotDataBag dataBag, VstsProfile profile)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            profile.ThrowIfNull(nameof(profile));

            dataBag.SetValue(Profile, profile);
        }
Пример #2
0
        /// <summary>
        /// Sets the profile.
        /// </summary>
        /// <param name="dataBag">the botdats.</param>
        /// <param name="profiles">the profile.</param>
        public static void SetProfiles(this IBotDataBag dataBag, IList <VstsProfile> profiles)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            profiles.ThrowIfNull(nameof(profiles));

            dataBag.SetValue(Profiles, profiles);
        }
Пример #3
0
        /// <summary>
        /// Sets the current account.
        /// </summary>
        /// <param name="dataBag">The <see cref="IBotDataBag"/>.</param>
        /// <param name="account">the account.</param>
        public static void SetAccount(this IBotDataBag dataBag, string account)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            account.ThrowIfNullOrWhiteSpace(nameof(account));

            dataBag.SetValue(Account, account);
        }
Пример #4
0
        private static string GetContextData(IBotDataBag data, string key)
        {
            string value;

            data.TryGetValue(key, out value);
            return((value != null) ? key + ": " + value : "");
        }
Пример #5
0
 private void CheckNull(string name, IBotDataBag value)
 {
     if (value == null)
     {
         throw new InvalidOperationException($"{name} cannot be null! probably forgot to call LoadAsync() first!");
     }
 }
Пример #6
0
        /// <summary>
        /// Sets the pin.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <param name="pin">The pin.</param>
        public static void SetPin(this IBotDataBag dataBag, string pin)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            pin.ThrowIfNullOrWhiteSpace(nameof(pin));

            dataBag.SetValue(Pin, pin);
        }
Пример #7
0
        /// <summary>
        /// Sets the current team project.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <param name="teamProject">The team project.</param>
        public static void SetTeamProject(this IBotDataBag dataBag, string teamProject)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            teamProject.ThrowIfNullOrWhiteSpace(nameof(teamProject));

            dataBag.SetValue(TeamProject, teamProject);
        }
Пример #8
0
        private bool UserIdentified(IDialogContext context)
        {
            IBotDataBag botstate = context.PrivateConversationData;
            bool        flag     = false;

            botstate.TryGetValue <bool>("ProfileComplete", out flag);
            return(flag);
        }
Пример #9
0
 public static void Replace(this IBotDataBag botBag, string key, object val)
 {
     if (botBag.ContainsKey(key))
     {
         botBag.RemoveValue(key);
     }
     botBag.SetValue(key, val);
 }
Пример #10
0
        private static T GetData <T>(this IBotDataBag dataBag, string key)
        {
            if (dataBag.TryGetValue(key, out T value))
            {
                return(value);
            }

            return(default(T));
        }
Пример #11
0
        public static void StoreEntityReference(this IBotDataBag botDataBag, IEntity entity, string key = "LastEntityReference")
        {
            var serializerSetting = new JsonSerializerSettings()
            {
                ContractResolver = new InterfaceContractResolver <IEntityReference>()
            };

            botDataBag.SetValue(key, JsonConvert.SerializeObject(entity, serializerSetting));
        }
Пример #12
0
        public async Task LoadAsync(CancellationToken cancellationToken)
        {
            var conversationTask        = LoadData(BotStoreType.BotConversationData, cancellationToken);
            var privateConversationTask = LoadData(BotStoreType.BotPrivateConversationData, cancellationToken);
            var userTask = LoadData(BotStoreType.BotUserData, cancellationToken);

            this.conversationData        = await conversationTask;
            this.privateConversationData = await privateConversationTask;
            this.userData = await userTask;
        }
Пример #13
0
        public async Task LoadAsync()
        {
            var conversationTask          = LoadData(BotStoreType.BotConversationData);
            var perUserInConversationTask = LoadData(BotStoreType.BotPerUserInConversationData);
            var userTask = LoadData(BotStoreType.BotUserData);

            this.conversationData          = await conversationTask;
            this.perUserInConversationData = await perUserInConversationTask;
            this.userData = await userTask;
        }
Пример #14
0
 public UserTokenCache(IBotDataBag userData)
 {
     _userData    = userData;
     BeforeAccess = args =>
     {
         if (userData.TryGetValue(KEY, out byte[] data))
         {
             this.Deserialize(data);
             this.HasStateChanged = false;
         }
     };
Пример #15
0
        /// <summary>
        /// Gets the value associated with the specified key.
        /// </summary>
        /// <typeparam name="T">The type of the value to get.</typeparam>
        /// <param name="bag">The bot data bag.</param>
        /// <param name="key">The key of the value to get or set.</param>
        /// <returns>The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException.</returns>
        public static T Get <T>(this IBotDataBag bag, string key)
        {
            T value;

            if (!bag.TryGetValue(key, out value))
            {
                throw new KeyNotFoundException(key);
            }

            return(value);
        }
Пример #16
0
        /// <summary>
        /// Gets the value associated with the specified key or a default value if not found.
        /// </summary>
        /// <typeparam name="T">The type of the value to get.</typeparam>
        /// <param name="bag">The bot data bag.</param>
        /// <param name="key">The key of the value to get or set.</param>
        /// <param name="defaultValue">The value to return if the key is not present</param>
        /// <returns>The value associated with the specified key. If the specified key is not found, <paramref name="defaultValue"/>
        /// is returned </returns>
        public static T GetValueOrDefault <T>(this IBotDataBag bag, string key, T defaultValue = default(T))
        {
            T value;

            if (!bag.TryGetValue(key, out value))
            {
                value = defaultValue;
            }

            return(value);
        }
        /// <summary>
        /// Retrieves, initializes and manipulates an IBotDataBag value.
        /// </summary>
        /// <typeparam name="T">The generic type of the value to be retrieved or initialized. Must allow new().</typeparam>
        /// <param name="botDataBag"> UserData, ConversationData or PrivateConversationData.</param>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="updateAction">A lamba Action<T> to manipulate the retrieve or new value to save.</param>
        public static void UpdateValue <T>(this IBotDataBag botDataBag, string key, Action <T> updateAction) where T : new()
        {
            T value = default(T);

            if (!botDataBag.TryGetValue(key, out value))
            {
                value = new T();
            }

            updateAction(value);
            botDataBag.SetValue(key, value);
        }
Пример #18
0
        public BotDataBagStream(IBotDataBag bag, string key)
        {
            SetField.NotNull(out this.bag, nameof(bag), bag);
            SetField.NotNull(out this.key, nameof(key), key);

            byte[] blob;
            if (this.bag.TryGetValue(key, out blob))
            {
                this.Write(blob, 0, blob.Length);
                this.Position = 0;
            }
        }
Пример #19
0
        void IDialogContextStore.Save(IDialogContext context, IBotDataBag bag, string key)
        {
            byte[] blobNew;
            using (var streamNew = new MemoryStream())
                using (var gzipNew = new GZipStream(streamNew, CompressionMode.Compress))
                {
                    formatter.Serialize(gzipNew, context);
                    gzipNew.Close();
                    blobNew = streamNew.ToArray();
                }

            bag.SetValue(key, blobNew);
        }
Пример #20
0
 public bool TryLoad(IBotDataBag bag, string key, out IDialogContext context)
 {
     try
     {
         return(this.store.TryLoad(bag, key, out context));
     }
     catch (Exception)
     {
         // exception in loading the serialized context data
         context = null;
         return(false);
     }
 }
Пример #21
0
        private bool IsConnected(IBotDataBag dataBag)
        {
            if (!dataBag.TryGetValue("userData", out UserData data))
            {
                return(false);
            }

            var profile = data.User;

            if (profile != null && profile.Token != null)
            {
                return(true);
            }

            return(false);
        }
            public static int Increment(IBotDataBag bag, int start)
            {
                const string Key = "key";
                int          value;

                if (bag.TryGetValue(Key, out value))
                {
                    value = value + 1;
                }
                else
                {
                    value = start;
                }

                bag.SetValue(Key, value);

                return(value);
            }
Пример #23
0
        bool IDialogContextStore.TryLoad(IBotDataBag bag, string key, out IDialogContext context)
        {
            byte[] blobOld;
            bool   found = bag.TryGetValue(key, out blobOld);

            if (found)
            {
                using (var streamOld = new MemoryStream(blobOld))
                    using (var gzipOld = new GZipStream(streamOld, CompressionMode.Decompress))
                    {
                        context = (IDialogContext)this.formatter.Deserialize(gzipOld);
                        return(true);
                    }
            }

            context = null;
            return(false);
        }
Пример #24
0
        protected async Task <User> GetValidatedProfile(IBotDataBag dataBag)
        {
            if (!dataBag.TryGetValue("userData", out UserData data))
            {
                return(null);
            }

            var profile = data.User;

            if (profile != null && profile.Token.ExpiresOn.AddMinutes(-5) <= DateTime.UtcNow)
            {
                profile.Token = await this._authenticationService.GetToken(profile.Token);

                dataBag.SetValue("userData", data);
            }

            return(profile);
        }
Пример #25
0
        public async static Task <IMessageActivity> PostNewQuestion(IBotDataBag conversationData, IMessageActivity messageActivity)
        {
            string conversationId = messageActivity.Conversation.Id;

            byte level = conversationData.GetValueOrDefault <byte>(KEY_LEVEL);

            Trace.TraceInformation($"PostNewQuestion: conversation: {conversationId}; level: {level}");

            QuestionItem newQuestion = await new QuestionDataSql().GetRandomQuestion(conversationId, (QuestionComplexity)level);

            Trace.TraceInformation($"PostNewQuestion: {newQuestion?.Id}, {newQuestion?.Question}, {newQuestion?.Answer}");

            if (newQuestion != null)
            {
                newQuestion.InitUrls("https://db.chgk.info/images/db/");

                conversationData.SetValue(KEY, newQuestion);

                messageActivity.Id = newQuestion.Id.ToString();

                CardAction answerAction = new CardAction()
                {
                    Title = "Answer",
                    Type  = "imBack",
                    Value = "answer"
                };

                messageActivity.Text = $"**Question:**<br/>{newQuestion.Question}<br/><br/>" +
                                       $"**Author:** {newQuestion.Authors ?? "Unknkown"}<br/>" +
                                       $"**Tour:** {newQuestion.TournamentTitle ?? "Unknkown"}";

                messageActivity.Attachments      = newQuestion.QuestionImageUrls.Select(ToAttachement).ToList();
                messageActivity.SuggestedActions = new SuggestedActions
                {
                    Actions = new List <CardAction> {
                        answerAction
                    }
                };

                return(messageActivity);
            }

            return(null);
        }
Пример #26
0
        /// <summary>
        /// Get the current profile.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <param name="authenticationService"><see cref="IAuthenticationService"/> object.</param>
        /// <returns>A VstsProfile.</returns>
        public static VstsProfile GetProfile(this IBotDataBag dataBag, IAuthenticationService authenticationService)
        {
            dataBag.ThrowIfNull(nameof(dataBag));
            authenticationService.ThrowIfNull(nameof(authenticationService));

            if (!dataBag.TryGetValue(Profile, out VstsProfile profile))
            {
                return(null);
            }

            if (profile.Token.ExpiresOn.AddMinutes(-5) > DateTime.UtcNow)
            {
                return(profile);
            }

            profile.Token = authenticationService.GetToken(profile.Token).Result;
            dataBag.SetProfile(profile);

            return(profile);
        }
Пример #27
0
        private BotDataInfo IncrementInfoCount(IBotDataBag botdata, string key)
        {
            BotDataInfo info = null;

            if (botdata.ContainsKey(key))
            {
                info = botdata.GetValue <BotDataInfo>(key);
                info.Count++;
            }
            else
            {
                info = new BotDataInfo()
                {
                    Count = 1
                }
            };

            return(info);
        }
    }
Пример #28
0
        /// <summary>
        /// Validates the OAuthToken and refresh it if necessary.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <returns>A validated profile.</returns>
        protected async Task <Profile> GetValidatedProfile(IBotDataBag dataBag)
        {
            if (!dataBag.TryGetValue("userData", out UserData data))
            {
                return(null);
            }

            var profile = data.Profile;

            if (profile != null && profile.Token.ExpiresOn.AddMinutes(-5) <= DateTime.UtcNow)
            {
                // Replace the current OAuth token.
                profile.Token = await this.authenticationService.GetToken(profile.Token);

                // Save it.
                dataBag.SetValue("userData", data);
            }

            return(profile);
        }
Пример #29
0
        /// <summary>
        /// Create the User Profile object based on the property values stored in the Bot conversation state for this user
        /// to be used when scheduling a Site inspection visit, for e.g.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private UserProfile GetBotuser(IDialogContext context)
        {
            IBotDataBag databag = context.PrivateConversationData;
            UserProfile profile = new UserProfile();

            try
            {
                profile.Address     = databag.Get <string>("Address");
                profile.Phone       = databag.Get <string>("Phone");
                profile.FirstName   = databag.Get <string>("FirstName");
                profile.LastName    = databag.Get <string>("FirstName");
                profile.MicrosoftId = databag.Get <string>("MicrosoftAccount");
            }
            catch (Exception ex)
            {
                // telemetry.TrackTrace("Exception getting Bot state in Dialog Class .." + ex.StackTrace);
                return(null);
            }
            return(profile);
        }
Пример #30
0
        /// <summary>
        /// Get the current profile.
        /// </summary>
        /// <param name="dataBag">The data bag.</param>
        /// <returns>A VstsProfile.</returns>
        public static VstsProfile GetProfile(this IBotDataBag dataBag)
        {
            var authenticationService = GlobalConfiguration.Configuration.DependencyResolver.GetService <IAuthenticationService>();

            dataBag.ThrowIfNull(nameof(dataBag));

            if (!dataBag.TryGetValue(Profile, out VstsProfile profile))
            {
                return(null);
            }

            if (profile.Token.ExpiresOn.AddMinutes(-5) > DateTime.UtcNow)
            {
                return(profile);
            }

            profile.Token = authenticationService.GetToken(profile.Token).Result;
            dataBag.SetProfile(profile);

            return(profile);
        }
Пример #31
0
 public BotDataBagSettingsService(IBotDataBag dataBag)
 {
     this.dataBag = dataBag;
 }
 public AuthenticationProvider(IClientKeys keys, IBotDataBag bag)
 {
     SetField.NotNull(out this.keys, nameof(keys), keys);
     SetField.NotNull(out this.bag, nameof(bag), bag);
 }