Microsoft.AspNet.Identity - What data should be stored as an identity claim vs another database table - claims-based-identity

What would be best practice to determine what I should store in the identity claim object versus in a separate table. For example, let's say that each user needs to have access to multiple sites. See object below:
public class Site
{
public int SiteID { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
Should i store the Site object as a Serialized Claim or should I create database table for it, as well make the Site object a property of the Application User class of Microsoft.AspNet.Identity framework.
public class ApplicationUser : IdentityUser
{
public Site[] Sites {get; set;}
}

Related

Confused about DTOs when reading and editing. How to desing DTO for filling the form in VUEjs app?

I am trying to develop an enterprise-level application. I have domain and application services. I have created my DTOs for multiple purposes separately. But confused about which way I should use them from the API viewpoint.
I have complex objects lets say,
public class Entity{
public int Id { get; set; }
public string Name { get; set; }
public int? ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer{
public int Id { get; set; }
public string Text { get; set; }
}
And I have corresponding DTOs designed with composition now. It was separated before.
public class EntityBaseDto{
public string Name { get; set; }
}
public class EntityReadDto : EntityBaseDto{
public string Manufacturer { get; set; }
}
public class EntityWriteDto : EntityBaseDto{
public int? ManufacturerId { get; set; }
}
Now the question is,
I have a table which is filled with List<EntityReadDto> which is clear. Before, EntityReadDto also had the ManufacturerDto as fully included with id and text. Whenever I require to edit one of the entries from the table I was able to load the dropdown selected items or list of tags etc with the ids attached to the Manufacturer objects within ReadDtos. Now it is not possible. Since I wanted to simplify the codes I just converted them to strings that are read-only. Now I have created another endpoint to get an editable version of the record when needed. Ex: EntityWriteDto will be used to fill the form when the edit is clicked on a specific item. The manipulation will be carried on that DTO and sent with the PUT type request to edit the record.
I am not sure if this approach is ok for these cases. What is the best practice for this? I have many objects related to the entities from other tables. Is it ok to make a call to get an editable version from the backend or need to have it right away in a VUEjs app?

using EF Core IdentityContext and DbContext both for order management

I am working on creating an ecommerce website on ASP MVC Core 2. I inherited my user from IdentityUser and inherited context from IdentityDbContext for working with user data and inherited a different context from DbContext for working with products and orders etc.
Now, I want to link an order or shopping cart to a particular user and can not wrap my head around how to refer to the user in order table as they are in different contexts. I am also using the default guid created by EF as primary key in both the tables.
Should I ditch DbContext and use IdentityDbContext only? Does doing this causes problems with async methods in identity and other usual non async methods.
Here are some code snippets from my classes
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace shophe1.Models
{
public enum Gender { Male, Female, Other}
public class User : IdentityUser
{
public string FullName { get; set; }
public Gender Gender { get; set; }
public string ReferralID { get; set; }
public DateTime RegistrationDateTime { get; set; }
public string ActivationDateTime { get; set; }
public string UserType { get; set; }
public Wallet Wallet {get;set;}
public virtual ICollection<UserBankDetail> BankDetails { get; set; }
public virtual ICollection<UserAddress> AddressDetails { get; set; }
//public ShoppingCart Cart { get; set; }
//public ICollection<Order> Orders { get; set; }
}
}
Order class
using System.Collections.Generic;
namespace shophe1.Models
{
public class Order
{
public string OrderId { get; set; }
public ICollection<product> CartProducts { get; set; }
//public User User { get; set; }
public decimal OrderTotal { get; set; }
public decimal ShippingCharges { get; set; }
}
}
The issue is if I add user in order model and a collection of orders in user class, both contexts get mixed up and when migrating, all user and product related models get clubbed in same migration whether I use DbContext or IdentityContext in migrations --context option. This is because both user and orders are now interrelated.
Please advice.
Inherit your context from IdentityDbContext. You should have one context per database, ideally - especially if you want to relate the entities to each other.
If you actually want separate databases, such that the Identity tables reside in one, while your application tables reside in another, then you won't be able to directly relate the entities with each other. However, you can still create a pseudo-foreign key, where you simply store the id of a particular user in a column on one of your entities. You'd then merely need to issue a separate query on the other context with this id to fetch the user manually. For example:
var order = await appContext.Orders.FindAsync(orderId);
var user = await identityContext.Users.FindAsync(order.UserId);

Fluent Nhibernate Cascade.None() results in HasOne foreign key relationship not being persisted

I'm having issues with Nhibernate persisting a HasOne Relationship for one of my entities with Cascade.None() in effect. My domain model involves 4 classes listed below.
public class Project
{
public virtual int Id {get;set;}
public virtual IList<ProjectRole> Team { get; protected set; }
}
public class ProjectRole
{
public virtual int Id { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
public virtual int Id { get; set; }
public virtual string Value { get; set; }
}
public class User
{
public virtual int Id { get; protected set; }
public virtual string LoginName { get; set; }
}
So basically we have projects, which have a list of ProjectRoles available from the Team property. Each ProjectRole links a User to the specific Role they play on that project.
I'm trying to setup the following cascade relationships for these entities.
project.HasMany<ProjectRoles>(p=> p.Team).Cascade.All()
projectRole.HasOne<Role>(r => r.Role).Cascade.None()
projectRole.HasOne<User>(r => r.User).Cascade.SaveUpdate()
I've used fluent nhibernate overrides to setup the cascades as above, but I'm finding that the line
projectRole.HasOne<Role>(r => r.Role).Cascade.None()
is resulting in the ProjectRole.Role property not being saved to the database. I've diagnosed this be looking at the SQL Generated by Nhibernate and I can see that the "Role_id" column in the ProjectRoles table is never set on update or insert.
I've also tried using
projectRole.HasOne<Role>(r => r.Role).Cascade.SaveUpdate()
but that fails as well. Unfortunately leaving it Cascade.All() is not an option as that results in the system deleting the Role objects when I try to delete a project role.
Any idea how to setup Cascade.None() for the ProjectRole-> Role relationship with out breaking persistence.
HasOne is for a one-to-one relationship which are rare. You want to use References to declare the one side of a one-to-many relationship. Making some assumptions about your domain model, the mapping should look like:
project.HasMany<ProjectRoles>(p=> p.Team).Inverse().Cascade.AllDeleteOrphan()
projectRole.References<Role>(r => r.Role);
projectRole.References<User>(r => r.User);
See also this question about the difference between HasOne and References.

How to map and reference entities from other data sources with NHibernate

I'm currently working on and ASP.NET MVC application in which I have a User entity like follows:
public class User
{
public virtual int Id { get; protected set; }
public virtual string Name { get; protected set; }
public virtual string Role { get; protected set; }
public virtual Location Location { get; protected set; }
}
Where location is just as straightforward:
public class Location
{
public virtual string Id { get; protected set; }
public virtual string Building { get; protected set; }
public virtual string City { get; protected set; }
public virtual string Region { get; protected set; }
}
My complication arises because I want to populate the User from Active Directory and not the database. Additionally, several classes persisted to the database reference a user as a property. I've got an ADUserRepository for retrieval, but I don't know how to integrate these Users into my object graph when the rest is managed by NHibernate.
Is there a way for NHibernate to persist just an id for a User without it being a foreign key to a Users table? Can I map it as a component to accomplish this? I've also looked at implementing IUserType to make the translation. That way it would map to a simple field and ADUserRepository could be put in the chain to resolve the stored Id. Or am I trying to hack something that's not really feasible? This is my first time around with NHibernate so I appreciate any insight or solutions you can give. Thanks.
Update
It appears my best solution on this will be to map the User with an IUserType and inject (preferably with StructureMap) a service for populating the object before its returned. Framed in that light there are a couple of questions here that deal with the topic mostly suggesting the need for a custom ByteCodeProvider. Will I still need to do this in order for IUserType to take a parameterized constructor or do the comments here: NHibernate.ByteCode.LinFu.dll For NHibernate 3.2 make a difference?
using a Usertype to convert user to id and back
public class SomeClass
{
public virtual string Id { get; protected set; }
public virtual User User { get; protected set; }
}
// in FluentMapping (you have to translate if you want to use mapping by code)
public SomeClassMap()
{
Map(x => x.User).Column("user_id").CustomType<UserType>();
}
public class UserType : IUserType
{
void NullSafeSet(...)
{
NHibernateUtil.Int32.NullSafeSet(cmd, ((User)value).Id, index);
}
void NullSafeGet(...)
{
int id = (int)NHibernateUtil.Int32.NullSafeGet(cmd, ((User)value).Id, index);
var userrepository = GetItFromSomeWhere();
return userrepository.FindById(id);
}
}

DTOs and WCF RIA

I have a DTO which has a collection within it of another DTO which I populate server-side and send to the client. However, this inner DTO collection is not returned to the client.
I believe I need to use the [Include] and [Association] attributes so that WCF RIA services knows what to do, however my issue with this is there is no real association as such between the main DTO and the inner DTO collection, I am just using it to aggregate data from various sources for return to the client.
Is my understanding wrong in what I am trying to achieve, if not how do I get WCF RIA to send this inner DTO collection.
I should add that I am using automapper and want to achieve it using such.
Here is an example, I want to send back to the client in one chunk;
The competencies that the employee has.
The competencies that the employee requires for their job.
The GAP, which is the difference between 1 and 2.
public class CompetencyRequirementsDto
{
[Key]
public string CompanyId { get; set; }
[Key]
public string EmployeeNo { get; set; }
public string JobId { get; set; }
[Include]
[Association("EmployeeCompetencies","CompanyId, EmployeeNo","CompanyId, EmployeeNo")]
public IList<EmployeeCompetencyDto> EmployeeCompetencies { get; set; }
[Include]
[Association("JobCompetencies","JobId, CompanyId","JobId, CompanyId")]
public IList<JobCompetencyDto> JobCompetencies { get; set; }
[Include]
[Association("CompetencyGap", "JobId, CompanyId", "JobId, CompanyId")]
public IList<JobCompetencyDto> CompetencyGap { get; set; }
} }
Now item 1 works fine, but 2 and 3 don't? What I have found is that my DTO is created ok server side but when it gets to the client CompetencyGap(even when it has no values) has
been given JobCompetencies values.
If you are using ADO.Net Entity data model and using RIA Services against them then you have got an option to create associated metadata.
So to get the reference entities at you client side we need to modify both the our corresponding meta-data and as well as well the function of the domain service class which is fetching your data .
Here I am giving an example...
1. Just add [Include] attribute at the the top of the referenced data for example.
[MetadataTypeAttribute(typeof(Customer.CustomerMetadata))]
public partial class Customer
{
// This class allows you to attach custom attributes to properties
// of the Customer class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CustomerMetadata
{
// Metadata classes are not meant to be instantiated.
private CustomerMetadata()
{
}
public int CustomerID { get; set; }
public string EmailAddress { get; set; }
public string FullName { get; set; }
[Include]
public EntityCollection<Order> Orders { get; set; }
public string Password { get; set; }
}
}
2. Modify the function in the domain service and add include there also for example.
public IQueryable<Customer> GetCustomers()
{
var res = this.ObjectContext.Customers.Include("Orders");
return res;
}
In your case the first part is done you just need to modify your domain service query to get reference entities.