De serialize the JSON data in wpf - wpf

I have a url which return's json data in the following way
{"title":"Test Title","image_url":"http://i.imgur.com/aZO5Kol.jpg","random_window":2,"windows":{"1":{"title":"Random 1"},"2":{"title":"Other Window 2"}},"thankyou_url":"http://google.com"}
Now i want to De-serialize this so that i can write the conditions based on the data received.
I want achieve this
will have to print the image and Name which is received through JSON. And based on the number of windows i should show the windows
I have declared a class
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
string[] windows { get; set; }
string thankyou_url { get; set; }
}
and i have written like this
WebClient objWebClient = new WebClient();
var jss = new JavaScriptSerializer();
string strJsonURL = "url";
var vJsondata = string.Empty;
vJsondata = objWebClient.DownloadString(strJsonURL);
var data = jss.Deserialize<object>(vJsondata);
try
{
var x = ((IList)data).Cast<object>().Select(o => o.ToString()).ToList();
}
But getting this error:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'System.Collections.IList'.

It appears that windows is a Dictionary and not a string array as you have defined in JsonData. You'll have to test this but from what I can tell it should be more like this:
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
Dictionary<string, WindowData> windows { get; set; }
string thankyou_url { get; set; }
}
public class WindowData
{
string title { get; set; }
}

Related

Receive file in Dictionary<string,IFormFile>

I'd like to receive files with special name - currently I have model like this:
public class SampleResultModel : SampleResult
{
public Dictionary<int, LayoutData> DataLayout { get; set; }
.
.
.
}
public class LayoutData
{
public int LayoutId { get; set; }
public Dictionary<string, string> Data { get; set; }
public Dictionary<string, string> Limits { get; set; }
public Dictionary<string, IFormFile> Attachments { get; set; }
public string DataType { get; set; }
public LayoutData() { }
}
Currently I'm able to receive any string data without problems with choosen structure, but when I need to receive files, then the "Attachments" property is always null.
Sent data:
dataLayout[0][layoutId]:
1101
dataLayout[1][layoutId]:
5
dataLayout[1][data][Conclusion]:
dataLayout[1][data][Result]:
1
dataLayout[0][Attachments][0]:
(binary)
dataLayout[0][Attachments][1]:
(binary)
What am I missing?
EDIT:
Tested also:
public List<IFormFile> Attachments { get; set; }
and still null and :
public class LayoutData
{
public int LayoutId { get; set; }
public Dictionary<string, string> Data { get; set; }
public Dictionary<string, string> Limits { get; set; }
public IFormFile Attachments { get; set; }
public string DataType { get; set; }
public LayoutData() { }
}
sent data:
dataLayout[0][layoutId]:
1101
dataLayout[1][layoutId]:
5
dataLayout[1][data][Conclusion]:
dataLayout[1][data][Result]:
1
dataLayout[0][attachments]:
(binary)
but data is still null...

Invalid column name exception thrown in .NET Core web api

I have two classes in my database which are defined as classes, fed into entity and then called from the API
The full method is below for the calls. The first call works fine, the second throws the exception
public async Task<ActionResult<List<QuizForms>>> GetQuiz([FromQuery]string id)
{
var form = await _context.QuizForms.Where(t=>t.QuizId == id).ToListAsync();
if (form == null)
{
return NotFound();
}
var elem = new List<Element>();
foreach(var e in form)
{
var data = await _context.Element.Where(t => t.ElementId == e.ElementId).ToListAsync();
elem.AddRange(data);
e.Element.AddRange(elem);
}
return form;
}
When the var data line is hit, an excception is thrown
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'QuizFormsFormId'.
It looks like the name of the class and column name are being concatenated and the used as the query parameter.
The two classes look like this
public class QuizForms
{
[Key]
public int FormId { get; set; }
public string QuizId { get; set; } = "";
#nullable enable
public string? Title { get; set; }
public int? ElementId { get; set; }
public List<Element>? Element { get; set; }
public int? PreviousId { get; set; }
public int? NextId { get; set; }
#nullable disable
}
and
public class Element
{
[Key]
public int Id { get; set; }
public int ElementId { get; set; }
#nullable enable
public int? MathsId { get; set; }
public int? QuestionId { get; set; }
public int? InformationId { get; set; }
public int? AnswerId { get; set; }
#nullable disable
public string QuizId { get; set; } = "";
}
Is it because I'm not using Id for the primary key or do I need to do something else so the class and property aren't concatented like this?

AutoMapper with Array and JsonApiSerializer.JsonApi.Relationship

I have an AppService solution with the following Classes and i want to map from the SourceObject to the DestinationObject
Source Classes
public class SourceObject
{
public string Id { get; set; }
public string Name { get; set; }
public JsonApiSerializer.JsonApi.Relationship<SourceChildObject[]> childObjects { get; set; }
}
public class SourceChildObject
{
public string Id { get; set; }
public string type { get; set; }
}
Destination Classes
public class DestinationObject
{
public string Id { get; set; }
public string Name { get; set; }
public JsonApiSerializer.JsonApi.Relationship<DestinationChildObject[]> childObjects { get; set; }
}
public class DestinationChildObject
{
public string Id { get; set; }
public string type { get; set; }
}
Auto mapper is setup in the sartup class
services.AddAutoMapper(typeof(EntityMappingProfile));
And my mapping class loos like this
public class EntityMappingProfile : Profile
{
public EntityMappingProfile()
{
CreateMap<SourceObject, DestinationObject>();
CreateMap<Relationship<SourceChildObject[]>, Relationship<DestinationChildObject[]>>();
}
}
When i execute the solution all fields are mapped apart form the array field of type JsonApiSerializer.JsonApi.Relationship. The destination field is null. What am i doing wrong?
You forgot about creating a map between SourceChildObject and DestinationChildObject. Add this line to your EntityMappingProfile.
CreateMap<SourceChildObject, DestinationChildObject>();
And one more thing, when you are mapping generic types, you can enable mapping for all types with:
CreateMap(typeof(Relationship<>), typeof(Relationship<>));
instead of creating a map with concrete use case of a generic type.

A circular reference was detected while serializing an object of type in AngularJs and asp.net mvc

Well I know it is well known error. There are lots of questions asked here. But after going through few questions I am not able to solve my problem I am getting this error my website.
This is my error
A circular reference was detected while serializing an object of type
My Controller Code is
[HttpGet]
public JsonResult Get(int currentPage, int recordsPerPage)
{
var pageNumber = currentPage;
var pageSize = recordsPerPage;
var begin = (pageNumber - 1) * pageSize;
var totalNumberOfRecords = db.Products.Count();
var productlist = db.Products.OrderBy(r => r.ProductID).Skip(begin).Take(pageSize).ToList();
db.Configuration.ProxyCreationEnabled = false;
//var productlist = db.Products.ToList();
var product = new { Product = productlist, TotalRecords = totalNumberOfRecords };
return Json(new { Products = productlist, RecordCount = totalNumberOfRecords }, JsonRequestBehavior.AllowGet);
}
My Angular Controller Code is this
function GetProducts() {
var productResult = productService.getProduct($scope.currentPage, $scope.recordsPerPage);
productResult.then(function (result) {
console.log("d",data);
if (result.data != '' || result.data != null) {
if (result.data != null || result.data != '') {
$scope.Products = result.data;
}
else if (result.data = 0) {
$scope.message = "No Product Found"
}
}
});
};
And Angular Service code is this
this.getProduct = function (currentPage, recordsPerPage) {
return $http.get('/Home/Get?currentPage=' + currentPage + '&recordsPerPage=' + recordsPerPage);
// return $http.get('/Home/Get');
};
I am missing something but I am unable to get that. Any expert please help me in this.. I spend my whole night with this error. I try every solution of stackoverflow which I read but nothing works for me
Here is My Model
namespace StylesStore.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.Carts = new HashSet<Cart>();
this.OrdersDetails = new HashSet<OrdersDetail>();
}
public int ProductID { get; set; }
public Nullable<int> SKU { get; set; }
public Nullable<int> VendorProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Nullable<int> MSRP { get; set; }
public Nullable<int> AvailableSize { get; set; }
public string AvailableColor { get; set; }
public Nullable<int> Size { get; set; }
public string Color { get; set; }
public Nullable<int> Discount { get; set; }
public Nullable<int> UnitWeight { get; set; }
public Nullable<int> UnitsInStock { get; set; }
public string UnitsInOrder { get; set; }
public string Picture1 { get; set; }
public string Picture2 { get; set; }
public string Picture3 { get; set; }
public string Picture4 { get; set; }
public Nullable<decimal> ShippingCharges { get; set; }
public string Note { get; set; }
public Nullable<bool> InStock { get; set; }
public Nullable<int> CatID { get; set; }
public Nullable<decimal> wieght { get; set; }
public Nullable<int> totalview { get; set; }
public Nullable<int> Disable { get; set; }
public Nullable<System.DateTime> EntryDate { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<OrdersDetail> OrdersDetails { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
You should not serialize your entity objects. Your entity objects have virtual navigation properties which are detected by JsonSerializer. JsonSerializer thinks they are embedded properties of that object and tries to serialize them too. and this goes on. serializer finds itself trying to serialize all database. this is why your error occurs.
You should either mark fields that need to be serialized or use DTO's to serialize objects.
Note: you can use AutoMapper to map objects between Entity and DTO

Web ApI Entity Framework (Code First) Value not appearing in database

My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL".
I have a reports and a bookings tables.
This is the code for the reports:
public class Report
{
public Report()
{
Injuries = new List<Injury>();
this.Bookings = new HashSet<Booking>();
}
public int Id { get; set; }
public string Club1 { get; set; }
public string Club2 { get; set; }
public virtual ICollection<Injury> Injuries { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings:
public class Booking
{
//public Booking()
//{
// Reports = new List<Report>();
//}
public int Id { get; set; }
public string Club { get; set; }
public string PlayerName { get; set; }
public string PlayerNumber { get; set; }
public string Reason { get; set; }
public string Description { get; set; }
//public int? Report_Id { get; set; }
public Nullable<int> Report_Id { get; set; }
public virtual Report Report { get; set; }
//public virtual ICollection<Report> Reports { get; set; }
}
Controller:
//POST: api/Reports
[ResponseType(typeof(Report))]
public async Task<IHttpActionResult> PostReport(Report report)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Reports.Add(report);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
}
I put the test information via Postman:
I'm not sure why Report_Id is showing as it's not required, however, Report_Id1 is the field that is connecting the Report and Booking together.
Since your foreign key doesn't follow convention (ReportId), you need to use the annotation [ForeignKey] or a fluent api configuration:
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Report)
.WithMany(b => b.Bookings)
.HasForeignKey(p => p.Report_Id);
That is why EF is adding the second Report_ID1. https://msdn.microsoft.com/en-us/data/hh134698.aspx

Resources