/// <summary>
        /// Populates the template table with the request urls and the scopes table with the permission scopes.
        /// </summary>
        private void SeedPermissionsTables()
        {
            HashSet <string> uniqueRequestUrlsTable = new HashSet <string>();
            int count = 0;

            foreach (string permissionFilePath in _permissionsFilePaths)
            {
                string jsonString = _fileUtility.ReadFromFile(permissionFilePath).GetAwaiter().GetResult();

                if (!string.IsNullOrEmpty(jsonString))
                {
                    JObject permissionsObject = JObject.Parse(jsonString);

                    JToken apiPermissions = permissionsObject.First.First;

                    foreach (JProperty property in apiPermissions)
                    {
                        // Remove any '(...)' from the request url and set to lowercase for uniformity
                        string requestUrl = Regex.Replace(property.Name.ToLower(), @"\(.*?\)", string.Empty);

                        if (uniqueRequestUrlsTable.Add(requestUrl))
                        {
                            count++;

                            // Add the request url
                            _urlTemplateTable.Add(count.ToString(), new UriTemplate(requestUrl));

                            // Add the permission scopes
                            _scopesListTable.Add(count, property.Value);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the JSON file contents of the sample queries and returns a deserialized instance of a
        /// <see cref="SampleQueriesList"/> from this.
        /// </summary>
        /// <returns>The deserialized instance of a <see cref="SampleQueriesList"/>.</returns>
        private async Task <SampleQueriesList> GetSampleQueriesListAsync()
        {
            // Get the file contents from source
            string jsonFileContents = await _fileUtility.ReadFromFile(_queriesFilePathSource);

            if (string.IsNullOrEmpty(jsonFileContents))
            {
                /* File is empty; instantiate a new list of sample query
                 * objects that will be used to add new sample queries*/
                return(new SampleQueriesList());
            }

            // Return the list of the sample queries from the file contents
            return(SamplesService.DeserializeSampleQueriesList(jsonFileContents));
        }
        /// <summary>
        /// Populates the template table with the request urls and the scopes table with the permission scopes.
        /// </summary>
        private void SeedPermissionsTables()
        {
            _urlTemplateTable = new UriTemplateTable();
            _scopesListTable  = new Dictionary <int, object>();

            HashSet <string> uniqueRequestUrlsTable = new HashSet <string>();
            int count = 0;

            foreach (string permissionFilePath in _permissionsBlobNames)
            {
                string relativePermissionPath = FileServiceHelper.GetLocalizedFilePathSource(_permissionsContainerName, permissionFilePath);
                string jsonString             = _fileUtility.ReadFromFile(relativePermissionPath).GetAwaiter().GetResult();

                if (!string.IsNullOrEmpty(jsonString))
                {
                    JObject permissionsObject = JObject.Parse(jsonString);

                    if (permissionsObject.Count < 1)
                    {
                        throw new InvalidOperationException($"The permissions data sources cannot be empty." +
                                                            $"Check the source file or check whether the file path is properly set. File path: " +
                                                            $"{relativePermissionPath}");
                    }

                    JToken apiPermissions = permissionsObject.First.First;

                    foreach (JProperty property in apiPermissions)
                    {
                        // Remove any '(...)' from the request url and set to lowercase for uniformity
                        string requestUrl = Regex.Replace(property.Name.ToLower(), @"\(.*?\)", string.Empty);

                        if (uniqueRequestUrlsTable.Add(requestUrl))
                        {
                            count++;

                            // Add the request url
                            _urlTemplateTable.Add(count.ToString(), new UriTemplate(requestUrl));

                            // Add the permission scopes
                            _scopesListTable.Add(count, property.Value);
                        }
                    }

                    _permissionsRefreshed = true;
                }
            }
        }
示例#4
0
        /// <summary>
        /// Fetches the sample queries from the cache or a JSON file and returns a deserialized instance of a
        /// <see cref="SampleQueriesList"/> from this.
        /// </summary>
        /// <param name="locale">The language code for the preferred localized file.</param>
        /// <returns>The deserialized instance of a <see cref="SampleQueriesList"/>.</returns>
        public async Task <SampleQueriesList> FetchSampleQueriesListAsync(string locale)
        {
            // Fetch cached sample queries
            SampleQueriesList sampleQueriesList = await _samplesCache.GetOrCreateAsync(locale, cacheEntry =>
            {
                // Localized copy of samples is to be seeded by only one executing thread.
                lock (_samplesLock)
                {
                    /* Check whether a previous thread already seeded an
                     * instance of the localized samples during the lock.
                     */
                    var lockedLocale            = locale;
                    var seededSampleQueriesList = _samplesCache?.Get <SampleQueriesList>(lockedLocale);

                    if (seededSampleQueriesList != null)
                    {
                        return(Task.FromResult(seededSampleQueriesList));
                    }

                    cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(_defaultRefreshTimeInHours);

                    // Fetch the requisite sample path source based on the locale
                    string queriesFilePathSource =
                        FileServiceHelper.GetLocalizedFilePathSource(_sampleQueriesContainerName, _sampleQueriesBlobName, lockedLocale);

                    // Get the file contents from source
                    string jsonFileContents = _fileUtility.ReadFromFile(queriesFilePathSource).GetAwaiter().GetResult();

                    /* Current business process only supports ordering of the English
                     * translation of the sample queries.
                     */
                    bool orderSamples = lockedLocale.Equals("en-us", StringComparison.OrdinalIgnoreCase);

                    // Return the list of the sample queries from the file contents
                    return(Task.FromResult(SamplesService.DeserializeSampleQueriesList(jsonFileContents, orderSamples)));
                }
            });

            return(sampleQueriesList);
        }
        /// <summary>
        /// Gets the JSON file contents of the policies and returns a deserialized instance of a <see cref="SampleQueriesPolicies"/> from this.
        /// </summary>
        /// <returns>A list of category policies.</returns>
        private async Task <SampleQueriesPolicies> GetSampleQueriesPoliciesAsync()
        {
            // Get the file contents from source
            string jsonFileContents = await _fileUtility.ReadFromFile(_policiesFilePathSource);

            if (string.IsNullOrEmpty(jsonFileContents))
            {
                // Create default policies template
                SampleQueriesPolicies policies = SamplesPolicyService.CreateDefaultPoliciesTemplate();

                // Get the serialized JSON string of the list of policies
                string policiesJson = SamplesPolicyService.SerializeSampleQueriesPolicies(policies);

                // Save the document-readable JSON-styled string to the source file
                await _fileUtility.WriteToFile(policiesJson, _policiesFilePathSource);

                // Return the list of policies
                return(policies);
            }

            // Return the list of policies
            return(SamplesPolicyService.DeserializeSampleQueriesPolicies(jsonFileContents));
        }
示例#6
0
        private async Task <DialogTurnResult> MainMenuStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userProfilesFilePath = _configuration["UsersFilePathSource"];
            // Fetch list of all user profile
            string userProfileJson = await _fileUtility.ReadFromFile(userProfilesFilePath);

            List <UserProfile> userProfiles = JsonConvert.DeserializeObject <List <UserProfile> >(userProfileJson);

            stepContext.Values["password"] = (string)stepContext.Result;
            if (stepContext.Values["Language"] == "KISWAHILI")
            {
                //Get the current profile object from user state
                var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

                //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken);
                //save all of the data inside the user profile
                userProfile.Name      = (string)stepContext.Values["Name"];
                userProfile.County    = (string)stepContext.Values["county"];
                userProfile.SubCounty = (string)stepContext.Values["subCounty"];
                userProfile.Ward      = (string)stepContext.Values["ward"];
                userProfile.UserName  = (string)stepContext.Values["userName"];
                userProfile.Password  = (string)stepContext.Values["password"];

                //show Summary to the user
                await stepContext.Context.SendActivityAsync(MessageFactory.Text($" Huu Hapa muhtasari wa Profaili yako: "), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Jina:{0}", userProfile.Name)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti:{0}", userProfile.County)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti ndogo:{0}", userProfile.SubCounty)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Wadi:{0}", userProfile.Ward)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken);

                //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format(" Hongera {0}!Umesajiliwa kutumia huduma yetu.Tafadhali chagua(1.MAIN MENU) kuendelea kutumia huduma", userProfile.Name)), cancellationToken);

                // Save data in userstate
                await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile);

                userProfiles.Add(userProfile);

                // Save user profiles
                var userProfilesString = JsonConvert.SerializeObject(userProfiles, Formatting.Indented);
                await _fileUtility.WriteToFile(userProfilesString, userProfilesFilePath);

                //display main menu
                return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu",
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("MAIN MENU"),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "TAARIFA ", "HABARI", "RUFAA", "UTAFITI", "SASISHA PROFAILI", "SHARE"
                    }),
                }, cancellationToken));

                stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result;
                //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end
                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }

            else
            {
                //Get the current profile object from user state
                var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

                //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken);
                //save all of the data inside the user profile
                userProfile.Name      = (string)stepContext.Values["Name"];
                userProfile.County    = (string)stepContext.Values["county"];
                userProfile.SubCounty = (string)stepContext.Values["subCounty"];
                userProfile.Ward      = (string)stepContext.Values["ward"];
                userProfile.UserName  = (string)stepContext.Values["userName"];
                userProfile.Password  = (string)stepContext.Values["password"];

                //show Summary to the user
                await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Here is a summary of your Profile:"), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Name:{0}", userProfile.Name)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("County:{0}", userProfile.County)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("SubCounty:{0}", userProfile.SubCounty)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Ward:{0}", userProfile.Ward)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken);

                //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Congratulations {0}! You are now registered to use our service. Please choose (1.MAIN MENU ) to continue using the service.", userProfile.Name)), cancellationToken);


                //save data in userstate
                await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile);

                //Write user details to a json file
                var userDetails = JsonConvert.SerializeObject(userProfile, Formatting.Indented);
                var filePath    = @"C:\Users\Tech Jargon\source\repos\FeedBackLegalBot\FeedBackLegalBot\Data\UserDetails.json";
                if (!File.Exists(filePath))
                {
                    File.WriteAllText(filePath, userDetails);
                }
                else
                {
                    File.AppendAllText(filePath, userDetails);
                }



                //display main menu
                return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu",
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("MAIN MENU"),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "INFORMATION", "NEWS", "REFERAL", "SURVEY", "UPDATE PROFILE", "SHARE"
                    }),
                }, cancellationToken));

                stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result;
                //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end
                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }
        }