I have the following in my client but I can't seem to deserialise the json into the UserRoleGetResult
public class WCFRootObject
{
public SignInResult SignInResult { get; set; }
public bool UserIsInRoleResult { get; set; }
public bool ChangePasswordRequiredResult { get; set; }
public UserRoleGetResultWrapper UserRoleGetResult { get; set; }
}
public class UserRoleGetResultWrapper
{
public string[] UserRoleGetResult { get; set; }
}
Here's the json it returns
{
"UserRoleGetResult": [
"MarbleAccess",
"MartinAccess",
"OLBAccess",
"SuperUser",
"Supervisor"
]
}
Is there some documentation I;ve not read which explains how I should of implemented the rootObject?
why?
i guess you are tiring to deserilize the json object into WCFRootObject. please try deserilzing your json into this object:
public class WCFRootObject
{
public SignInResult SignInResult { get; set; }
public bool UserIsInRoleResult { get; set; }
public bool ChangePasswordRequiredResult { get; set; }
public string[] UserRoleGetResult { get; set; }
}
you wrapped the object twice.
Related
I want to use mapbox matching in ASP.NET Core. This link you can get response https://api.mapbox.com/matching/v5/mapbox/driving/..
I want to convert this response to dynamic json in Asp.net core, I use this line
var jsonResponse = JsonConvert.DeserializeObject(mapResponse);
but I get empty values. Any help?
Firstly, The API you have shared I got follwing response using
postman:
If its same what you are getting then I follow below steps to retrive
the value from the API response in C# asp.net core controller
Model You should have :
public class Admin
{
public string iso_3166_1_alpha3 { get; set; }
public string iso_3166_1 { get; set; }
}
public class Leg
{
public List<object> via_waypoints { get; set; }
public List<Admin> admins { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public List<object> steps { get; set; }
public double distance { get; set; }
public string summary { get; set; }
}
public class Matching
{
public double confidence { get; set; }
public string weight_name { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public double distance { get; set; }
public List<Leg> legs { get; set; }
public string geometry { get; set; }
}
public class Tracepoint
{
public int matchings_index { get; set; }
public int waypoint_index { get; set; }
public int alternatives_count { get; set; }
public double distance { get; set; }
public string name { get; set; }
public List<double> location { get; set; }
}
public class MapResponseClass
{
public List<Matching> matchings { get; set; }
public List<Tracepoint> tracepoints { get; set; }
public string code { get; set; }
public string uuid { get; set; }
}
Asp.net core Controller:
public async Task<IActionResult> CallMapAPI()
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256;-117.17298,32.712603;-117.17314,32.71259;-117.17334,32.71254?access_token=pk.eyJ1Ijoibm92ZXJzbWFwIiwiYSI6ImNreTdwc3ppNTE3dzkyb3B2MnVzNXpueTUifQ.csYTL2GKkl99Yqk_TQjr5w");
response.EnsureSuccessStatusCode();
string mapAPIjson = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<MapResponseClass>(mapAPIjson);
}
catch (Exception ex)
{
throw;
}
return data;
}}
Output:
Note:
You should bound your class as per your API response. What I am
assuming of your empty values is you haven't converted the relevant
class accordingly. I hope above steps guided you accordingly.
I am looking for solution my issue... Probably my Shifts class cannot be mapped.
I have entity class Worker:
public class Worker
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(200)]
public string PhotoFilePath { get; set; }
public Workplace Workplace { get; set; }
public int WorkplaceId { get; set; }
public List<Service> Services { get; set; }
public List<Shift> Shifts { get; set; }
public IEnumerable<Worker> ToList()
{
throw new NotImplementedException();
}
}
And model WorkerModel:
public int Id { get; set; }
[Required]
[DisplayName("Imię")]
public string Name { get; set; }
[DisplayName("Nazwisko")]
public string LastName { get; set; }
[Display(Name = "Zdjęcie")]
public IFormFile Photo { get; set; }
public string PhotoFilePath { get; set; }
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int WorkplaceId { get; set; }
public List<ServiceModel> Services { get; set; }
public List<ShiftModel> Shifts { get; set; }
}
My default mapper profile:
//Mapping workers
CreateMap<Worker, WorkerModel>();
CreateMap<WorkerModel, Worker>();
And when I try map model to entity class in my action:
Worker worker = _mapper.Map<Worker>(model);
I get an issue:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
This is caused by different mapping types. Take the property Service as an example.
The resource is a type of Service.
But the destination is a type of ServiceModel.
So, they need to be converted. Here is a demo.
I create the Service and ServiceModel according to your model.
public class Service
{
public int serviceID { get; set; }
public string myservice { get; set; }
}
public class ServiceModel
{
public int serviceID { get; set; }
public string myservice { get; set; }
}
This is mapping relationship.
public class AutomapProfile : Profile
{
public AutomapProfile()
{
CreateMap<Worker, WorkerModel>();
CreateMap<WorkerModel, Worker>()
.ForMember(m => m.Services, x => x.MapFrom(y => y.Services.Select(a=>
new Service
{
serviceID=a.serviceID,
myservice=a.myservice
})));
}
}
This is the mapping method.
public IActionResult Index()
{
var model = new WorkerModel
{
Id=1,
Name="names",
//...
Services = new List<ServiceModel>
{
new ServiceModel{ serviceID=1, myservice="service1"},
new ServiceModel{ serviceID=2, myservice="service2"},
},
//...
};
Worker worker = _mapper.Map<Worker>(model);
return Ok(worker);
}
Result.
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.
I m trying this tutorial: Requesting a Derived Entity Collection
When i make this request:
GET : http://tdd.stooges.com.my/api/paymentAbles?$format=application/json
I get this response:
{
"#odata.context":"http://tdd.stooges.com.my/api/$metadata#paymentAbles",
"value":[
{
"#odata.type":"#EFDB.Topup","id":1
},
{
"#odata.type":"#EFDB.Order","id":7
}
]
}
It is OK. But when i try this request:
GET : http://tdd.stooges.com.my/api/paymentAbles/EFDB.Order?$format=application/json
I get the response 404
I found a similar question on stackoverflow:
WCF Data Service gives 404 when making OData requests for derived types,
but the solution make all http request return 500 internal error.
How can I solve the problem? You can use this site: http://tdd.stooges.com.my for testing (for example using firebug to view teh request/response details).
Update :
modelBuilder.Entity<PaymentAble>()
.Map<Topup>(s => s.Requires("type").HasValue("topup"))
.Map<Order>(m => m.Requires("type").HasValue("order"));
[Table("payment_able")]
public abstract class PaymentAble
{
[Key]
public int id { get; set; }
public double amount { get; set; }
public string code { get; set; }
public string statusEnum { get; set; }
[ForeignKey("member")]
public int member_id { get; set; }
public virtual Member member { get; set; }
public virtual Payment payment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTimeOffset rowCreatedDT { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[ConcurrencyCheck]
public byte[] rowVersion { get; set; }
[ForeignKey("rowCreator")]
public int rowCreatorLoginPerson_id { get; set; }
[ForeignKey("rowLastModifiedBy")]
public int rowLastModifiedByLoginPerson_id { get; set; }
public virtual LoginPerson rowCreator { get; set; }
public virtual LoginPerson rowLastModifiedBy { get; set; }
}
public class Topup : PaymentAble
{
}
public class Order : PaymentAble
{
[Column("order_GSTPercent")]
public double GSTPercent { get; set; }
[Column("order_clientName")]
public string clientName { get; set; }
[Column("order_clientEmail")]
public string clientEmail { get; set; }
[Column("order_clientHp")]
public string clientHp { get; set; }
public virtual List<OrderItem> items { get; set; }
}
[Table("order_item")]
public class OrderItem : RowInfo
{
[Key]
public int id { get; set; }
public int qty { get; set; }
public double amount { get; set; }
[ForeignKey("order")]
public int order_id { get; set; }
public virtual Order order { get; set; }
public virtual OrderCard card { get; set; }
}
public static IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<LoginPerson>("loginPersons");
builder.EntitySet<Admin>("admins");
builder.EntitySet<Member>("members");
builder.EntitySet<Card>("cards");
builder.EntitySet<CardPackage>("cardPackages");
builder.EntitySet<Game>("games");
builder.EntitySet<Img>("imgs");
builder.EntitySet<Currency>("currencys");
builder.EntitySet<Topup>("topups");
builder.EntitySet<Order>("orders");
builder.EntitySet<OrderItem>("OrderItems");
builder.EntitySet<Payment>("payments");
builder.EntitySet<PaymentAble>("paymentAbles");
builder.Namespace = "RPC"; //test only
var gettotalFn = builder.EntityType<PaymentAble>().Collection.Function("getTotal");
gettotalFn.Returns<int>();
return builder.GetEdmModel();
}
config.MapODataServiceRoute("odata", "api", GetModel());
[ODataRoutePrefix("paymentAbles")]
public class PaymentAblesController : BaseController
{
[ODataRoute("")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<PaymentAble> get()
{
return db.paymentAbles;
}
public async Task<IHttpActionResult> getTotal()
{
return Ok(15);
}
}
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; }
}