передача переменной ввода пользователя в другой файл - PullRequest
0 голосов
/ 10 июля 2020

Мне нужна помощь в том, как принять ввод пользователя со страницы входа, проверить базу данных на предмет имени пользователя и, если он существует в БД, передать его в другой файл, который извлечет информацию, относящуюся к этому имени пользователя, из cosmosDB .

Ниже приведен код страницы входа

         using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ToDoItems.Core.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPage()
        {
            InitializeComponent();
        }

        async void SignInProcedure(object sender, EventArgs e)
        {
            User user = new User(Entry_Username.Text, Entry_Password.Text);
            if (user.CheckInformation())
            {
                //await Navigation.PushModalAsync(new CosmosDBService(Entry_Username.Text));
                await Navigation.PushAsync(new ToDoItemsPage());  
            }
            else
            {
                DisplayAlert("Login", "Login Failed", "Okay");
            }
        }
    }
}

И я пытаюсь, сначала проверьте cosmosDB на имя пользователя, затем передайте имя пользователя, если оно существует, в файл cosmosDBservice, чтобы получить информацию связано с именем пользователя:

    using System.Collections.Generic;
               using System.Linq;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using System;

using System.Data;
using System.Diagnostics;
using Microsoft.Azure.Documents.Linq;
using Xamarin.Forms;
using ToDoItems.Core.Pages;

namespace ToDoItems.Core
{
    public class CosmosDBService
    {
       static string queryname;

        public CosmosDBService(string logname)
        {
            // store the parameter for use later;
            queryname = logname;
 
        }

        static DocumentClient docClient = null;

        static readonly string databaseName = "Tasks";
        static readonly string collectionName = "Items";

        static async Task<bool> Initialize()
        {
            if (docClient != null)
                return true;

            try
            {
                docClient = new DocumentClient(new Uri(APIKeys.CosmosEndpointUrl), APIKeys.CosmosAuthKey);

                // Create the database - this can also be done through the portal
                await docClient.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseName });

                // Create the collection - make sure to specify the RUs - has pricing implications
                // This can also be done through the portal

                await docClient.CreateDocumentCollectionIfNotExistsAsync(
                    UriFactory.CreateDatabaseUri(databaseName),
                    new DocumentCollection { Id = collectionName },
                    new RequestOptions { OfferThroughput = 400 }
                );

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                docClient = null;

                return false;
            }

            return true;
        }

        // <GetToDoItems>        
        /// <summary> 
        /// </summary>
        /// <returns></returns>
        /// 


        public async static Task<List<ToDoItem>> GetToDoItems()
        {
            
            var todos = new List<ToDoItem>();

            if (!await Initialize())
                return todos;

            var todoQuery = docClient.CreateDocumentQuery<ToDoItem>(
                UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
                new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
                .Where(name => name.Name == queryname)
                .AsDocumentQuery();

            while (todoQuery.HasMoreResults)
            {
                var queryResults = await todoQuery.ExecuteNextAsync<ToDoItem>();

                todos.AddRange(queryResults);
            }

            return todos;
        }
        // </GetToDoItems>



 

1 Ответ

0 голосов
/ 10 июля 2020

вы уже передаете имя пользователя конструктору CosmosDBService

public void CosmosDBService(string user) 
{
  ...
}

, вам нужно создать переменную класса для его хранения

string username; 

public void CosmosDBService(string user) 
{
  // store the parameter for use later
  username = user;
  ...
}

, тогда в вашем запросе используйте это переменная класса

public async static Task<List<ToDoItem>> GetToDoItems()
{
  ...
  
  .Where(name => name.Name == username)
          
  ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...