I think I understand the error but I have no idea how to solve it :/
This is the error I'm getting:
"JAR library references with identical file names but different contents were found: __reference__guava.jar. Please remove any conflicting libraries from EmbeddedJar, InputJar and AndroidJavaLibrary. Food_Recipe_App.Android"
Reason to why I want Xamarin.Google.Guava is that someone said that it would fix an issue I had earlier;
"System.NullReferenceException
Message=Object reference not set to an instance of an object."
Which, honestly, I have no idea how to solve either.
I'm thankful for all help :)
Edit: It breaks after calling the Firestore.Read();
protected override async void OnAppearing()
{
base.OnAppearing();
//using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
//{
// conn.CreateTable<Recipe>();
// var recipes = conn.Table<Recipe>().ToList();
// //recipeListView.ItemsSource = recipes;
//};
var recipes = await Firestore.Read(); ***//this line breaks***
//assignRecipesToDays(recipes);
}
This is the Read method from my Firestore script:
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
And this is the whole Firestore Script if that helps solving it:
using Android.App;
using Android.Content;
using Android.Gms.Tasks;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Auth;
using Firebase.Firestore;
using Food_Recipe_App.Assets.Classes;
using Food_Recipe_App.Helpers;
using Java.Interop;
using Java.Util;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(Food_Recipe_App.Droid.Dependencies.Auth))]
namespace Food_Recipe_App.Droid.Dependencies
{
public class Firestore : Java.Lang.Object, IFirestore, IOnCompleteListener
{
List<Recipe> recipes;
bool hasReadRecipes = false;
public Firestore()
{
recipes = new List<Recipe>();
}
public async Task<bool> Delete(Recipe recipe)
{
try
{
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Delete();
return true;
}
catch (Exception ex)
{
return false;
}
}
public async Task<bool> Insert(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = Firebase.Firestore.FirebaseFirestore.Instance.Collection("recipes");
collection.Add(new HashMap(recipeDocument));
return true;
}
catch (Exception ex)
{
return false;
}
}
public void OnComplete(Android.Gms.Tasks.Task task)
{
if (task.IsSuccessful)
{
var documents = (QuerySnapshot)task.Result;
recipes.Clear();
foreach (var doc in documents.Documents)
{
Recipe newRecipe = new Recipe()
{
title = doc.Get("title").ToString(),
description = doc.Get("description").ToString(),
Id = doc.Id
};
recipes.Add(newRecipe);
}
}
else
{
recipes.Clear();
}
hasReadRecipes = true;
}
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
public async Task<bool> Update(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Update(recipeDocument);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
Related
I have a XXXWriter. Is this the correct Fire and Forget approach in C#?
public void Add(XXX model)
{
Task.Run(() => // Fire and forget?
{
using (var ctx = new FormsEntities())
{
var dbXXX = new DALXXX();
dbXXX.Foo = model.Foo;
try
{
ctx.DALXXX.Add(dbXXX);
ctx.SaveChanges();
}
catch (Exception ex)
{
Log.Log.LogError(ex.GetMostInnerException(), "whatever");
}
}
});
}
I would recommend that the implementation is refactored as below
public class XXXWriter
{
public static void FireAndForget(XXX model)
{
Task.Run(() => DoFireAndForgetAsync(model));
}
private void DoFireAndForgetAsync(XXX model)
{
try
{
using (var ctx = new FormsEntities())
{
var dbXXX = new DALXXX();
dbXXX.Foo = model.Foo;
ctx.DALXXX.Add(dbXXX);
ctx.SaveChanges();
}
}catch (Exception ex)
{
// Remember that the Async code needs to handle its own
// exceptions, as the "DoFireAndForget" method will never fail
Log.Log.LogError(ex.GetMostInnerException(), "whatever");
}
}
}
Does anyone have any idea of how to solve this error message
Error CS1729: 'SQLiteConnection' does not contain a constructor that takes 1 arguments (CS1729)
this is the files where it is happening
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
using Android.Util;
using SQLite.Net;
namespace CPDEP1
{
public class DataBase
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool createDataBase()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")));
{
connection.CreateTable<Person>();
return true;
}
}
catch(SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool insertIntoTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Insert(person);
return true;
}
}
catch(SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public List<Person> selectTablePerson()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
return connection.Table<Person>().ToList();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
public bool updateTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Query<Person>("UPDATE Person set Nom=?,Prenom=?,Telephone=?,Addresse=?,Courriel=?,Cin=? Where Id=?,",person.Nom,person.Prennom,person.Telephone,person.Addresse,person.Courriel,person.Cin,person.Id);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool deleteTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Delete(person);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool selectQueryTablePerson(int Id)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Query<Person>("SELECT * FROM Person Where Id=?", Id);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
}
}
Thanks in advance for your help
I was following the instruction here: https://wolfprogrammer.com/2016/09/10/adding-a-sqlite-database-to-xamarin-forms/ and got the same error.
Then I referred to Microsoft instruction here (https://msdn.microsoft.com/en-us/magazine/mt736454.aspx) and noticed there are 2 very similar thing both written by Frank Krueger. Please check the image below, download the one that is highlighted in GREEN, not the RED one.
I am using CrossGeolocator to retrieve the current latitude and longitude of the device. However I am using it inside an OnAppearing override method and it is not working. The GetPositionAsync method hangs the App.
protected override void OnAppearing()
{
base.OnAppearing();
var position = GetPosition().Result;
var lat = position.Latitude;
var lon = position.Longitude;
}
private static async Task<Position> GetPosition()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(10000);
return position;
}
Detail is that I am using this same GetPosition method in buttons in the application and works perfectly.
Could someone help me in this matter?
Try this:
Create a global variable:
private Position _position;
Then call ur method to get the position on constructor.
Re-write ur method like this:
public async void GetPosition()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var myPosition = await locator.GetPositionAsync();
_position = new Position(myPosition.Latitude, myPosition.Longitude);
}
Then make a while where u want to use this:
while(_position == new Postion(0,0))
GetPosition();
This worked for me.
Set up the xamarin forms maps as stated in the link.
https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/
set permissions as stated in below link
https://jamesmontemagno.github.io/GeolocatorPlugin/GettingStarted.html
you may make use of https://jamesmontemagno.github.io/GeolocatorPlugin/CurrentLocation.html
using Plugin.Geolocator;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace MapApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : ContentPage
{
private Position _position;
public MapPage()
{
InitializeComponent();
var map = new Map(
MapSpan.FromCenterAndRadius(
new Position(37, -122), Distance.FromMiles(0.3)))
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
if (IsLocationAvailable())
{
GetPosition();
map.MoveToRegion(MapSpan.FromCenterAndRadius(_position, Distance.FromMiles(1)));
}
map.MapType = MapType.Street;
var stack = new StackLayout { Spacing = 0 };
stack.Children.Add(map);
Content = stack;
}
public bool IsLocationAvailable()
{
if (!CrossGeolocator.IsSupported)
return false;
return CrossGeolocator.Current.IsGeolocationAvailable;
}
public async void GetPosition()
{
Plugin.Geolocator.Abstractions.Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100;
position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
_position = new Position(position.Latitude, position.Longitude);
//got a cahched position, so let's use it.
return;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
return;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);
}
catch (Exception ex)
{
throw ex;
//Display error as we have timed out or can't get location.
}
_position = new Position(position.Latitude, position.Longitude);
if (position == null)
return;
}
}
}
Things to take care is
calling the method in constructor.
have available lat long if exists.
VERY IMP have try catch, without try catch the application crashes. Not writing any thing in catch as don;t want to catch exception.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using System.Threading.Tasks;
using Plugin.Geolocator.Abstractions;
using Plugin.Geolocator;
using System.Diagnostics;
using Xamarin.Forms;
using abcde.iOS;
[assembly: Xamarin.Forms.Dependency(typeof(GPSLocation_iOS))]
namespace abcde.iOS
{
public class GPSLocation_iOS : IGPSLocation
{
public Position _position;
public GPSLocation_iOS()
{
GetPosition();
}
public Dictionary<string, string> GetGPSLocation()
{
Dictionary<string, string> dictPosition = new Dictionary<string, string>();
dictPosition.Add("latitude", _position.Latitude.ToString());
dictPosition.Add("longitude", _position.Longitude.ToString());
return dictPosition;
}
public async void GetPosition()
{
try
{
var locator = CrossGeolocator.Current;
_position = await locator.GetLastKnownLocationAsync();
if (_position == null)
{
locator.DesiredAccuracy = 50;
var myPosition = await locator.GetPositionAsync();
_position = new Position(myPosition.Latitude, myPosition.Longitude);
}
}
catch (Exception ex)
{
}
}
latest 2018-07-10 version update,
To support iOS 11 and earlier, you can include all three keys:
NSLocationWhenInUseUsageDescription,
NSLocationAlwaysAndWhenInUseUsageDescription
NSLocationAlwaysUsageDescription.
I use Xamarin to write app, and it works fine in my iOS project
reference : https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/map
I solved my problem just adding the parameters in GetPositionAsync: null and true.
var location = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);
and turn on the GPS
My problem was on Android 4.4
this is my service code :
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.Linq.Expressions;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Web;
namespace RadAppSilver.Web
{
public class DsWFS006 : DataService<WFS006Entities>
{
public DsWFS006()
{
ServiceHost host = new ServiceHost(typeof(DsWFS006));
ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();
// if not found - add behavior with setting turned on
if (debug == null)
{
host.Description.Behaviors.Add(
new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
}
else
{
// make sure setting is turned ON
if (!debug.IncludeExceptionDetailInFaults)
{
debug.IncludeExceptionDetailInFaults = true;
}
}
host.Open();
// This method is called only once to initialize service-wide policies.
}
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
//config.SetEntitySetPageSize("DocDetail", 30);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
}
I need to debug when I'm going to new record to my entity error happened but update entity works fine :
private void Grid1RowEditEnded(object sender, Telerik.Windows.Controls.GridViewRowEditEndedEventArgs e)
{
if (e.EditAction == Telerik.Windows.Controls.GridView.GridViewEditAction.Commit)
{
doc.AccNo = string.IsNullOrEmpty(SelectedAcc) ? doc.AccNo : SelectedAcc;
if (e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Edit)
{
service.UpdateObject(doc);
}
else if (e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Insert)
{
(this.grid1.ItemsSource as VirtualQueryableCollectionView).Add(doc);
service.AddObject("DocDetail", doc);
}
service.BeginSaveChanges(OnChangesSaved, service);
}
}
private void OnChangesSaved(IAsyncResult result)
{
Dispatcher.BeginInvoke(() =>
{
service = result.AsyncState as DS1.WFS006Entities;
try
{
service.EndSaveChanges(result);
}
catch (DataServiceRequestException ex)
{
MessageBox.Show(ex.Response.ToString());
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
});
}
and this code include initializing service on my client :
private void SetContext()
{
service = new DSEntity();
DataServiceQuery<DS1.Accounts> queryAcc = (DataServiceQuery<DS1.Accounts>)
(service.Accounts.Select(m =>
new DS1.Accounts
{
AccNo = m.AccNo,
AccDesc = m.AccDesc
}));
queryAcc.BeginExecute(t =>
{
DataServiceQuery<DS1.Accounts> state = t.AsyncState as DataServiceQuery<DS1.Accounts>;
var executedState = state.EndExecute(t);
ObservableCollection<DS1.Accounts> data = new ObservableCollection<DS1.Accounts>();
foreach (var entity in executedState)
data.Add(entity);
AccCache = data.ToList();
}, queryAcc);
var view = new VirtualQueryableCollectionView() { LoadSize = 300, VirtualItemCount = 10000 };
view.ItemsLoading += (y, e) =>
{
DataServiceQuery<DS1.DocDetail> query = (DataServiceQuery<DS1.DocDetail>)
service.DocDetail.OrderBy(it => it.Item)
.Where<DS1.DocDetail>(it => it.DocSerNo == 91120001)
.Where(view.FilterDescriptors)
.Sort(view.SortDescriptors)
.Skip(e.StartIndex)
.Take(e.ItemCount);
query = query.IncludeTotalCount();
query.BeginExecute(
s =>
{
DataServiceQuery<DS1.DocDetail> state = s.AsyncState as DataServiceQuery<DS1.DocDetail>;
var executedState = state.EndExecute(s);
var response = executedState as QueryOperationResponse<DS1.DocDetail>;
int count = (int)response.TotalCount;
ObservableCollection<DS1.DocDetail> data = new ObservableCollection<DS1.DocDetail>();
foreach (var entity in executedState)
data.Add(entity);
var dataSource = data.ToList();
view.VirtualItemCount = count;
view.Load(e.StartIndex, dataSource);
}, query);
};
grid1.ItemsSource = view;
}
it doesn't work while add new object and exception doesn't give me any detail when I add host.open(); on constructor to show exception detail the service has been stop.
Include all the option for debugging the wcf service
1.Apply the following attribute to your service class
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
Override the following two methods in your service class
a. protected override void OnStartProcessingRequest(ProcessRequestArgs args)
b,protected override void HandleException(HandleExceptionArgs args)
set the break points on these two methods and see what type of exception.
I created a little class in order to create logs.
This class use streamwriter functions in order to do this.
I write a log, and after closed the log, i would like to re-open after, in order to append some datas.
I tried severals tips, and...i always have an exception who tell me " The file is used by another process".
Nevertheless, i use the close(), but, i always had this exception.
Here is my class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TEST
{
public class CLog
{
private StreamWriter myWriter;
public string Name
{
set { Name = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Name;
}
}
public string Directory
{
set { Directory = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Directory.ToString();
}
}
public string CompleteFileName { set; get; }
public CLog(string _CompleteFileName)
{
CompleteFileName = _CompleteFileName;
}
public bool CreateLog()
{
try
{
myWriter = new StreamWriter(CompleteFileName);
return true;
}
catch (Exception ex )
{
return false;
}
}
public bool AppendTextToFile(string strText)
{
try
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText(CompleteFileName))
{
sw.WriteLine(strText);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool WriteLine(string strLine)
{
try
{
myWriter.WriteLine(strLine);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool SaveFile()
{
try
{
myWriter.Close();
myWriter.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
Please look at the AppendTextToFile.
Here is the use :
monLog = new CLog("C:\\TEST.TXT");
if (monLog.CreateLog())
{
monLog.WriteLine("");
monLog.WriteLine("******");
monLog.WriteLine("Some data");
monLog.WriteLine("******");
monLog.SaveFile();
...
....
monLog.AppendTextToFile("** my AppendedData***);
monLog.SaveFile();
}
Anyone know why i have this exception and how solve it ?
Thanks a lot :)