Object value is null after deserialization (Xamarin with SQLite) - sqlite

for an internship project I'm developping an app with Xamarin that will allow users to scan barcodes and create sheets of labels and purchases.
To prevent the scanned codes from being lost in case of crash etc, I've implemented SQLite to create a local backup that we could restore.
The structure is as follows : a ListOfLabelLines contains several LabelLine which each contain a Product and different other informations (such as packaging, quantity etc).
ListOfLabelLines.cs :
[Table("ListOfLabelLines")] // Indique le nom de la table qui sera générée par SQLite
public class ListOfLabelLines : BaseItem
{
private string _name { get; set; }
[TextBlob("LabelLinesBlob")]
public ObservableCollection<LabelLine> lines { get; set; }
[TextBlob("ListBlob")]
public List<String> TestList { get; set; }
public string LabelLinesBlob { get; set; } // serialized LabelLines
public string ListBlob { get; set; } // serialized TestList
public ListOfLabelLines()
{
}
public ListOfLabelLines(string name)
{
this._name = name;
lines = new ObservableCollection<LabelLine>();
TestList = new List<String>();
TestList.Add("Test1");
TestList.Add("Test2");
}
public string Name
{
get { return _name; }
set
{
_name = value;
}
}
}
}
These objects ListOfLabelLines contain an ObservableCollection<LabelLine> which I'm serializing by using the TextBlob property from SQLite-net-extensions.
However, when I retrieve the ListOfLabelLines I've stored, the ObservableCollection appears as null :
Example of null collections
Here are the methods I use to store the objects in SQlite :
public void SaveListOfLabelLines(ListOfLabelLines ShelfLabelInstance)
{
var query = from label in database.Table<ListOfLabelLines>()
where label.Name == ShelfLabelInstance.Name
select label;
var res = query.FirstOrDefault();
if (res != null)
{
database.UpdateWithChildren(ShelfLabelInstance);
Console.WriteLine("Label " + ShelfLabelInstance.Name + " updated");
}
else
{
database.InsertWithChildren(ShelfLabelInstance);
Console.WriteLine("Label " + ShelfLabelInstance.Name + " created");
}
}
and to retrieve them :
public void CheckProductsInLabelLine(string n)
{
var query = from LOLL in database.Table<ListOfLabelLines>()
where LOLL.Name == n
select LOLL;
ListOfLabelLines res = query.FirstOrDefault();
The string property linked to the TextBlob, however, contains the JSON object I need.
I thought the ObservableCollection would be obtainable when getting the object in DB since TextBlob is supposed to serialize AND deserialize.
Could anybody help ?
Thanks a lot !

Related

.Net Core 6.0 Web API - How to implement postgresql database(eg: Product Table -> Description column) localization for English and French?

I am developing a Web API using Core 6.0 with localization. Localization should be supported for both static (e.g., basic strings like greeting) and dynamic content (e.g., Values of the Product Instance).
I have implemented the localization for static content using JsonStringLocalizerFactory as discussed in this article - https://christian-schou.dk/how-to-add-localization-in-asp-net-core-web-api/.
public class LocalizerController : ControllerBase
{
private readonly IStringLocalizer<LocalizerController> _stringLocalizer;
public LocalizerController(IStringLocalizer<LocalizerController> stringLocalizer)
{
_stringLocalizer = stringLocalizer;
}
[HttpGet]
public IActionResult Get()
{
var message = _stringLocalizer["hi"].ToString();
return Ok(message);
}
[HttpGet("{name}")]
public IActionResult Get(string name)
{
var message = string.Format(_stringLocalizer["welcome"], name);
return Ok(message);
}
[HttpGet("all")]
public IActionResult GetAll()
{
var message = _stringLocalizer.GetAllStrings();
return Ok(message);
}
}
Next, I would like to implement localization for dynamic content (e.g., Details of the Product which will be sent to the WEB API and stored in the postgresql database table).
A possible approach is to duplicate the postgresql database table for each language (English and French). Could there be a better approach to avoid duplicate data and additional manual work?
You can create language table for each multi-language entity.
Langugage model;
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
public string IsoCode { get; set; }
}
Static language list;
public class Constant
{
public static List<Language> Languages { get; set; } = new()
{
new Language
{
Id = 1,
Name = "English(United States)",
IsoCode = "en-US"
},
new Language
{
Id = 2,
Name = "Turkish",
IsoCode = "tr-TR"
}
};
}
Entities;
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
public virtual ICollection<ProductLang> ProductLangs { get; set; }
}
public class ProductLang
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[ForeignKey("Products")]
public Guid ProductId { get; set; }
public virtual Product Product { get; set; }
public int LanguageId { get; set; }
}
You can change the LanguageId property name. If you want to store languages in database, you can create a Languages table and create a relationship with that table from entity language tables. This can reduce duplication.
After include the language table to the entity, you can write an extension method to easily get the requested language data.
public static string GetLang<TEntity>(this IEnumerable<TEntity> langs, Expression<Func<TEntity, string>> propertyExpression, int defaultLangId)
{
var languageIdPropName = nameof(ProductLang.LanguageId);
var requestedLangId = GetCurrentOrDefaultLanguageId(defaultLangId);
if (langs.IsNullOrEmpty())
return string.Empty;
var propName = GetPropertyName(propertyExpression);
TEntity requestedLang;
if (requestedLangId != defaultLangId)
requestedLang = langs.FirstOrDefault(lang => (int)lang.GetType()
.GetProperty(languageIdPropName)
.GetValue(lang) == requestedLangId)
?? langs.FirstOrDefault(lang => (int)lang.GetType()
.GetProperty(languageIdPropName)
.GetValue(lang) == defaultLangId);
else requestedLang = langs.FirstOrDefault(lang => (int)lang.GetType().GetProperty(languageIdPropName).GetValue(lang) == defaultLangId);
requestedLang ??= langs.FirstOrDefault();
return requestedLang.GetType().GetProperty(propName).GetValue(requestedLang, null)?.ToString();
static int GetCurrentOrDefaultLanguageId(int defaultLanguageId)
{
var culture = CultureInfo.CurrentCulture;
var currentLanguage = Constant.Languages.FirstOrDefault(i => i.IsoCode == culture.Name);
if (currentLanguage != null)
return currentLanguage.Id;
else
return defaultLanguageId;
}
static string GetPropertyName<T, TPropertyType>(Expression<Func<T, TPropertyType>> expression)
{
if (expression.Body is MemberExpression tempExpression)
{
return tempExpression.Member.Name;
}
else
{
var op = ((UnaryExpression)expression.Body).Operand;
return ((MemberExpression)op).Member.Name;
}
}
}
This extension method checks for 3 conditions;
If there is data in the requsted language, it returns this data,
If there is no data in the requsted language, it checks if there is data in the default language. If the data is available in the default language, it will return the data,
Returns the first available language data if there is no data in the default language
Usage;
var defaultLangId = 1;
Product someProduct = await _dbContext.Set<Product>().Include(i => i.ProductLangs).FirstOrDefaultAsync();
var productName = someProduct.ProductLangs.GetLang(i => i.Name, defaultLangId);
It is up to you to modify this extension method according to your own situation. I gave you an example scenario where languages are kept in a static list.

EF Core with Lazy Loading tracks unreachable Objects?

I am currently having troubles with entity framework core.
The application I am developing is supposed to help users plan their next business year by increasing/decreasing the quantity of a service they want to provide in the next year.
Based on their input the "worth" of a service is distributed pro rata to other "mini-services" that are contained in the changed service.
To do so I load the affected entries of the main service and the "mini-services" from Database via a repository which then uses Entity Framework.
public IEnumerable<OpsDistributionEntry> FilteredOpsDistributionEntries(int catalogId, IEnumerable<OpsDistributionEntry> filterEntries)
{
return _context.OpsDistributionEntries.FromSqlRaw(
$"SELECT * FROM OpsDistributionEntries WHERE (Id IN (SELECT OpsEntriesId FROM DistributionCatalogOpsDistributionEntry WHERE CatalogsId = {catalogId}) " +
$"AND EntityId IN ({string.Join(",", filterEntries.Select(x => x.EntityId))}))").ToList();
}
I then map those database objects to my domain objects via constructor.
var opsDistributionEntries = new OpsDistributionEntriesFromDatabaseObjects(
_repository.FilteredOpsDistributionEntries(_distCatalogId, _filterEntries));
public class OpsDistributionEntriesFromDatabaseObjects : IOpsDistributionEntries
{
private readonly IOpsDistributionEntries _distribution;
public OpsDistributionEntriesFromDatabaseObjects(IEnumerable<DatabaseObjects.OpsDistributionEntry> distribution)
{
_distribution = new OpsDistributionEntries(distribution.Select(x => new OpsDistributionEntryFromDatabaseObject(x)));
}
public IEnumerator<IOpsDistributionEntry> GetEnumerator()
{
return _distribution.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class OpsDistributionEntryFromDatabaseObject : IOpsDistributionEntry
{
public OpsDistributionEntryFromDatabaseObject(DatabaseObjects.OpsDistributionEntry opsDistributionEntry)
: this(opsDistributionEntry.Id, opsDistributionEntry.TotalCases, opsDistributionEntry.TotalEffectiveWeight, opsDistributionEntry.Provide,
opsDistributionEntry.Freeze,
new OpsFromDatabaseObject(opsDistributionEntry.Entity),
new DrgDistributionsFromDatabaseObjects(opsDistributionEntry.DrgDistribution))
{
}
private OpsDistributionEntryFromDatabaseObject(int id, int totalCases, double totalEffectiveWeight, bool provide, bool freeze, IOps ops,
IDrgDistributions drgDistribution)
{
Id = id;
TotalCases = totalCases;
TotalEffectiveWeight = totalEffectiveWeight;
Provide = provide;
Freeze = freeze;
Ops = ops;
DrgDistribution = drgDistribution;
}
public int Id { get; }
public int TotalCases { get; }
public double TotalEffectiveWeight { get; }
public bool Provide { get; }
public bool Freeze { get; }
public IOps Ops { get; }
public IDrgDistributions DrgDistribution { get; }
}
public sealed class OpsFromDatabaseObject : IOps
{
public OpsFromDatabaseObject(DatabaseObjects.Ops ops) : this(ops.Id, ops.Code, ops.Description, ops.Year)
{
}
private OpsFromDatabaseObject(int id, string code, string description, int year)
{
Id = id;
Code = code;
Description = description;
Year = year;
}
public int Id { get; }
public string Code { get; }
public string Description { get; }
public int Year { get; }
}
I pass the database objects on to different levels, but finally every value is assigned and every possible navigation property is mapped to an domain object.
With those mapped domain objects I recalculate the new "worth" of the service and the correlated "mini-services".
After calculation I again map my Domain Objects to DatabaseObjects.
DatabaseObjects.OpsDistributionEntry ToDatabaseObject() => new DatabaseObjects.OpsDistributionEntry
{
Id = Id,
EntityId = Ops.Id,
Freeze = Freeze,
Provide = Provide,
TotalCases = TotalCases,
TotalEffectiveWeight = TotalEffectiveWeight,
DrgDistribution = DrgDistribution.Select(x => x.ToDatabaseObject()).ToImmutableList(),
};
When I want to add those "updated" Objects to the context via repository
public void UpdateDistributionEntries(IEnumerable<OpsDistributionEntry> opsDistributionEntries)
{
if (opsDistributionEntries == null) throw new ArgumentNullException(nameof(opsDistributionEntries));
_context.OpsDistributionEntries.UpdateRange(opsDistributionEntries);
}
I am getting an Error that the Entities I want to updated are already being tracked by Entity Framework.
After some debugging I think that EF is still tracking the database objects I loaded for mapping the domain objects. I just use the database objects to map values to the domain objects and do not store any reference for them (as far as I understand).
Can any of you maybe tell me why they are still being tracked even if they are "unreachable". Or am I thinking wrong? Might this be because of Lazy Loading?
I've been debugging for almost 14 hours now :D Please someone give me a hint :D
Many thanks in advance

SQLite.NET PCL returning 0 in all instances of autoincrement primary key

I am totally not getting this, because I have used this library in Xamarin apps for several years.
I have this base class that contains properties common in all db items:
public class BaseItem
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; } = 0; // SQLite ID
public long CreatedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
public long ModifiedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
}
Now, I derive from it:
[Table("CategoryTable")]
public class Category : BaseItem
{
public int CategoryTypeID { get; set; } = (int)CategoryType.Invalid;
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
Here's a simplified version of what I'm seeing:
public class DBWorld
{
ISQLiteService SQLite { get { return DependencyService.Get<ISQLiteService>(); } }
private readonly SQLiteConnection _conn;
public DBWorld()
{
_conn = SQLite.GetConnection("myapp.sqlite");
}
public void TestThis()
{
_conn.CreateTable<Category>();
var category = new Category();
category.Name = "This Should Work";
int recCount = connection.Insert(category);
// at this point recCount shows as 1, and category.ID shows as zero.
// I thought Insert was supposed to set the autoincrement primary key
// regardless, it should be set in the database, right? So...
var categoryList = connection.Query<Category>($"SELECT * FROM {DBConstants.CategoryTableName}");
// at this point categoryList[0] contains all the expected values, except ID = 0
}
}
I am obviously missing something, but for the life of me, I can't figure out what...
Like so many other bizarre things that happen in the Visual Studio Xamarin world, when I went back later, this worked the way all of us expect. I guess Visual Studio was just tired and needed to be restarted.

A circular reference was detected while serializing entities with one to many relationship

How to solve one to many relational issue in asp.net?
I have Topic which contain many playlists.
My code:
public class Topic
{
public int Id { get; set; }
public String Name { get; set; }
public String Image { get; set; }
---> public virtual List<Playlist> Playlist { get; set; }
}
and
public class Playlist
{
public int Id { get; set; }
public String Title { get; set; }
public int TopicId { get; set; }
---> public virtual Topic Topic { get; set; }
}
My controller function
[Route("data/binding/search")]
public JsonResult Search()
{
var search = Request["term"];
var result= from m in _context.Topics where m.Name.Contains(search) select m;
return Json(result, JsonRequestBehavior.AllowGet);
}
When I debug my code I will see an infinite data because Topics will call playlist then playlist will call Topics , again the last called Topic will recall playlist and etc ... !
In general when I just use this relation to print my data in view I got no error and ASP.NET MVC 5 handle the problem .
The problem happens when I tried to print the data as Json I got
Is there any way to prevent an infinite data loop in JSON? I only need the first time of data without call of reference again and again
You are getting the error because your entity classes has circular property references.
To resolve the issue, you should do a projection in your LINQ query to get only the data needed (Topic entity data).
Here is how you project it to an anonymous object with Id, Name and Image properties.
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new
{
Id = x.Id,
Name = x.Name,
Image = x.Image
});
return Json(result, JsonRequestBehavior.AllowGet);
}
If you have a view model to represent the Topic entity data, you can use that in the projection part instead of the anonymous object
public class TopicVm
{
public int Id { set;get;}
public string Name { set;get;}
public string Image { set;get;}
}
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new TopicVm
{
Id = x.Id,
Name = x.Name,
Image = x.Image
});
return Json(result, JsonRequestBehavior.AllowGet);
}
If you want to include the Playlist property data as well, you can do that in your projection part.
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new
{
Id = x.Id,
Name = x.Name,
Image = x.Image,
Playlist = x.Playlist
.Select(p=>new
{
Id = p.Id,
Title = p.Title
})
});
return Json(result, JsonRequestBehavior.AllowGet);
}

handle this object datasource on reporting services

If I had a class defined with this attributes
public class GestionesDataSet
{
public DateTime GestionInicio { get; set; }
public DateTime GestionFin { get; set; }
public Nullable<DateTime> LlamadaInicio { get; set; }
public Nullable<DateTime> LlamadaFin { get; set; }
public string Login { get; set; }
public string Tipificacion { get; set; }
public List<CamposGestion> campoValor { get; set; }
}
And the class called CamposGestion is defined like this
public class CamposGestion
{
public string Nombre { get; set; }
public string Valor { get; set; }
}
How can I Defined a report where I can use the field that refers to the list of the other elements?
I tried to used one dataset where I can set this linq as object data source
var gestiones = (from G in db.Gestion
where
G.IDTipificacion == idTipificacion
&& (from T in db.Tipificacion where T.IdTipificacion == G.IDTipificacion select T.Servicio.IDServicio).AsEnumerable().Contains(idServicio)
select G).AsEnumerable().Select(xx => new GestionesDataSet()
{
GestionInicio = xx.HoraInicio,
GestionFin = xx.HoraFin,
#Tipificacion = ((from T in db.Tipificacion select T).Where(x => x.IdTipificacion == xx.IDTipificacion).Count() > 0 ?
(from T in db.Tipificacion where T.IdTipificacion == xx.IDTipificacion select T.Nombre).FirstOrDefault() : ""),
LlamadaInicio = xx.Llamada.HoraInicio,
LlamadaFin = xx.Llamada.HoraFin,
Login = xx.Llamada.Sesion.Usuario.Nombre,
campoValor = xx.CampoValor.Select(aux => new CamposGestion() {
Nombre = aux.ConfiguracionCampo.Campo.Nombre,
Valor = aux.Valor
}).ToList()
}).ToList();
But what I want to see the report the field that contains the List show's an error like this
Any help would be appreciate.
I would rewrite the query like this:
var gestiones =
from xx in db.Gestion
where
xx.IDTipificacion == idTipificacion
&& (from T in db.Tipificacion
where T.IdTipificacion == xx.IDTipificacion select T.Servicio.IDServicio).AsEnumerable().Contains(idServicio)
select new GestionesDataSet()
{
GestionInicio = xx.HoraInicio,
GestionFin = xx.HoraFin,
#Tipificacion = (from T in db.Tipificacion where T.IdTipificacion == xx.IDTipificacion select T.Nombre).FirstOrDefault() ?? "",
LlamadaInicio = xx.Llamada.HoraInicio,
LlamadaFin = xx.Llamada.HoraFin,
Login = xx.Llamada.Sesion.Usuario.Nombre,
campoValor = xx.CampoValor.Select(aux => new CamposGestion()
{
Nombre = aux.ConfiguracionCampo.Campo.Nombre,
Valor = aux.Valor
}).ToList()
}).ToList();
When you call a projection (Select) after the AsEnumerable was called, LINQ will try to get the navigation objects first from the already loaded ones. If no object is loaded, then will execute a select SQL command for each navigation property used in the projection. If the [DeferredLoadingEnabled][1] property is set to false it won't execute any query and if no object is loaded already (they can be loaded "apriori" with [LoadWith][2]) it will give a NullReferenceException. So, in some situations, calling AsEnumerable might hurt performance. All these things are not valid when AsEnumerable is used in the where parts.
For giving a default value, when no Tipificacion doesn't exist, it can be used the null-coalescing operator, from C#, instead of using the Count method, which creates an extra lookup on the the table.
Now.. to your problem.
SSRS doesn't support binding to a list of items. The column campoValor tries to bind to a list of objects, which is not allowed. So either you create a subreport (there is a section which describes this) or you flatten your data (having the all the properties on one single object) and then use the HideDuplicates property

Resources