I found a xamarin forms project which uses Azure, I want to do the same thing using SQLite - sqlite-net-pcl

The project is a quiz app in xamarin forms using SqLite, in the code there needs to be a way to load the questions, I will show how they do it in Azure, I need to do the same thing but in SqLite. I have also included a link to the source code for the xamarin quiz using Azure. [1]: https://github.com/garudaslap/xamarinquiz
public async Task LoadQuestions()
{
IsLoading = true;
MobileServiceClient client = AppSettings.MobileService;
IMobileServiceTable<XamarinQuiz> xamarinQuizTable =
client.GetTable<XamarinQuiz>();
try
{
QuestionList = await xamarinQuizTable.ToListAsync();
}
catch (Exception exc)
{
}
IsLoading = false;
ChooseNewQuestion();
}

You can use SQLite with this plugin:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases
Then your code will be something like:
public async Task LoadQuestions()
{
IsLoading = true;
SQLiteAsyncConnection connection = new SQLiteAsyncConnection(dbPath);
// if you need to create the table
connection.CreateTableAsync<XamarinQuiz>().Wait();
try
{
QuestionList = await database.Table<XamarinQuiz>().ToListAsync();
}
catch (Exception exc)
{
}
IsLoading = false;
ChooseNewQuestion();
}

Related

Rare error when trying to save data "unhandled exception on the current circuit"

I am using VS 2022, Blazor server project. When I trying to save data
async public static Task<bool> updateObject(Firecall obj)
{
Firecall r;
try
{
using (var context = new sptContext())
{
r = context.Firecalls.Where(c => c.Mguid == obj.Mguid).FirstOrDefault();
bool новое = (r == null);
if (новое)
{
r = new Firecall();
}
r.comment = obj.comment;
if (новое)
await context.Firecalls.AddAsync(r);
if (busy)
return false;
try
{
busy = true;
await context.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
finally {
busy = false;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
sometimes I get error:
Sometimes an error occurs, sometimes not. No error in debugger.
How to solve problem?
P.S. Data in each operation is saved as expected. Only after the operation is completed the indicated error message appear
And calling savechanges method from #code block of .razor view:
async private void SaveChanges()
{
bool rez = await firecallRepository.updateObject(_currentFireCall);
}

Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 405 (Method Not Allowed)

I am getting following exception when calling an Asp.NET Core 3.1 web api from a Blazor app.
But same code works great from visual studio debugging
Response status code does not indicate success: 405 (Method Not Allowed).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.AspNetCore.Components.HttpClientJsonExtensions.SendJsonAsync[T](HttpClient httpClient, HttpMethod method, String requestUri, Object content)*
UI Code:
public async Task<bool> UpdateCOAValue(COALookUps dataItem)
{
bool result = false;
try
{
bool response = await _httpClient.SendJsonAsync<bool>(HttpMethod.Put, string.Format(#_webApi.WebAPIUrl, "update"), dataItem);
result = await Task.FromResult(response);
}
catch (Exception ex)
{
Log.Error("Error: {0}", ex);
}
return result;
}
Web API Controller Method:
[HttpPut("update")]
public bool UpdateCOAEntry([FromBody]COALookups value)
{
try
{
List<SqlParameter> lstSQLParams = new List<SqlParameter>();
SqlParameter paramCOALookUpID = new SqlParameter();
//other code
dbManager.Update("UpdateCOALookUp", CommandType.StoredProcedure, lstSQLParams.ToArray());
}
catch (Exception ex)
{
Log.Error("Error: {0}", ex);
return false;
}
return true;
}
Web API Controllers syntax:
[Route("api/[controller]")]
[ApiController]
public class COAController : ControllerBase
{
}
Here is what worked for me. (this is a workaround), will have to redo this after each release. Please post if anyone has a better solution.
Open WebDav Authoring Rules and then select Disable WebDAV option
present on the right bar.
Select Modules, find the WebDAV Module and remove it.
Select HandlerMapping, find the WebDAVHandler and remove it.
I found this solution working than changing any settings in IIS
In ConfigureServices method add following
var handler = new HttpClientHandler()
{
UseDefaultCredentials = false,
Credentials = System.Net.CredentialCache.DefaultCredentials,
AllowAutoRedirect = true
};
services.AddSingleton(sp =>
new HttpClient(handler)
{
BaseAddress = new Uri(Configuration["WebAPI:BaseUrl"])
});

EF Core Deleting Entities in Disconnected Environment

I'm having real difficulty with EF Core with a Web API project I'm working... to me EF Core is not intuitive at all. I'm in a disconnected environment and I'm trying to update Sudoku games. EF Core is spending more time deleting connections between users and their apps and roles than in updating the game. How do I disable delete statements in an update? There is no reason for deletes, I don't need them. How do I stop them?
The method is as follows, the game is loaded as a graph and my understanding is this code should change everything tracked to modified or added. To me it seems like EF Core is going out of it's way to delete things... this makes no sense. I never instructed it to delete anything:
async public Task<IRepositoryResponse> Update(TEntity entity)
{
var result = new RepositoryResponse();
try
{
dbSet.Update(entity);
context.ChangeTracker.TrackGraph(entity,
e => {
var dbEntry = (IEntityBase)e.Entry.Entity;
if (dbEntry.Id != 0)
{
e.Entry.State = EntityState.Modified;
}
else
{
e.Entry.State = EntityState.Added;
}
});
await context.SaveChangesAsync();
result.Success = true;
result.Object = entity;
return result;
}
catch (Exception exp)
{
result.Success = false;
result.Exception = exp;
return result;
}
}
Well, I found a work around but it is the equivalent to the fixing your bike with bubblegum and tape. It's ugly... but it works. Before I save the game I create a list of all associated apps and roles and then recreate and resave the values after await context.SaveChangesAsync();. The code is listed below:
async public Task<IRepositoryResponse> Update(TEntity entity)
{
var result = new RepositoryResponse();
try
{
entity.DateUpdated = DateTime.UtcNow;
context.Games.Update(entity);
context.ChangeTracker.TrackGraph(entity,
e => {
var dbEntry = (IEntityBase)e.Entry.Entity;
if (dbEntry.Id != 0)
{
e.Entry.State = EntityState.Modified;
}
else
{
e.Entry.State = EntityState.Added;
}
});
var apps = new List<App>();
var roles = new List<Role>();
foreach (var userApp in entity.User.Apps)
{
apps.Add(userApp.App);
}
foreach (var userRole in entity.User.Roles)
{
roles.Add(userRole.Role);
}
await context.SaveChangesAsync();
foreach (var app in apps)
{
userAppDbSet.Add(new UserApp(entity.UserId, app.Id));
}
foreach (var role in roles)
{
userRoleDbSet.Add(new UserRole(entity.UserId, role.Id));
}
await context.SaveChangesAsync();
result.Success = true;
result.Object = entity;
return result;
}
catch (Exception exp)
{
result.Success = false;
result.Exception = exp;
return result;
}
}
There has to be a better way of doing this? The full app can be found here, can someone tell me a better way of setting this up:
https://github.com/Joseph-Anthony-King/SudokuCollective

Opening a Postgres Connection in Xamarin returns Error While Connecting

I am trying to connect my Android Application to Postgres but seems not to work.
The Exception Message is: Exception while Connecting
This is my Code Behind,
private void Login_Clicked(object sender, EventArgs e)
{
DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
DBLogicInput userInput = new DBLogicInput();
DBLogicResult DBResult = new DBLogicResult();
LoginModel useCredentials = new LoginModel()
{
userName = txtUsername.Text,
passWord = txtPassword.Text
};
userInput[typeof(LoginModel).FullName] = useCredentials;
try
{
DBResult = dbLoginLogic.DoProcess(userInput);
bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userExisting)
{
Application.Current.MainPage = new NavigationPage(new IndexPage());
}
else
{
_ = DisplayAlert("Login Error", "User does not exist", "Ok");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This is the Class I created to connect the DB.
public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
{
public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
public DBLogicResult DoProcess(DBLogicInput inOut)
{
//throw new NotImplementedException();
DBLogicResult result = default(DBLogicResult);
NpgsqlConnection connection = null;
NpgsqlTransaction transaction = null;
try {
connection = new NpgsqlConnection(connectionString);
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
transaction = connection.BeginTransaction();
result = Process(connection, inOut);
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
} finally {
if (connection != null)
{
connection.Close();
}
}
return result;
}
protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
}
The error exists after the debugger hits the code connection.Open();.
Should I add a web services to connect the postgres to my android app built in xamarin forms?
I am only a beginner in Xamarin Forms. I am just trying to create a self application. And need a little help for me to learn a new platform in programming.
Thank you and Regards,
How to fix it?
Well, I think I am doing it wrong.
Maybe the Right way to Connect the PostgreSQL is to have a WEB API.
Calling that web API to the Xamarin forms.
I really don't know if it is correct, but I will give it a try.
I will update the correct answer after I finish the development of that WEB API so that other beginners will found this answer helpful.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)