XAML Binding - Cannot access array item - xaml

I'm trying to bind a property via MVVM pattern.
The payload is something like that:
{
"QualificationSummary": "For all positions individuals must have IT-related experience...",
"PositionRemuneration": [
{
"MinimumRange": "62639.0",
"MaximumRange": "137348.0",
"RateIntervalCode": "PA"
}
]
}
I Tried this, but did nor worked.
<Label>
<Label.Text>
<MultiBinding StringFormat="{}{0}{1}">
<Binding Path="PositionRemuneration[MinimumRange]"/>
<Binding Path="PositionRemuneration[MaximumRange]"/>
</MultiBinding>
</Label.Text>
</Label>
Any clues?

After spend some time understanding the problem, that's the solution.
The c# class:
public Positionlocation[] PositionLocation { get; set; }
public class Positionlocation
{
public string LocationName { get; set; }
public string CountryCode { get; set; }
public string CountrySubDivisionCode { get; set; }
public string CityName { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
}
and to access the property:
<Binding Path="MatchedObjectDescriptor.PositionLocation[0].LocationName"/>

Related

ASP.Net core - make a search inside a nested collection

I'm trying to make a nested collection search and I'm really struggling.
My expected result is: I would like to make a search and find all the powerUp objects by a certain date. (PowerUpDate property - that's the searching criteria)
User Model:
public class AppUser : IdentityUser
{
public ICollection<Hero> Heroes { get; set; }
}
Hero Model:
[Table("Heroes")]
public class Hero
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Ability { get; set; }
[Required]
public string SuitColors { get; set; }
public double CurrentPower { get; set; }
public double StartingPower { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public ICollection<PowerUp> PowerUps { get; set; }
public AppUser AppUser { get; set; }
[Required]
public string AppUserId { get; set; }
}
PowerUp Model:
[Table("PowerUps")]
public class PowerUp
{
public int Id { get; set; }
[Required]
public double PowerUpIncrement { get; set; }
[Required]
public DateTime PowerUpDate { get; set; } = DateTime.Now;
public Hero Hero { get; set; }
[Required]
public int HeroId { get; set; }
}
DataContext:
public class DataContext : IdentityDbContext<AppUser>
{
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Hero>().HasMany(hero => hero.PowerUps).WithOne(powerUp => powerUp.Hero)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<AppUser>().HasMany(user => user.Heroes).WithOne(hero => hero.AppUser)
.OnDelete(DeleteBehavior.Cascade);
}
}
Could someone please explain to me how can I implement such a search on a nested collection?
Inject your AppUser user using Dependency injection
(better use the repository pattern) anyway it should be something like this: user.Heroes.PowerUps.OrderBy(x=>x.PowerUpDate == Datetime.Now).ToList();
x.PowerUpDate == To whatever date you will insert

SignalR (asp.net core) not sending Complex class object

SignalR for some reason fails when I try to send an object from client to be represented in a complex class.
The below client-side code works fine...
connection.send("ABC", "111", "222", { text: "text" }).then(() => console.log("sent")).catch((r) => console.log(r))
...for the below server-side code
public async Task ABC(string a, string b, User c)
{
await Clients.All.SendAsync(RECEIVE, a, b, c);
}
public class User
{
public string Text { get; set; }
public string Name { get; set; }
}
The below doesn't work....
connection.send("ABC", "111", "222", { text: "text", jsonOptions: [] }).then(() => console.log("sent")).catch((r) => console.log(r))
...for the below server side code
public async Task ABC(string a, string b, Post c)
{
await Clients.All.SendAsync(RECEIVE, a, b, c);
}
public class Post
{
public int Id { get; set; }
[Required] [StringLength(450, ErrorMessage = "Sender id cannot be more than 450")]
public string SenderId { get; set; }
[Required] [StringLength(30, ErrorMessage = "Sender name cannot be more than 30")]
public string SenderName { get; set; }
[StringLength(300, ErrorMessage = "Senderpic length must not be more than 300")]
public string SenderPic { get; set; }
public PostLocation PostLocation { get; set; }
public int? CourseId { get; set; }
public int ClassId { get; set; }
public int? ChatId { get; set; }
public int? LectureId { get; set; }
[Required] [StringLength(2000, ErrorMessage = "Post text cannot be more than 2000")]
public string Text { get; set; }
[Required]
public DateTimeOffset TimeStamp { get; set; }
[NotMapped]
public int Upvotes { get; set; }
[NotMapped]
public ICollection<string> UpvoteIds { get; set; }
[NotMapped]
public ICollection<string> DownvoteIds { get; set; }
[NotMapped]
public ICollection<string> StarredIds { get; set; }
public PostType Type { get; set; }
public bool IsReply { get; set; }
[ForeignKey(nameof(FullRepliedPost))]
public int? RepliedId { get; set; }
[NotMapped]
public MiniPost RepliedPost { get; set; }
[StringLength(300, ErrorMessage = "ProfilePicturePath length must not be more than 300")]
public string AttachmentPath { get; set; }
public AttachmentType AttachmentType { get; set; }
public int AnsweredPostId { get; set; }
public Choice CorrectAnswer { get; set; }
public string JsonOptions { get; set; }
[NotMapped]
public ICollection<string> Options => (ICollection<string>)
JsonConvert.DeserializeObject(JsonOptions, typeof(ICollection<string>));
[NotMapped]
public ICollection<string> ASelectionIds { get; set; }
[NotMapped]
public ICollection<string> BSelectionIds { get; set; }
[NotMapped]
public ICollection<string> CSelectionIds { get; set; }
[NotMapped]
public ICollection<string> DSelectionIds { get; set; }
[NotMapped]
public ICollection<string> ESelectionIds { get; set; }
#region navigation properties
[JsonIgnore]
public Post FullRepliedPost { get; set; }
[JsonIgnore]
public ICollection<PostVote> PostVotes { get; set; }
[JsonIgnore]
public ICollection<PostStar> PostStars { get; set; }
[JsonIgnore]
public ICollection<MultiChoice> OptionSelections { get; set; }
[JsonIgnore] [ForeignKey(nameof(RepliedId))]
public ICollection<Post> Replies { get; set; }
#endregion
}
I use the above Post class as a business object, that's why it has all those attributes. I wonder if that has something to do with the failure. I get the below error in Chrome dev tools
[2020-11-07T20:19:42.768Z] Information: Connection disconnected.
and when I try to send again, I get an error saying that I can't send messages when signalR is disconnected.
EDIT: I omitted something in the code I pasted here (jsonOptions: []), which turned out to be the actual cause of the problem.
It turns out the problem was entirely my fault. The JsonOptions property in the entity class should be a string, but I was sending an array from the client. Replacing jsonOptions: [] with jsonOptions: "[]" fixed it and it serialized fine.
Regardless, I've decided to just send the Id of the Post object instead of the whole object. I think it's going to be more efficient that way.

Format list elements in viewmodel

In my viewmodel I have SubscriptionExpires formatted as below
public class IndexViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dddd d MMMM yyyy}")]
public DateTime? SubscriptionExpires { get; set; }
public IEnumerable<Device> Devices { get; set; }
}
Device also includes a date property
public partial class Device
{
[Key]
public int DeviceId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public string DeviceName { get; set; }
public DateTime UnlockedTo { get; set; }
}
Is there any way of setting the date format for UnlockedTo in IndexViewModel or must formatting for this property be done in the view?
View should be responsible for formatting and showing data. Model is responsible just to deliver those data.

Deserialize JSON object to C# object that contains lists

I what to use the Rest Sharp Deserialization but i don't know how to build the right class
The JSON :
{
"LIST_ID":34468,
"CREATED_PERSONAL_FIELDS":[],
"EXISTING_PERSONAL_FIELD_NAMES":[ ["41028","Test1"] , ["41029","Test2"] ]
}
I tried this class:
public class PersonalFieldsAddResponse
{
public string LIST_ID { get; set; }
public List<List<string>> SUBSCRIBERS_CREATED { get; set; }
public List<List<string>> BAD_PERSONAL_FIELDS { get; set; }
}
And this one:
public class PersonalFieldsAddResponse
{
public string LIST_ID { get; set; }
public List<string> SUBSCRIBERS_CREATED { get; set; }
public List<string> BAD_PERSONAL_FIELDS { get; set; }
}
The Deserialization does get me the LIST_ID but i always get NULL at SUBSCRIBERS_CREATED and BAD_PERSONAL_FIELDS.
Any help will be appreciated.
LOL,
it need to be :
public class PersonalFieldsAddResponse
{
public string LIST_ID { get; set; }
public List<List<string>> CREATED_PERSONAL_FIELDS { get; set; }
public List<List<string>> EXISTING_PERSONAL_FIELD_NAMES { get; set; }
}

Json.net fails to deserialize a list of complex types

I'm using json.net to perform handle my json deserialization in a IIS hosted restful service.
First, here are the objects I'm trying to work with.
[DataContract]
public class CreateSamplesRequest
{
[DataMember] public Guid SessionId { get; set; }
[DataMember] public SampleTemplateDTO Template { get; set; }
}
[DataContract]
public class SampleTemplateDTO
{
[DataMember] public int NumberOfSamples { get; set; }
[DataMember] public int CompanyId { get; set; }
[DataMember] public int SampleTypeId { get; set; }
[DataMember] public HmisDTO Hmis { get; set; }
[DataMember] public List<AttributeValueDTO> AttributeValues { get; set; }
}
[DataContract]
public class AttributeValueDTO
{
[DataMember] public int AttributeId { get; set; }
[DataMember] public string AttributeName { get; set; }
[DataMember] public string Value { get; set; }
}
[DataContract]
public class HmisDTO
{
[DataMember] public string Health { get; set; }
[DataMember] public string Flammability { get; set; }
[DataMember] public string Reactivity { get; set; }
[DataMember] public string Equipment { get; set; }
}
The help page asks for json in this format for the CreateSamplesRequest
{
"SessionId":"1627aea5-8e0a-4371-9022-9b504344e724",
"Template":{
"NumberOfSamples":2147483647,
"CompanyId":2147483647,
"SampleTypeId":2147483647,
"Hmis":{
"Health":"String content",
"Flammability":"String content",
"Reactivity":"String content",
"Equipment":"String content"
},
"AttributeValues":[{
"AttributeId":2147483647,
"AttributeName":"String content",
"Value":"String content"
}]
}
}
And this is what I'm actually sending:
{
"SessionId":"17aaec11-be28-4536-b5df-d98fbda91e91",
"Template":{
"NumberOfSamples":1,
"CompanyId":1,
"SampleTypeId":9,
"Hmis":{
"Health":"2",
"Flammability":"0",
"Reactivity":"0",
"Equipment":"E",
},
"AttributeValues":[
{"AttributeId":1,"AttributeName":"Item No.","Value":"MN0002NG"},
{"AttributeId":2,"AttributeName":"Lot No.","Value":"C4526"}
]
}
}
The problem I'm having is that the AttributeValues property of the SampleTemplateDTO object always ends up being ignored. With the above code, it will be null. If I instanciate it to a empty List<AttributeValueDTO> it will be an empty list. I've been banging my head against this for a few hours.
I've tried creating a service that just takes a List<AttributeValueDTO> and it works fine. I've tried creating a wrapper class for the AttributeValues and it still ends up as null. I'm completely stumped. Any ideas?
MOTHER OF GOD, I JUST WASTED 5 FREAKING HOURS ON A FREAKING COMMA. The trailing comma in the HMIS section was apparently telling json.net to stop parsing at that point.
When I submit this json:
{
"SessionId":"17aaec11-be28-4536-b5df-d98fbda91e91",
"Template":{
"NumberOfSamples":1,
"CompanyId":1,
"SampleTypeId":9,
"Hmis":{
"Health":"2",
"Flammability":"0",
"Reactivity":"0",
"Equipment":"E"
},
"AttributeValues":[
{"AttributeId":1,"AttributeName":"Item No.","Value":"MN0002NG"},
{"AttributeId":2,"AttributeName":"Lot No.","Value":"C4526"}
]
}
}
Everything works great.