How to display Image Data on .NET MAUI Blazor App
Here is the api that fetches Image data
https://quizapijwt.azurewebsites.net/api/Questions
Images are stored in imagedata bytea
CREATE TABLE public."Questions" (
"SNo" int4 NOT NULL GENERATED BY DEFAULT AS IDENTITY( INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START 1 CACHE 1 NO CYCLE),
"No" int4 NOT NULL,
"Topic" varchar(500) NULL,
"QuestionTitle" varchar(500) NULL,
"Opt1" varchar(50) NULL,
"Opt2" varchar(50) NULL,
"Opt3" varchar(50) NULL,
"Opt4" varchar(50) NULL,
"Answer" varchar(50) NULL,
"Time" int4 NULL,
"Correct" int4 NULL,
solution varchar(500) NULL,
imagedata bytea NULL,
CONSTRAINT pk_no PRIMARY KEY ("SNo")
);
public class QuestionI
{
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; }
public byte[] Imagedata { get; set; }
internal IEnumerable<Question> Select(Func<object, Question> value)
{
throw new NotImplementedException();
}
}
@using System.Text;
@using System.Net.Http.Headers;
@using Microsoft.AspNetCore.Components;
@using Newtonsoft.Json;
@using System.Timers;
@using MauiAppMCQs.Models;
@page "/ImageApp"
<PageTitle>QuizApp</PageTitle>
@if (Questions.ToList().Count <= 0)
{
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
}
@if (Questions.ToList().Count > 0)
{
<button class="btn btn-primary" @onclick="NextQuestion">Next Question</button>
}
<p role="status">@Topich</p>
<p role="status">@Topic</p>
@if (Questions.ToList().Count > 0)
{
@number
@filler
@maxnumber
}
<p role="status">@QuestionTitleh</p>
<p role="status">@QuestionTitle</p>
<p role="status">@Answerh</p>
<p role="status">@Answer</p>
<p>@ImageData</p>
@if (Questions.ToList().Count > 0)
{
<p role="status">@timeh</p>
<p role="status">@time</p>
<button class="btn btn-primary" @onclick="ToggleAnswer">@buttonText</button>
<p style="display:@display">@solutionh</p>
<p style="display:@display">@solution</p>
<p>@(_currentCount)</p>
}
<p role="status">@errormessage</p>
@code {
public byte[] ImageData;
// using Communication = Microsoft.Maui.ApplicationModel.Communication;
private string activity = "";
public string code; public string errortoggle = ""; public string errormessage = ""; public string checkflag = "N";
public string matches;
public int number;
public List<QuestionI> Questions { get; set; } = new List<QuestionI>();
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; public int _currentSec ;
private System.Timers.Timer _timer;
public int maxnumber; public int minumber; public string solution; public string Topic; public string QuestionTitle;
public string Answer;public int time; public string timeh;
bool isInitialized = false;
string solutionh;
string Topich;
string QuestionTitleh;
string Answerh;
List<QuestionI> res;
private string display = "none";
private string buttonText = "Hide Solution";
public int range;
string filler = "/";
private void ToggleAnswer()
{
string bypass = "N";
if (_currentCount > 60 )
{
bypass = "Y";
errormessage = "";
}
else
{ errormessage = "Cannot Show Solution until 1 minute "; }
if (bypass == "Y")
{
if (display == "none")
{
display = "block";
buttonText = "Hide Solution";
}
else
{
checkflag = "Y";
display = "none";
buttonText = "Show Solution";
}
}
}
private void NextQuestion()
{
if (checkflag == "N")
{ errormessage = "Show/Hide Solution to move to next question"; }
else
{
_currentCount = 0;
_timer = new();
_timer.Interval = 1000;
_timer.Elapsed += async (object? sender, ElapsedEventArgs e) =>
{
_currentCount++;
await InvokeAsync(StateHasChanged);
};
_timer.Enabled = true;
LoadQuestionsAsync();
checkflag = "N";
errormessage = " ";
}
}
private void IncrementCount()
{
_currentCount = 0;
_timer = new();
_timer.Interval = 1000;
_timer.Elapsed += async (object? sender, ElapsedEventArgs e) =>
{
_currentCount++;
_currentSec = _currentCount / 10;
await InvokeAsync(StateHasChanged);
};
_timer.Enabled = true;
LoadQuestionsAsync();
}
async Task<List<QuestionI>> GetApiData()
{
string jwlurl="https://quizapijwt.azurewebsites.net/api/";
List<QuestionI> Questions = new List<QuestionI>();
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();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = null;
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<QuestionI>>(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
// }
//comment ends
}
else
{ // Load Questions from sql lite table
}
}
catch (Exception ex)
{
if (connected == "N")
{
}
}
}
return Questions;
}
private async Task LoadQuestionsAsync()
{
display = "none";
buttonText = "Show Solution";
if (!isInitialized)
{
res = await GetApiData();
Questions.AddRange(res.Select(r => new QuestionI
{
SNo = r.No,
Topic = r.Topic,
QuestionTitle = r.QuestionTitle,
Answer = r.Answer,
Time = r.Time,
Correct = r.Correct,
Solution = r.Solution,
Imagedata=r.Imagedata
}));
isInitialized = true;
}
maxnumber = (from e in res select e.No).Max();
minumber = (from e in res select e.No).Min();
range = maxnumber + 1;
Questions = Questions.OrderByDescending(s => s.SNo).ToList();
Random rand = new Random();
number = rand.Next(minumber, range);
var result = Questions.FirstOrDefault(c => c.SNo == number);
solution = result.Solution;
solutionh = "Solution";
Topic = result.Topic;
Topich = "Topic";
time = (result.Time)/60;
timeh = "Time in minutes";
QuestionTitle = result.QuestionTitle;
QuestionTitleh = "QuestionTitle";
Answer = result.Answer;
Answerh = "Answer";
ImageData = result.Imagedata;
}
}