The type 'JsonPropertyAttribute' exists in both NestV5, and Newtonsoft.Json - json.net

using Newtonsoft.Json;
namespace XX.XX.XX.XX
{
public class Geolocation
{
[JsonProperty(PropertyName = "postal_code")]
public string PostalCode { get; set; }
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
}
}
I was facing below build error for the above code
Severity Code Description Project File Line Suppression State
Error CS0433 The type 'JsonPropertyAttribute' exists in both 'NestV5, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Newtonsoft.Json, Version=7.0.0.0,

go solution explorer -> project -> references -> NestV5 right-click properties and change aliases from global to NestV5 like below

Related

Blazor and Identity

I have a project in .net core 3.0 with 3 parts : api, shared and a blazor app.
I added few models in shared project and a user model :
[Table("user")]
public class User : IdentityUser<Guid>
{
[Required(ErrorMessage = "Firstname is required")]
[StringLength(32, ErrorMessage = "Firstname must be 32 charaters maximum")]
[Column("firstname")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Lastname is required")]
[StringLength(32, ErrorMessage = "Lastname must be 32 charaters maximum")]
[Column("lastname")]
public string Lastname { get; set; }
[Required(ErrorMessage = "Thumbnail link is required")]
[StringLength(512, ErrorMessage = "Thumbnail link must be 512 charaters maximum")]
[Column("thumbnail_link")]
public string ThumbnailLink { get; set; }
[Column("birthday")]
public DateTime Birthday { get; set; }
[Required(ErrorMessage = "CreationDate is required")]
[Column("creation_date")]
public DateTime CreationDate { get; set; }
// [Required(ErrorMessage = "User role is required")]
// [Column("user_role")]
// public UserRole UserRole { get; set; }
[Required(ErrorMessage = "Is a banned user is required")]
[Column("is_banned")]
public IsBanned IsBanned { get; set; }
public ICollection<UserRole> UserRoles { get; set; }
public ICollection<UserProgression> UserProgressions { get; set; }
public ICollection<Playlist> Playlists { get; set; }
// public ICollection<Message> MessagesReceived { get; set; }
// public ICollection<Message> MessagesSended { get; set; }
public ICollection<Rating> Ratings { get; set; }
public ICollection<Course> Courses { get; set; }
public ICollection<SubscriptionHistory> SubscriptionHistories { get; set; }
}
But when I run the blazor side I got an error
Cannot find declaration of exported type 'System.Threading.Semaphore' from the assembly 'System.Threading, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Fatal error in IL Linker
Unhandled Exception: Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'C:\Users\sebastien\.nuget\packages\system.buffers\4.5.0\lib\netstandard2.0\System.Bufers.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'C:\Users\sebastien\.nuget\packages\system.buffers\4.5.0\lib\netstandard2.0\System.Bufers.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
at Mono.Linker.DirectoryAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
at Mono.Linker.AssemblyResolver.Resolve(AssemblyNameReference
name, ReaderParameters parameters)
at Mono.Linker.LinkContext.Resolve(IMetadataScope scope)
--- End of inner exception stack trace ---
at Mono.Linker.LinkContext.Resolve(IMetadataScope scope)
at Mono.Linker.Steps.ResolveFromAssemblyStep.Process()
at Mono.Linker.Steps.BaseStep.Process(LinkContext context)
at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
at Mono.Linker.Pipeline.Process(LinkContext context)
at Mono.Linker.Driver.Run(ILogger customLogger)
at Mono.Linker.Driver.Execute(String[] args, ILogger customLogger)
at Mono.Linker.Driver.Main(String[] args)
So user inherit from IdentityUser which is part of :
PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0"
I found out that blazor doesn't support package with entity framework.
So how can I implement Identity ? How can I share my Models between my server side and my front end ? I'm a beginner and it's very difficult to find some informations on the subject.
All kind of help is welcomed !
Thank you
Unfortunately you can't share an IdentityUser model with the blazor application. Blazor client-side runs on .Net standard 2.0, your identity assets run on Asp.net core. You can use .net standard code on the asp.net core side, but not the other way around.
To get around this, move your IdentityUser model to the server and create a "transfer model" in your shared project with the properties you want to transfer down to the client, then copy each property from the actual AspNetUsers table row. You want to have full control over what user's are able to see about the AspNetUsers table anyway. Hope this helps!

Cannot Scaffold (EF, Core 2.1) model that contains a 'bool' item

My model looks like this:
namespace Flow.Models
{
public abstract class Project
{
public int ID { get; set; }
public String HashID { get; set; }
public string FileLoc { get; set; } //Use HashedID above.
public bool Network { get; set; }
public int ClientID { get; set; }
public int FirmID { get; set; }
public ICollection<Order> Orders { get; set; }
}
}
AND
namespace Flow.Models
{
public class ProjectDepo : Project
{
public DateTime DepoDate { get; set; } //some way to set this to only the date
public TimeSpan DepoTime { get; set; } //some way to set this to only the time of day
public bool DepoNoticeReceived { get; set; } //yes or no
//public int FirmUserID { get; set; }
}
}
When I scaffold ProjectDepo, I receive these types of error messages:
CS1061 'CreateModel' does not contain a definition for
'DepoNoticeReceived' and no extension method 'DepoNoticeReceived'
accepting a first argument of type 'CreateModel' could be found (are
you missing a using directive or an assembly reference?)
AND
CS1061 'CreateModel' does not contain a definition for 'Network' and
no extension method 'Network' accepting a first argument of type
'CreateModel' could be found (are you missing a using directive or an
assembly reference?)
Only for the fields that I have set a 'public bool'.
In the database, both 'Network' and 'DepoNoticeReceived' are set as 'bit'. One is nullable and the other is not.
I do not know why the Scaffolding generates these errors.
Please pass along any ideas.
thank you for any assistance.
chuck
Reading the other post indicated this is a bug in the Scaffolding. For some reason, bool values are NOT being properly referenced by scaffolding. Probably should be a bug for future releases of EF/Core. (This is still in EF/Core 2.1)
#Html.DisplayNameFor(model => model.Network)
(The above is the scaffolded code, which fails.)
#Html.DisplayNameFor(model => model.ProjectDepo.Network)
This is the correct code. It fills in the missing model 'ProjectDepo'.
(This find is due to the guidance of #Renato Alio. thank you for the guidance.)
chuck

Unable to retrieve metadata when controller create

I'm trying to create controller with vies for entity framework. As model class I'm going to use Product class:
public class Product
{
public int ProductId { get; set; }
public int CategoryId { get; set; }
public int ManufacturerId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string PhotoUrl { get; set; }
public Category Category { get; set; }
public Manufacturer Manufacturer { get; set; }
}
And like data context class this:
public class RetroGadgetEntities:DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
The problem is that I get an error when trying to create controller "Unable to retrieve metadata for 'RetroGadget.Models.Product'".
As I understand it is actualy thrown when code generator trying to create strongly typed view, but I can't figure out why.
UPD:
Here is my Web.config.
<connectionStrings>
<add name="RetroGadgetCon" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=RetroGadget.Models.RetroGadgetEntities;Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
UPD2
public class Product
{
[Key]
public int ProductId { get; set; }
public int CategoryId { get; set; }
public int ManufacturerId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string PhotoUrl { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
[ForeignKey("ManufacturerId")]
public Manufacturer Manufacturer { get; set; }
}
Why this error thrown and what I can do with it?
Here are possible fixes you can do:
1) If you're using Code First & error message indicates Entity 'X' has no key defined or EntitySet 'X' is based on type 'Y' that has no keys defined, add primary key attribute (KeyAttribute) to model class property which serves as identity column:
using System.ComponentModel.DataAnnotations;
public class Product
{
[Key] // add this attribute
public int ProductId { get; set; }
// other properties
}
Additionally, ensure that DbContext constructor contains reference to named connection string in web.config:
public class RetroGadgetEntities : DbContext
{
public RetroGadgetEntities() : base("RetroGadgetCon")
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
Afterwards, ensure all foreign keys & table relationships are arranged well (add ForeignKeyAttribute & ICollection if required).
2) If error message indicates Unrecognized element 'providers', this provider section in web.config possibly causing metadata problem on EF context when creating controller from a model (often occurs when you're downgrading default EF version used by template to previous one):
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
Try removing that provider part so that the entityFramework section becomes this:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
NB: The connection string section seems used invalid database location namespace as RetroGadget.Models.RetroGadgetEntities, try changing Initial Catalog to use a database name instead:
<add name="RetroGadgetCon" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=(database name);Integrated Security=True;" providerName="System.Data.SqlClient"/>
If the connection still not working with given LocalDB instance, add AttachDbFilename="(database path)\(database name).mdf" & use Data Source=(LocalDb)\v11.0 (depending on LocalDB version, see SQL Server connection string).
References:
Cannot create controller with Entity framework - Unable to retrieve metadata for ' '
Entity Framework: Unrecognized element 'providers' exception
Ok, I'v solved it.
The actual problem was with linked classes.
public class Category
{
[Key]
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Product> Products { get; set; }
}
public class Manufacturer
{
[Key]
public int ManufacturerId { get; set; }
public string Name { get; set; }
}
Problem was that there was no field Products in Manufacturer class. So I'v changed this like this.
public class Manufacturer
{
[Key]
public int ManufacturerId { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}

The system cannot find the file specified " return employeeDBContext.Departments.Include("Employees").ToList();"

I am developing web application using vs 2017 ,EF v 6.0.1 with code first approach.On running the application I am getting error at employee repository class, return statement as "The system cannot find the file specified. return employeeDBContext.Departments.Include("Employees").ToList();".I am unable to upload the picture to explain clearly. And also I am using gridview with object datasource.
The below is my code along with connection strings.So, please Let me know where the problem is...
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public Department Department { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Employee> Employees { get; set; }
}
public class EmployeeDBContext:DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
public class EmployeeRepository
{
public List<Department> GetDepartments()
{
EmployeeDBContext employeeDBContext = new EmployeeDBContext();
return employeeDBContext.Departments.Include("Employees").ToList();
}
}
<connectionStrings>
<add name="EmployeeDBContext" providerName="System.Data.SqlClient"
connectionString="server=.;uid=sa;pwd=P#ssw0rd;database=Sample;" />
The system cannot find the file specified "return employeeDBContext.Departments.ToList(); "
The mistake is at web.config connectionstring. I replaced the following code
<connectionStrings>
with the code
<connectionStrings>
<add name="EmployeeDBContext" providerName="System.Data.SqlClient" connectionString="server=.\SQLSERVERR2;uid=sa;pwd=P#ssw0rd;database=Sample;" />
Changed the server name.
Thanks........

XMLserializer, Entity Framework : Cannot serialize member of type ICollection see inner exception for more details

I want to map XML elements into my database table (using Entity Framework):
var xmlSerializer = new XmlSerializer(typeof(Participant), new XmlRootAttribute("participant"));
var participant = (Participant)xmlSerializer.Deserialize(new StringReader(content));
I have Participant table which I can access by
[XmlRoot("participant", Namespace = "")]
public partial class Participant
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Participant()
{
this.GroupParticipant = new HashSet<GroupParticipant>();
this.ParticipantAddress = new HashSet<ParticipantAddress>();
this.ParticipantPublisher = new HashSet<ParticipantPublisher>();
this.ParticipantJob = new HashSet<ParticipantJob>();
this.ParticipantProvider = new HashSet<ParticipantProvider>();
}
[XmlElement("firstName")]
public string FirstName { get; set; }
[XmlElement("lastName")]
public string LastName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
//[XmlElement("address")]
//[XmlElement("address")]
//[XmlArray("HashSet<ParticipantAddress>"), XmlElement("address")]
//[XmlArrayItem("ICollection<ParticipantAddress>")]
//[XmlAttribute(DataType = "ICollection<ParticipantAddress>", AttributeName = "address")]
[XmlElement("address", typeof(List<ParticipantAddress>))]
public virtual ICollection<ParticipantAddress> ParticipantAddress { get; set; }
}
ParticipantAddress is ICollection:
[Serializable]
[XmlInclude(typeof(HashSet<ParticipantAddress>))]
public partial class ParticipantAddress
{
public int ParticipantAddressId { get; set; }
public int ParticipantId { get; set; }
[XmlElement("city")]
public string City { get; set; }
[XmlElement("state")]
public string State { get; set; }
[XmlElement("zipCode")]
public string ZipCode { get; set; }
public virtual Participant Participant { get; set; }
}
Exception says:
{"There was an error reflecting type 'x.Participant'."}
My inner Exception says:
{"Cannot serialize member 'xParticipant.ParticipantAddress' of type 'System.Collections.Generic.ICollection`1[[x.ParticipantAddress, APS.Data.BatchInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]', see inner exception for more details."}
I am reading XML by streamReader.
I have tried
[XMLArray]
Changing ICollection to List
make class serializable
Is there any other way to overcome this problem or any examples related to my question or any changes I need to implement in my code?
ICollection is not serializable.
- You can use DTO.
- You can change the collection type (i.e. with List<>) and with XML serialization attributes avoid circular references and/or disable lazy load (i.e. use eagerly load using Include method) or the risk is that you serialize the whole database.
You have this issue because of the virtual properties. You try to serialize a class which has a reference to another class, which has a reference to the first, class, which... endless loop.
If you want to serialize an entity, the best thing you can do is use a DTO class, which is a class used only to export your data. In these classes you can't have virtual properties, but what you can do is include the DTO objects of your ParticipantAddress.
The other thing you can try, if it isn't a necessity to serialize to XML, is use the Newtonsoft.Json package to serialize the entities. The package has some options to deal with navigational properties.
I have created a region and change ICollection<> to List<> because
ICollection is an interface and interfaces are not serializable.
But List<> is a class and this class implements all the below interfaces:
IList, ICollection, IList, ICollection, IReadOnlyList, IReadOnlyCollection, IEnumerable, IEnumerable.
I kept both Icollection as well as List and put [XmlIgnore] on ICollection.
[XmlRoot("participant", Namespace = "")]
public partial class Participant
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Participant()
{
this.GroupParticipantList = new List<GroupParticipant>();
this.ParticipantAddressList = new List<ParticipantAddress>();
this.ParticipantPublisherList = new List<ParticipantPublisher>();
this.ParticipantJobList = new List<ParticipantJob>();
this.ParticipantProviderList = new List<ParticipantProvider>();
}
[XmlElement("firstName")]
public string FirstName { get; set; }
[XmlElement("lastName")]
public string LastName { get; set; }
[XmlIgnore]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ParticipantAddress> ParticipantAddress { get; set; }
#region Custom properties
[XmlElement("address")]
public virtual List<ParticipantAddress> ParticipantAddressList { get; set; }
#endregion
}
But with this option I am having another Problem: If I do any single change in my SQL database and if I do update model from database, then I lose manually implemented code like all the XML sentences in this code.
I answered this in the below article to add [System.Xml.Serialization.XmlIgnore] to entity.tt template
Prevent Property from being serialized
I had a similar issue using EF, to implement a Web service and couldn't serialize the ICollection<> object.
I hopes this helps you out.
public class User
{
public User()
{
sessions = new HashSet<Session>();
}
public int Id { get; set; }
public string Name { get; set; }
[XmlIgnore]
[IgnoreDataMember]
public virtual ICollection<Session> sessions { get; set; }
}
public class Session
{
public int Id { get; set; }
public Datetime start_dtime{ get; set; }
public Datetime end_dtime{ get; set; }
public virtual User user{ get; set; }
}

Resources