Issue for nested child list for Swagger - c#

I'm developing a web api with .NET Core
I use Swagger for API documentation
For an endpoint i have a return object like this
public class TaxonomyNode
{
public int Id { get; set; }
public string Key { get; set; }
public string Title { get; set; }
public string ParentKey { get; set; }
public bool HasAssociations { get; set; }
public int Level { get; set; }
public IEnumerable<TaxonomyNode> Children { get; set; }
}
When i launch my web application on swagger page and expland my API endpoint swagger give me this error
Resolver error at paths./api/Taxonomies/{idTaxonomyItemDbMaster}/GetNodes.get.responses.200.content.application/json.schema.properties.children.items.$ref
Could not resolve reference:
Resolver error at paths./api/Taxonomies/{idTaxonomyItemDbMaster}/GetNodes.get.responses.200.content.text/json.schema.properties.children.items.$ref
Could not resolve reference:
Resolver error at paths./api/Taxonomies/{idTaxonomyItemDbMaster}/GetNodes.get.responses.200.content.text/plain.schema.properties.children.items.$ref
Could not resolve reference:
the problem is
public IEnumerable Children { get; set; }
i think that swagger go into an overflow when generating documentation for response
How can i prevent this?
thanks

Your model of type TaxonomyNode is refering to the type TaxonomyNode as a property.
Therefore it will cause a infinite loop if you wish to serialize this type.
It is the cause of the error you are getting

Related

How to map Syncfusion Blazor QueryBuilder rules from C# class

I am trying to implement the Syncfusion Blazor QueryBuilder component to build dynamic search filters.
I can successfully store query builder rules to my DB after mapping to my C# class model.
But when I try to re-map these rules back to the Syncfusion "RuleModel" class I get error below in the browser.
It appears to be caused by the dynamic property types on the "Operate" and "Value" fields.
When I get the error, these properties have the "ValueKind" element. When this is not present, it works fine (eg. If I manually create a new RuleModel())
Error in Browser, when QueryBuilderObj.SetRules() method is called..
Error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'System.Text.Json.JsonElement' to 'string'
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Syncfusion.Blazor.QueryBuilder.Internal.QueryBuilderRules`1.SetField()
at Syncfusion.Blazor.QueryBuilder.Internal.QueryBuilderRules`1.OnParametersSetAsync()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
Client Code
<SfQueryBuilder TValue="#FilterColumns" #ref="QueryBuilderObj" MaxGroupCount=3>
<QueryBuilderColumns>
<QueryBuilderColumn Field="Status" Label="Status" Type="ColumnType.String"></QueryBuilderColumn>
<QueryBuilderColumn Field="DepartmentCode" Label="DepartmentCode" Type="ColumnType.String"></QueryBuilderColumn>
</QueryBuilderColumns>
</SfQueryBuilder>
<button type="button" #onclick="getRules">Get Rules</button>
#code {
SfQueryBuilder<FilterColumns> QueryBuilderObj;
public class FilterColumns
{
public string Status { get; set; }
public string DepartmentCode { get; set; }
}
[Parameter]
public RuleModel rules { get; set; }
private void getRules()
{
QueryBuilderObj.SetRules(rules.Rules, rules.Condition);
}
}
Syncfusion RuleModel Class
public class RuleModel
{
public RuleModel();
public string Condition { get; set; }
public string Field { get; set; }
public string Label { get; set; }
public bool? Not { get; set; }
public dynamic Operator { get; set; }
public string Type { get; set; }
public dynamic Value { get; set; }
public List<RuleModel> Rules { get; set; }
}
I have replicated the syncfusion RuleModel class exactly as above in my domain model.
Has anyone successfully stored and retrieved QueryBuilder rules from Blazor UI into a C# model/class?
Thanks.
I figured out this problem is due to System.Text.Json behaviour causing the newly created property to have a ValueKind object on each property.
Basically this problem... How do I get System.Text.Json to deserialize objects into their original type?
When I switch to using NewtonSoft JSON.NET to de-serialize the RuleModel, it solved the issue.
Not sure how to make it work with System.Text.Json - but will use Json.Net for now.

Sessions in .net6 after upgrading from .net4.8

I just upgraded my .net 4.8 MVC web app to .net6.
I used Sessions to store objects.
for example the User class:
public class User
{
[Key]
public string UserID { get; set; }
public string TenantId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobilePhone { get; set; }
public bool IsEnabled { get; set; }
public virtual ICollection<Department> Departments { get; set; }
}
This is how I set the session:
Session[Consts.CURRENTUSER] = userFromDb;
This is how I use it:
User _currentUser = Session[Consts.CURRENTUSER] as User;
Now, after the upgrade it does not compile. I get the following error:
Error CS0103 The name 'Session' does not exist in the current context
If i use the following HttpContext.Session[Consts.CURRENTUSER] as User it still does not allow the the above use.
Will appreciate an example on how I will be able to use the above scenario in .net core.
after reading Microsoft docs, I followed this guide from step 4 to allow the usage of Sessions.
Then, in order to use complex objects in .net core I followed this link which provided an extension method that implementing the use of complex objects in sessions.

.net core : incomplete JSON response

I'm trying to build simple API for training, in my database I got users (firstname, lastname, email password, list<sports>) and sports ( name, userID).
All is okay when I want to get my users, I got an object populated with sports. But the JSON response is incomplete, it is "cut" in the middle.
[{"firstName":"Nicolas","lastName":"Bouhours","email":"n.bouh#test.com","password":"nico#hotmail.fr","sports":[{"name":"Trail","userId":1
This is my controller :
// GET: api/Users
[HttpGet]
public IEnumerable<User> GetUsers()
{
var users = _context.Users.Include(u => u.Sports).ToList();
return users;
}
And my models :
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
public class SportAppContext : DbContext
{
public SportAppContext(DbContextOptions<SportAppContext> options) : base(options)
{ }
public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
}
I really don't understand what happen, if you have any idea
I'm running into the same issue right now. You can also change the JSON serialization/configuration settings to ignore self-reference loops, as shown in the accepted answer for this question
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
I had this problem to in one of my projects. This is caused by a self referencing loop.
You need to create some sort of DTO (Data Transfer Object) which will be used to generate your JSON.
In your DTO you remove the inverse relationship so you end up having something like
public class SportDto
{
public string Name { get; set; }
}
public class UserDto
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<SportDto> Sports { get; set; }
}
You then map your user User and Sport models to your UserDto and SportDto
A good tool for doing this mapping is AutoMapper. You can read the docs to see how to get started.
After the mapping is done, you Send the DTOs as your JSON and not your models.
Just to add another yet unique scenario where this can occur. This can also happen if your DAL is returning queryables. In my scenario, I was returning a boxed object from the DAL and had something like this as a linq query
...
RootLevelProp1 = "asd",
RootLevelProp2 = "asd",
Trades = b.Trades.OrderBy(c => c.Time).Select(c => new
{
c.Direction,
c.Price,
c.ShareCount,
c.Time
}) //<---- This was being returned as a queryable to the controller
The Trades query was never being executed even though it's root object had .ToListAsync() called on it. What was happening was that the controller would return the result but only up to the Trades section and the Json would not be terminated properly. I then realized an exception was being caught in some custom middleware I wrote in which it was complaining about the data reader already being open. Without going to deep into my investigation, I assumed it had to do something with the DI and how it was handling the lifecycle of the context. The fix was to just add ToList on the trades. It's an ugly way to pass data from the DAL but this is just a fun project.
In my case this solve my issue on core 3, by using Newtonsoft:
https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.0#add-newtonsoftjson-based-json-format-support
Prior to ASP.NET Core 3.0, the default used JSON formatters
implemented using the Newtonsoft.Json package. In ASP.NET Core 3.0 or
later, the default JSON formatters are based on System.Text.Json.
Support for Newtonsoft.Json based formatters and features is available
by installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet
package and configuring it in Startup.ConfigureServices.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
The selected answer was correct in my case as well, my JSON response was getting truncated by a reference loop in my JSON response, and setting ReferenceLoopHandling.Ignore did indeed solve my issue. However, this is not the best solution in my opinion, as this maintains the circular references in your model. A better solution would use the [JsonIgnore] attribute within the model.
The issue in your model is here:
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
public User User { get; set; } //This is the cause of your circular reference
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
As you can see, your User navigation property is where this response is truncated. Specifically, it will cause each Sport in the json response to contain all of the user information for each sport entry in the response. Newtonsoft does not like this. The solution is to simply [JsonIngore] the navigation properties that cause this circular reference. In your code this would be:
public class Sport : BaseEntity
{
public string Name { get; set; }
public int UserId { get; set; }
[JsonIgnore]
public User User { get; set; } //fixed
}
public class User : BaseEntity
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public List<Sport> Sports { get; set; }
}
Faced similar issue, response was getting truncated. Issue was a getter method which trying to formatting date.

object collision with wcf

Could someone explain why this is happening, I have a C# backend that I'm connecting to via WCF. In the back end, i have two classes in the same namespace that have two properties that have the same name. These classes are used in a separate object. The types of the properties are different, one is a string and one is an object but there seems to be some sort of collision when deserializing the object?
It's returning this random error when I call to return the object.
This could be due to the service endpoint binding not using the HTTP
protocol. This could also be due to an HTTP request context being aborted by
the server (possibly due to the service shutting down). See server logs for
more details.
Here are the classes, the property causing the problem is BCIssued
public class Activities
{
public string ApplicationReceived { get; set; }
public string PIMGranted { get; set; }
public Bcgranted[] BCGranted { get; set; }
public object CCCGranted { get; set; }
// public object BCIssued { get; set; }
public object CCCIssued { get; set; }
}
public class CCC
{
public string BCIssued { get; set; }
public string FinalIns { get; set; }
public string LapsedMonths { get; set; }
public object WorkStarted { get; set; }
public object Notified { get; set; }
public object Lapsed { get; set; }
public object Extension { get; set; }
}
Thanks to Rene's post about WCF logging, i was able to turn on logging and found the error on the server side
Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract
which is not supported. Consider modifying the definition of collection
'Newtonsoft.Json.Linq.JToken' to remove references to itself.

NServiceBus Deserialization Exception After Deployment

I am currently using NServiceBus6. I am successfully submitting a message from my web api to endpoint which is windows service hosted. Everything works fine in my development environment on my local machine. I am using "NewtonsoftSerializer" in all my endpoint configurations. I have now deployed my solution to a server. My services are now hosted as Window Services as opposed to a console app. Service Insight is now reporting an NServiceBusDeserialization Exception:
An error occurred while attempting to extract logical messages from transport message 8221d498-81ca-406e-8ab6-a77701065f1f ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
A couple items stick out. A. I am not using XmlSerialization. B. I have no serialization issues in development environment. I would appreciate any help provided thank you.
Message Class:
public class CreateSearchRequest : ICommand
{
public SearchRequest Request { get; set; }
}
SearchRequest:
public class SearchRequest : Resource
{
public string User { get; set; }
public string SearchName { get; set; }
public SearchCriteriaSimple Criteria { get; set; }
public string Status { get; set; }
public DateTime RequestBegin { get; set; }
public DateTime RequestEnd { get; set; }
public int Records { get; set; }
public string OutputFileName { get; set; }
public string FtpLocation { get; set; }
public DateTime CreateDate { get; set; }
}
SearchRequestSimple:
public class SearchCriteriaSimple
{
public string Name { get; set; }
public List<Dictionary<string, string>> Criteria { get; set; }
}
Resource: Azure DocumentDbResource class
I am embarrassed to say. But I have figured out the issue. During development in Visual studio I configured the endpoint in the Task AsyncOnStart() method of ProgramService.cs. It seems once I install the NServiceBus host I must also provide configuration via Endpoint Config. Once I matched serialization there the issues went away.

Categories