Load Questions during Initialize method

Anonymous
2024-01-06T10:33:06.39+00:00

I want to call the

 LoadQuestionsAsync()

method only once when it is getting Initialized.

This code should be called in the method IncrementCount() on click

        Random rand = new Random();         number = rand.Next(minumber, maxnumber);        var result = Questions.FirstOrDefault(c => c.SNo == number);        solution = result.Solution;        Topic = result.Topic;        QuestionTitle = result.QuestionTitle;        Answer = result.Answer;
  private void IncrementCount()   
 {        questionsDatabase = new QuestionsDatabase();        LoadQuestionsAsync();    }

    public static class Constants
    {
        public const string DatabaseFilename = "MCQs.db3";

        public const SQLite.SQLiteOpenFlags Flags =
            // open the database in read/write mode
            SQLite.SQLiteOpenFlags.ReadWrite |
            // create the database if it doesn't exist
            SQLite.SQLiteOpenFlags.Create |
            // enable multi-threaded database access
            SQLite.SQLiteOpenFlags.SharedCache;

        public static string DatabasePath =>
          Path.Combine(FileSystem.AppDataDirectory, DatabaseFilename);
    }



  public class InQuestion


    {
        [PrimaryKey, Indexed]


        public int SNo { get; set; }
        public int No { get; set; }

        public string Topic { get; set; }

        public string QuestionTitle { get; set; }

        public string Opt1 { get; set; }

        public string Opt2 { get; set; }

        public string Opt3 { get; set; }

        public string Opt4 { get; set; }

        public string Answer { get; set; }

        public int Time { get; set; }


        public int Correct { get; set; }

        public string Solution { get; set; }

    }


internal class PostData
    {

        public string Name { get; set; }

        public string Password { get; set; }

    }









 public class Question
    {


        public int SNo;
        public string QuestionTitle { get; set; } = string.Empty;


        public string Topic { get; set; } = string.Empty;
        public IEnumerable<string> Options { get; set; } = new List<string>();
        public string Answer { get; set; } = string.Empty;


        public int Time;
        public int Correct;
        public string Solution { get; set; } = string.Empty;
    }



    public class QuestionsDatabase
    {
        SQLiteAsyncConnection Database;
        private SQLiteAsyncConnection _dbConnection;
        public const string DatabaseFilename = "MCQ.db3";
        async Task Init()
        {
            string dbPath =
             Path.Combine(FileSystem.AppDataDirectory, DatabaseFilename);
            FileStream fileStream = new FileStream(dbPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

            _dbConnection = new SQLiteAsyncConnection(dbPath);
            if (Database is not null)
                return;
            Database = new SQLiteAsyncConnection(dbPath, Constants.Flags);

            var result = await Database.CreateTableAsync<InQuestion>();
        }
        public async Task<List<InQuestion>> GetItemsAsync()
        {
            await Init();
            var res = await Database.Table<InQuestion>().ToListAsync();
            return res;
        }
        public async Task<InQuestion> GetItemAsync(int id)
        {
            await Init();
            return await Database.Table<InQuestion>().Where(i => i.No == id).FirstOrDefaultAsync();
        }


        public async Task<int> SaveItemAsync(InQuestion item)
        {
            await Init();
            InQuestion res = await GetItemAsync(item.No);
            if (res != null)
                return await Database.UpdateAsync(item);
            else
                return await Database.InsertAsync(item);
        }


        public async Task<int> DeleteItemAsync(InQuestion item)
        {
            await Init();
            return await Database.DeleteAsync(item);
        }



    }




@using System.Text;
@using System.Net.Http.Headers;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@using System.Timers;
@using MauiAppActivity.Models;

@page "/"

<PageTitle>Counter</PageTitle>

 
<p role="status">@Topic</p>
<p role="status">@QuestionTitle</p>
<p role="status">@Answer</p>
<p role="status">@solution</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {


    //   using Communication = Microsoft.Maui.ApplicationModel.Communication;
    private string activity="";
    public string code;
    public string matches;
    QuestionsDatabase questionsDatabase;
    public int number;
    public List<Question> Questions { get; set; } = new List<Question>();
    protected int questionIndex = 0;
    protected int score = 0;
    protected int failedIndex = 0;
    protected string[] failedQuestions = new string[500];
    public int totaltime; public int totalquestions;
    public int _currentCount = 0;
    private System.Timers.Timer _timer;
    public int maxnumber; public int minumber; public string solution; public string Topic; public string QuestionTitle;
    public string Answer;


    


    private void IncrementCount()
    {
        questionsDatabase = new QuestionsDatabase();
        LoadQuestionsAsync();








    }
    async Task<List<InQuestion>> GetApiData()
    {
        //    string apiUrl = "https://sheet2api.com/v1/UHC796KdSvqC/testsp";


        string jwturl = "https://quizapijwt.azurewebsites.net/api/";
        List<InQuestion> Questions = new List<InQuestion>();


        using (var client1 = new HttpClient())
        {
            try
            {

                var postData = new PostData
                    {
                        Name = "",

                        Password = ""
                    };
                var jsonpost = System.Text.Json.JsonSerializer.Serialize(postData);
                var content = new StringContent(jsonpost, Encoding.UTF8, "application/json");
                client1.BaseAddress = new Uri(jwturl);

                client1.DefaultRequestHeaders.Clear();
                client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage Res = await client1.PostAsync("Auth", content);

                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    string json = await Res.Content.ReadAsStringAsync();

                    // Parse the JSON response to extract the address
                    dynamic data1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    code = data1.token;



                }
            }
            catch (Exception ex)
            {


            }

        }











        string connected = "N";



        string apiUrl = "https://quizapijwt.azurewebsites.net/api/";

        using (HttpClient client = new HttpClient())
        {
            try
            {
                // Make a GET request to the API
                //    HttpResponseMessage response = await client.GetAsync(apiUrl);
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {code}");
                HttpResponseMessage response = await client.GetAsync("Questions");
                // Check if the request was successful (status code 200)
                if (response.IsSuccessStatusCode)
                {

                    // Make a GET request to the API

                    connected = "Y";
                    // Read the content of the response
                    string jsonString = await response.Content.ReadAsStringAsync();


                    // Deserialize the JSON string into an object
                    Questions = JsonConvert.DeserializeObject<List<InQuestion>>(jsonString);
                    // truncate sqlLIte table Load sqlite table  from  Questions
                    //If the first time when you load the api data, it will push data to the sqlite DB.

                    //comment begins

                    List<InQuestion> itemInTheDB = await questionsDatabase.GetItemsAsync();
                    //    if (itemInTheDB.Count == 0)
                    // {


                    foreach (InQuestion item in itemInTheDB)
                    {
                        var result = Questions.FirstOrDefault(c => c.SNo == item.SNo);

                        if (result == null)
                        {
                            await questionsDatabase.DeleteItemAsync(item);
                        }
                    }

                    foreach (InQuestion itemdb in Questions)
                    {
                        var resulty = itemInTheDB.FirstOrDefault(c => c.SNo == itemdb.SNo);
                        matches = "N";


                        if (resulty == null)
                        { await questionsDatabase.SaveItemAsync(itemdb); }


                        if (resulty != null)
                        {
                            if ((resulty.No == itemdb.No) && (resulty.Opt1 == itemdb.Opt1) && (resulty.Opt2 == itemdb.Opt2) && (resulty.Opt3 == itemdb.Opt3) && (resulty.Opt4 == itemdb.Opt4)
                             && (resulty.QuestionTitle == itemdb.QuestionTitle) && (resulty.Solution == itemdb.Solution) && (resulty.Time == itemdb.Time) && (resulty.Answer == itemdb.Answer)
                             && (resulty.Topic == itemdb.Topic))
                            { matches = "Y"; }

                        }
                        else
                        { await questionsDatabase.SaveItemAsync(itemdb); }
                        if (matches == "N")
                        { await questionsDatabase.SaveItemAsync(itemdb); }

                    }
                    //   }
                    //comment ends

                }
                else
                { // Load  Questions from sql lite  table
                    Questions = await questionsDatabase.GetItemsAsync();

                }
            }
            catch (Exception ex)
            {
                if (connected == "N")
                {
                    Questions = await questionsDatabase.GetItemsAsync();

                }


            }
        }
        return Questions;
    }

    private async Task LoadQuestionsAsync()
    {

        List<InQuestion> res = await GetApiData();

        Questions.AddRange(res.Select(r => new Question
            {  SNo = r.No,
                Topic = r.Topic,
                QuestionTitle = r.QuestionTitle,
                Options = new List<string>() { r.Opt1, r.Opt2, r.Opt3, r.Opt4 },
                Answer = r.Answer,
                Time =  r.Time  ,
                Correct = r.Correct,
                Solution = r.Solution

            })); 

        totaltime = Questions.Sum(Question => Convert.ToInt32(Question.Time));

        totalquestions = (from e in res  select e.No).Count();  
        maxnumber=(from e in res select e.No).Max();
        minumber = (from e in res select e.No).Min();
        Questions= Questions.OrderByDescending(s => s.SNo).ToList();


        Random rand = new Random();
         number = rand.Next(minumber, maxnumber);
        var result = Questions.FirstOrDefault(c => c.SNo == number);
        solution = result.Solution;
        Topic = result.Topic;
        QuestionTitle = result.QuestionTitle;
        Answer = result.Answer;
        }


}
Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Azar 29,525 Reputation points MVP Volunteer Moderator
    2024-01-06T14:14:21.91+00:00

    Hi Maui Learner

    I think the LoadQuestionsAsync method is called only once during initialization, you can use a boolean flag to track this.

    @page "/"
    
    <!-- your existing code -->
    
    @code {
        // ... (existing code)
    
        private bool isInitialized = false;
    
        private void IncrementCount()
        {
            if (!isInitialized)
            {
                questionsDatabase = new QuestionsDatabase();
                LoadQuestionsAsync();
                isInitialized = true;
            }
    
            // ... (rest of your IncrementCount method)
        }
    
        // ... (existing code)
    
        private async Task LoadQuestionsAsync()
        {
            // ... (existing code)
        }
    }
    
    

    the isInitialized flag is initially set to false. When the IncrementCount method is called, it checks if isInitialized is false. If so, it initializes the necessary components, calls LoadQuestionsAsync, and sets isInitialized to true. Subsequent calls to IncrementCount will bypass the initialization block, ensuring that LoadQuestionsAsync is called only once during the component's lifetime.

    If this helps kindly accept the answer thanks much.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.