LINQ to SQL query containing joins resulting in class that contains arrays, - c#

I'm currently working on a minecraft-like game. All-terrain data is stored in SQLite. I have 3 tables that should be joined by one SQL Query using LINQ to List theMother. Tables are:
public class Chunks {
[PrimaryKey]
public int Id { get; set; }
[Indexed]
public double X { get; set; }
[Indexed]
public double Y { get; set; }
public int Resolution { get; set; }
public float Size { get; set; }
public bool isBackground { get; set; }
}
public class Cell{
[PrimaryKey]
public int Id { get; set; }
public long GlobalX { get; set; }
public long GlobalZ { get; set; }
public long PivotX { get; set; }
public long PivotZ { get; set; }
public short Size { get; set; }
public double Random { get; set; }
public int ChunkPlotType { get; set; }
public bool isCommercial { get; set; }
public bool isFarming { get; set; }
public int BiomeType { get; set; }
public short Height { get; set; }
[Indexed]
public int ChunkOwnerId { get; set; }
}
public class Heightmap {//4225 rows for every chunk
[PrimaryKey]
public int Id { get; set; }
[Indexed]
public int ChunkOwnerId { get; set; }
public float Height { get; set; }
}
public class TheMotherOfAll {
public float CoordX;
public float coordY;
public Cell[] cells;
public float[] heightmap;
}
I think the final query should look like this:
public void Load(){
List<TheMotherOfAll> theMother = new List<TheMotherOfAll>(
from rowChunks in dbManager.Table<Chunks>()
join rowCells in dbManager.Table<Cell>()
where rowChunks.X > 100 && rowChunks.X < 200//for example
select rowChunks.X as theMother.CoordX, rowChunks.Y as theMother.CoordY
on rowChunks.id equals rowCells.ChunkOwnerId
//How to continue I don't know
)
}

Related

C# Linq set merged lists as datasource

I'm currently merging to lists will be the datasource of a gridview. This is my code:
// Get models
var products = await API.Zelkon.Products.GetAll();
var productsCurrencies = await API.Zelkon.CurrenciesBackend.Get();
// Merge lists
var results = products.Item1.Zip(productsCurrencies.Item1, (x, y) => new Tuple<Models.Products, Models.Zelkon.CurrenciesBackend>(x, y));
// Create datasource
var datasource = results.Select(r => new { r.Item2.price, r.Item2.setup_fee, r.Item1.product_number });
GridProducts.DataSource = datasource;
// GridProducts.VisibleColumns("name");
UI.CustomizeGridDefault(GridProducts);
My problem is that the value of r.Item2.setup_fee is always the value of the first row. I have checked the collection and the data is correct there.
Am I doing something wrong?
Below are the structures:
class CurrenciesBackend
{
public string currency_name { get; set; }
public string currency_code { get; set; }
public double price { get; set; }
public double recommended_price { get; set; }
public double setup_fee { get; set; }
public int product_number { get; set; }
}
class Products
{
public string name { get; set; }
public string description { get; set; }
public string invoice_layout { get; set; }
public string layout_number { get; set; }
public string payment_terms_name { get; set; }
public string payment_terms_number { get; set; }
public DateTime creation_date { get; set; }
public int enabled { get; set; }
public int is_subscription { get; set; }
public int is_delivery_required { get; set; }
public int allow_discount { get; set; }
public int allow_trial { get; set; }
public int max_discount { get; set; }
public int max_discount_duration { get; set; }
public int vat_percentage { get; set; }
public int trial_period { get; set; }
public int binding_period { get; set; }
public int days_of_credit { get; set; }
public int unit { get; set; }
public string allowed_country_codes { get; set; }
public int product_number { get; set; }
public int authorize_invoice { get; set; }
}
Thanks in advance

MongoDB wont let me save Object possible circular reference

I am trying to save to the database the updated Account details object which contains a list of Player objects in it.
public class AccountDetails {
public String Id { get; set; }
public String Username { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String Token { get; set; }
public int PremiumDays { get; set; }
public List<Player> Players { get; set; }
public String LastLogin { get; set; }
public int AdminLevel { get; set; }
public int Banned { get; set; }
public int Muted { get; set; }
It seems to get this error on the Players part,
MongoDB.Bson.BsonSerializationException: 'Maximum serialization depth exceeded (does the object being serialized have a circular reference?).'
I have looked through the references for Player and the inherited GameObj but I cannot seem to find what might be causing this circular reference,
This is my Player Object,
public PlayerClass Class { get; set; }
public int Level { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public List<Skill> Skills { get; set; }
public List<ArchewoodGameServer.core.Shared.Utils.Attribute> Attributes { get; set; }
public int AttributePoints { get; set; }
public int CurrentHealth { get; set; }
public int MaxHealth { get; set; }
public int CurrentMana { get; set; }
public int MaxMana { get; set; }
public int CurrentExp { get; set; }
public int MaxExp { get; set; }
[JsonIgnore]
public List<Node> Path = new List<Node>();
[JsonIgnore]
public int PathCount = 0;
[JsonIgnore]
public int HealthTick = 0, AttackTick = 10000, AnimTick = 0, MaxAnimTick = 20;
public float AttackSpeed { get; set; }
public ushort AttackRange { get; set; }
and this is my GameObj class,
public string Id { get; set; }
public float X { get; set; }
public float Y { get; set; }
public int O { get; set; }
public int A { get; set; }
public int T { get; set; }
public float S { get; set; }
[JsonIgnore]
public Instance Instance { get; set; }
[JsonIgnore]
public string InstanceID { get; set; }
[JsonIgnore]
public List<String> playerInteractions = new List<string>();
[JsonIgnore]
public int LastProcessedSequence { get; set; }
public string TargetEntity { get; set; }
public ushort PrivateId { get; set; }
The [JsonIgnore] were not working with mongos parser so I changed the structure to not rely on these tags and it was resolved.
I resolved problem in our core project on this way.
'
using Newtonsoft.Json;
using AutoMapper;
var stringContent = JsonConvert.SerializeObject(_mapper.Map<DataDTO>(newdata), new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }).ToString();
_mongoService.Save(JsonConvert.DeserializeObject<DataDTO>(stringContent));
//mongo service save method
public async void Save(DataDTO dataDTO)
{
await collection.InsertOneAsync(dataDTO));
}
'

Extracting JSON data Xamarin

I am working a Xamarin.Forms App that uses the Azure Face API. With this API you retrieve a JSON response (See Below).
I want to extract the gender of the person in the image but am having trouble with it as I am very new to this.
I extract the full JSON response into a string but I would like to be able to extract data such as the 'Gender' or the 'Age' of the person in the image.
[{"faceId":"9448dfe4-afb6-4557-94fe-010fc439ff36","faceRectangle":{"top":635,"left":639,"width":789,"height":789},"faceAttributes":{"smile":0.187,"headPose":{"pitch":0.0,"roll":-1.6,"yaw":-7.9},"gender":"male","age":34.6,"facialHair":{"moustache":0.5,"beard":0.6,"sideburns":0.6},"glasses":"NoGlasses","emotion":{"anger":0.0,"contempt":0.69,"disgust":0.0,"fear":0.0,"happiness":0.187,"neutral":0.12,"sadness":0.002,"surprise":0.0},"blur":{"blurLevel":"low","value":0.15},"exposure":{"exposureLevel":"overExposure","value":0.85},"noise":{"noiseLevel":"medium","value":0.42},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.02,"invisible":false,"hairColor":[{"color":"brown","confidence":1.0},{"color":"black","confidence":0.95},{"color":"other","confidence":0.22},{"color":"blond","confidence":0.11},{"color":"gray","confidence":0.05},{"color":"red","confidence":0.04}]}}}]
This is how I set the JSON data to a string.
string contentString = await response.Content.ReadAsStringAsync();
You usually want to create a class that represents your response e. g. Person. Then you could use the Newtonsoft.Json nuget package to deserialize the object.:
var person = JsonConvert.DeserializeObject<Person>(contentString);
Now you can access the values like:
person.Gender
Using Newtonsoft.Json:
var results = JsonConvert.DeserializeObject<AzureFace>(contentString);
Debug.WriteLine(results.faceAttributes.age);
C# Model Used (via http://jsonutils.com)
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class HeadPose
{
public double pitch { get; set; }
public double roll { get; set; }
public double yaw { get; set; }
}
public class FacialHair
{
public double moustache { get; set; }
public double beard { get; set; }
public double sideburns { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class Blur
{
public string blurLevel { get; set; }
public double value { get; set; }
}
public class Exposure
{
public string exposureLevel { get; set; }
public double value { get; set; }
}
public class Noise
{
public string noiseLevel { get; set; }
public double value { get; set; }
}
public class Makeup
{
public bool eyeMakeup { get; set; }
public bool lipMakeup { get; set; }
}
public class Occlusion
{
public bool foreheadOccluded { get; set; }
public bool eyeOccluded { get; set; }
public bool mouthOccluded { get; set; }
}
public class HairColor
{
public string color { get; set; }
public double confidence { get; set; }
}
public class Hair
{
public double bald { get; set; }
public bool invisible { get; set; }
public IList<HairColor> hairColor { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public HeadPose headPose { get; set; }
public string gender { get; set; }
public double age { get; set; }
public FacialHair facialHair { get; set; }
public string glasses { get; set; }
public Emotion emotion { get; set; }
public Blur blur { get; set; }
public Exposure exposure { get; set; }
public Noise noise { get; set; }
public Makeup makeup { get; set; }
public IList<object> accessories { get; set; }
public Occlusion occlusion { get; set; }
public Hair hair { get; set; }
}
public class AzureFace
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}

String or binary data would be truncated.The statement has been terminated while removing data

I have a PriceId and I get some PriceGaranties by it and I am trying to delete PriceGaranties by updating Price and see this error.
Here is the code:
public void DeletePriceGaranties(int priceId)
{
var deletedPriceGaranties = context.PriceGaranties.Where(p => p.PriceId == priceId).ToList();
foreach (var priceGaranty in deletedPriceGaranties)
{
context.PriceGaranties.Remove(priceGaranty);
context.SaveChanges();
}
}
The error is:
String or binary data would be truncated. The statement has been
terminated.
Update
Here are the models:
public class Price
{
public int PriceId { get; set; }
public int ProductId { get; set; }
public int ClassId { get; set; }
public int ClassPartnerId { get; set; }
public int UserId { get; set; }
public decimal Cost { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public DateTime LastUpdate { get; set; }
public bool Enable { get; set; }
public int CostTypeId { get; set; }
public int Value { get; set; }
public Class Class { get; set; }
public Product Product { get; set; }
public User User { get; set; }
public List<OldPrice> OldPrices { get; set; }
public List<PriceColor> PriceColors { get; set; }
public List<PriceGaranty> PriceGaranties { get; set; }
public ClassPartner ClassPartner { get; set; }
}
public class PriceGaranty
{
public int PriceGarantyId { get; set; }
public int PriceId { get; set; }
public int GarantyId { get; set; }
public Comparing.Model.Price.Price Price { get; set; }
}
And all of string types are nvarchar(MAX).
You have specified the length of the string in your database to be shorter than what you are trying to add to it. E.g. you may have set a varchar length in your database to be of length 10 but the string you want to add is 11, 15, 20 etc characters. The database doesnt know what to do with it so it just cuts off the excess characters. Try setting the field length in your database to a larger length.

Cannot Serialize JSON

I am trying to access data from a json at this url : http://na.lolesports.com/api/gameStatsFantasy.json?tournamentId=104.
I used a website called http://json2csharp.com/ to help create classes to serialize. It worked but I noticed the JSON had many duplicate instances of the same gameID, playerID and teamID(e.g one named Game2998 and Game29982 or team4 and team42).
public class RootObject
{
public TeamStats teamStats { get; set; }
public PlayerStats playerStats { get; set; }
}
public class TeamStats
{
public Dictionary<string, Game> GameID { get; set; }
}
public class PlayerStats
{
public Dictionary<string,game> gameID { get; set; }
}
public class Game
{
public string dateTime { get; set; }
public Team blueTeam { get; set; }
public Team purpleTeam { get; set; }
public string matchId { get; set; }
}
public class game
{
public string dateTime { get; set; }
public string matchId { get; set; }
public Player bluePlayer1 { get; set; }
public Player bluePlayer2 { get; set; }
public Player bluePlayer3 { get; set; }
public Player bluePlayer4 { get; set; }
public Player bluePlayer5 { get; set; }
public Player purplePlayer1 { get; set; }
public Player purplePlayer2 { get; set; }
public Player purplePlayer3 { get; set; }
public Player purplePlayer4 { get; set; }
public Player purplePlayer5 { get; set; }
}
public class Player
{
public int playerId { get; set; }
public int kills { get; set; }
public int deaths { get; set; }
public int assists { get; set; }
public int minionKills { get; set; }
public int doubleKills { get; set; }
public int tripleKills { get; set; }
public int quadraKills { get; set; }
public int pentaKills { get; set; }
public string playerName { get; set; }
public string role { get; set; }
}
public class Team
{
public int teamId { get; set; }
public string teamName { get; set; }
public int matchVictory { get; set; }
public int matchDefeat { get; set; }
public int baronsKilled { get; set; }
public int dragonsKilled { get; set; }
public int firstBlood { get; set; }
public int firstTower { get; set; }
public int firstInhibitor { get; set; }
public int towersKilled { get; set; }
}

Categories