AutoMapper / Castle - Inheritance security rules violated while overriding member - .net-4.0

I am getting the following exception when calling any of my Mapper.Map methods.
Inheritance security rules violated while overriding member: 'Castle.Core.Logging.LevelFilteredLogger.InitializeLifetimeService()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
I am using the latest build of AutoMapper downloaded from codeplex inside my S#arp 1.6 application running on .Net 4.0 (which is using version 1.2.0.6623 of Castle.Core).
I beleive it has something to do with the new .Net 4.0 security settings which I don't quite understand.
Is there a way to fix it?
Paul

I tried something from a little googling which fixed my problem, i'm not sure if this is the ideal or recommended approach but it worked.
I added this to the Automapper projects 'AssemblyInfo.cs' file:
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
I recompiled and used the new DLL and everything worked fine.
Please leave comments if this isn't reccomended or if there is a better approach.
For now though i will leave my own answer as the correct one.
Thanks for the help though!
UPDATE:
My mappings are pretty simple, sorry about all the code but thought it may help you:
Initialisation Code:
Mapper.Reset();
Mapper.Initialize(x =>
{
x.AddProfile<LeadsProfile>();
//x.AddProfile<AttendeeProfile>();
});
Mapper.AssertConfigurationIsValid();
LeadsProfile.cs
public class LeadsProfile : AutoMapper.Profile
{
public override string ProfileName
{
get { return "LeadsProfile"; }
}
protected override void Configure()
{
Mapper.CreateMap<Lead, LeadDto>();
Mapper.CreateMap<Lead, LeadDetailDto>();
Lead lead = null;
Mapper.CreateMap<int, LeadDetailDto>()
.BeforeMap((s, d) => lead = ServiceLocator.Current.GetInstance<ILeadRepository>().FindOne(s))
.ForMember(d => d.Id, x => x.MapFrom(s => lead.Id))
.ForMember(d => d.Fullname, x => x.MapFrom(s => lead.Fullname))
.ForMember(d => d.TelNumber, x => x.MapFrom(s => lead.TelNumber))
.ForMember(d => d.BookedAppointmentDate, x => x.MapFrom(s => lead.BookedAppointmentDate));
}
}
Source Class
public class Lead : Entity
{
public Lead()
{
Status = Common.LeadStatus.Raw;
CreatedDate = DateTime.Now;
}
public Lead(Branch branch, Promoter promoter, LeadSource source, string fullname, string telNumber, Address address, DateTime apptDate) : this()
{
this.Branch = branch;
this.Promoter = promoter;
this.Source = source;
this.Fullname = fullname;
this.TelNumber = telNumber;
this.Address = address;
this.BookedAppointmentDate = apptDate;
}
public virtual Branch Branch { get; set; }
public virtual Promoter Promoter { get; set; }
public virtual LeadSource Source { get; set; }
public virtual Common.LeadStatus Status { get; set; }
public virtual bool ExistingCustomer { get; set; }
public virtual bool IsDoso { get; set; }
public virtual string TitlePrefix { get; set; }
public virtual string Fullname { get; set; }
public virtual string TelNumber { get; set; }
public virtual string MobileNumber { get; set; }
public virtual DateTime BookedAppointmentDate { get; set; }
public virtual Address Address { get; set; }
public virtual Store Store { get; set; }
public virtual IList<LeadProduct> Products { get; set; }
public virtual IList<Appointment> Appointments { get; set; }
public virtual IList<Sale> Sales { get; set; }
public virtual DateTime CreatedDate { get; set; }
}
Destination Dto's
public class LeadDto
{
public int Id { get; set; }
public string Fullname { get; set; }
public string TelNumber { get; set; }
public DateTime BookedAppointmentDate { get; set; }
}
public class LeadDetailDto
{
public int Id { get; set; }
public string Fullname { get; set; }
public string TelNumber { get; set; }
public DateTime BookedAppointmentDate { get; set; }
}

I'd try upgrading Castle.Core to 2.5, which has been built and tested specifically against .net 4.0. (I should note that Castle.Core 2.5 is also available for .net 3.5 and SL 3/4)
Related questions:
Log4Net and .NET 4.0 RC
Weird override problem with Fluent NHibernate and .NET 4

Related

EF Core 2.2: migrating starts reporting that there are pending model changes for a context

Existing ASP.NET Core 2.1 app (running against netcore2.1) was migrated to ASP.NET Core 2.2 (installed the sdk and changed the target). Now, whenever I ran the app, it starts showing the traditional "There are pending model changes for ApplicationDbContext".
If I follow the instructions and try to add a migration, I've noticed that it does in fact generate a new migration file. By running a diff, I can see that it's adding these lines to the Application context snapshot:
modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
And it will also add the following to my entity:
b.Property<long?>("UserServiceId1");
b.Property<long?>("UserServiceServiceId");
b.Property<long?>("UserServiceUserId");
I'm not sure on where it gets the UserServiceId1 name (the entity has a UserServiceId property). Btw, here's the entity class code:
[Table("UserIdentifiers", Schema = "Gov")]
public class UserIdentifiers
{
[Required]
public long UserId { get; set; }
[Required]
public long ServiceId { get; set; }
[Required]
public long UserServiceId { get; set; }
[Required]
public long IdentifierId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public long UserIdentifierId { get; set; }
public virtual Identifiers Identifier { get; set; }
public virtual UserServices UserService { get; set; }
}
The table that maps to this entity has a composite key built from the the UserId, ServiceId, UserServiceId, IdentifierId and UserIdentifierId. The snapshot has it defined like this:
b.HasKey("UserId", "ServiceId", "UserServiceId", "IdentifierId", "UserIdentifierId");
Oh, and yes, there are also migration files for dropping the UserServiceId column and adding the "new" UserServiceId1 column.
I'm not really an EF expert, so I'm not sure on why this stopped working after migrating from 2.1 to 2.2.
So, can anyone point me in the right direction?
btw, is there a way to disable migrations on ef core?
thanks
EDIT: adding the classes referenced by the UserIdentifiers entity (only showing the relations between classes):
// identifiers
[Table("Identifiers", Schema = "Gov")]
public class Identifiers
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public long IdentifierId { get; set; }
[Required]
public int IdentityResourceId { get; set; }
[Required]
public long ServiceId { get; set; }
public virtual Services Service { get; set; }
}
//Services
[Table("Services", Schema = "Gov")]
public class Services
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public long ServiceId { get; set; }
public virtual List<Identifiers> Identifiers { get; set; }
public virtual List<UserServices> UserServices { get; set; }
public virtual List<ClientServices> ClientServices { get; set; }
}
// userservices
[Table("UserServices", Schema = "Gov")]
public class UserServices
{
[Required]
public long UserId { get; set; }
[Required]
public long ServiceId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public long UserServiceId { get; set; }
public virtual List<UserIdentifiers> UserIdentifiers { get; set; }
public virtual Services Service { get; set; }
public virtual ApplicationUser User { get; set; }
}
And finally, here's the configuration performed inside the OnModelCreating method:
builder.Entity<Identifiers>()
.HasKey(x => new { x.ServiceId, x.IdentifierId });
builder.Entity<UserIdentifiers>()
.HasKey(x => new { x.UserId, x.ServiceId, x.UserServiceId, x.IdentifierId, x.UserIdentifierId });
builder.Entity<UserServices>()
.HasKey(x => new { x.UserId, x.ServiceId, x.UserServiceId });
builder.Entity<ClientServices>()
.HasKey(x => new { x.ServiceId, x.ClientId, x.ClientServiceId });
A friend of mine solve it by adding the "missing" foreignkey info to the model:
[ForeignKey("ServiceId, IdentifierId")]
public virtual Identifiers Identifier { get; set; }
[ForeignKey("UserId, ServiceId, UserServiceId")]
public virtual UserServices UserService { get; set; }
And now everything works out as expected.
thanks again

Setting up Automapper 5.1

I am having trouble following the wiki in this instance. I wanted to use Automapper 5.2. I cannot find a simple end for end example that shows a solid configuration with context. By context I mean where do you put the config files and whats the difference between static and instance api?
I checked out the DNRTV download but it deals with the 1.0 version.
How do you set this package up? I have a model called Client as below.
public class Client : IEntityBase
{
public Client()
{
Jobs = new List<Job>();
}
public int Id { get; set; }
public int ClientNo { get; set; }
public bool Company { get; set; }
public string CompanyName { get; set; }
public string ClientFirstName { get; set; }
public DateTime DeActivated { get; set; }
public bool Activity { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public int? StateId { get; set; }
public State State { get; set; }
public int CreatorId { get; set; }
public User Creator { get; set; }
public ICollection<Job> Jobs { get; set; }
}
and a ClientViewModel as so:
public class ClientViewModel
{
public int Id { get; set; }
public int ClientNo { get; set; }
public bool Company { get; set; }
public string CompanyName { get; set; }
public string ClientFirstName { get; set; }
public DateTime DeActivated { get; set; }
public bool Activity { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public int? StateId { get; set; }
public int CreatorId { get; set; }
public int[] Jobs { get; set; }
}
I am unsure how to set AutoMapper up with regard to configuration. That is, they talk about a global.asax file and I am using aspnet core.. there is no Global.asax file..
What do you put in the Startup.cs file if anything.
Given these two files above what do I need to do to use Automapper with them?
Regards
Here is the steps to configure the automapper in asp.net core mvc.
1. Create the mapping profile class which extends from Profile
public class ClientMappingProfile : Profile
{
public ClientMappingProfile ()
{
CreateMap<Client, ClientViewModel>().ReverseMap();
}
}
2. Create the AutoMapper Configuration Class and add your mapping profile class here.
public class AutoMapperConfiguration
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}
3. Create extension method so, we can add this to Startup.cs ConfigureServices method
public static class CustomMvcServiceCollectionExtensions
{
public static void AddAutoMapper(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
var config = new AutoMapperConfiguration().Configure();
services.AddSingleton<IMapper>(sp => config.CreateMapper());
}
}
4. Call the extension method in Startup.cs ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddAutoMapper();
}

fluent nhibernate mapping issue

I have two objects Customer_policy and policy_maturity.
public class Customer_policy
{
public virtual String policy_no { get; set; }
public virtual DateTime maturity_date { get; set; }
public virtual Boolean matured_status { get; set; }
}
public class Policy_maturity
{
public virtual string policy_no { get; set; }
public virtual string customer_id { get; set; }
public virtual float maturity_amt { get; set; }
public virtual string policy_type { get; set; }
public virtual DateTime pay_date { get; set; }
}
When a customer creates a policy Customer_policy is getting populated but Policy_maturity should remain empty(which I have already done). When a policy matures I want to insert a row in Policy_maturity and update matured_status field of the corresponding Customer_policy. What type of mapping should I do so that inserting and update gets accomplished by hitting the database only one time ??? Thanx for your suggestions.
a suggestion:
public class CustomerPolicy
{
public virtual String PolicyNumber { get; private set; }
public virtual DateTime MaturityDate { get; set; }
public virtual PolicyMaturity Maturity { get; private set; }
public virtual Boolean HasMatured { get { return Maturity != null; } }
public virtual void DoMature(Customer customer, float maturity_amt, string policyType, DateTime payDate)
{
DoMature(new PolicyMaturity
{
Customer = customer,
MaturityAmt = maturity_amt,
PolicyType = policyType,
PayDate = payDate,
});
}
/*public*/ virtual void DoMature(PolicyMaturity maturity)
{
Maturity = maturity;
MaturityDate = DateTime.Today;
}
}
public class PolicyMaturity
{
public virtual String PolicyNumber { get; private set; }
public virtual CustomerPolicy Policy { get; set; }
public virtual Customer Customer { get; set; }
public virtual float MaturityAmt { get; set; }
public virtual string PolicyType { get; set; }
public virtual DateTime PayDate { get; set; }
}
class CustomerPolicyMap : ClassMap<CustomerPolicy>
{
public CustomerPolicyMap()
{
Id(cp => cp.PolicyNumber).GeneratedBy.Assigned();
Map(cp => cp.MaturityDate);
HasOne(cp => cp.Maturity);
}
}
class PolicyMaturityMap : ClassMap<PolicyMaturity>
{
public PolicyMaturityMap()
{
Id(cp => cp.PolicyNumber).GeneratedBy.Foreign("Policy");
HasOne(cp => cp.Policy);
References(cp => cp.Customer);
Map(cp => cp.MaturityAmt);
Map(cp => cp.PayDate);
Map(cp => cp.PolicyType);
}
}
then if you save the Updated Customerpolicy NHibernate should batch the two updates
You will need to ask NHibernate to batch the two DML queries. Have a look at this blog post for a detailed description of how to use batching in NHibernate.
Wrapping the two operations in a transaction (as the example in the blog post does) is also a good idea.

Fluent NHibernate Mapping Non Required Object using Automapping

I have a composite object set up Project->Appraisal, My appraisal object has a ApprovedMentor object which is not required but when i go to save project Nhib throws and error to say that ApprovedUser has not been set. but its not set because its not a required field. How do i set up this using fluent auto mapping, is it possible?
public class MentoringProject : BaseEntity
{
public MentoringProject()
{
Appraisal = new Appraisal();
}
[NotNullNotEmpty]
[Length(Min=25, Max=1000)]
public virtual string Description { get; set; }
[Length(Min=25, Max=1000)]
public virtual string SupportRequired { get; set; }
[NotNullNotEmpty]
public virtual System.DateTime? DateSubmitted { get; set; }
[NotNullNotEmpty]
public virtual System.DateTime? ClosingDate { get; set; }
[NotNullNotEmpty]
[Size(Min=1)]
public virtual short Duration { get; set; }
[NotNullNotEmpty]
public virtual string Skills { get; set; }
public virtual Appraisal Appraisal { get; set; }
}
public class Appraisal : BaseEntity
{
public Appraisal()
{
ShortlistedMentors = new List<User>();
ApprovedMentor = new User();
College = new RefData();
}
#region Primitive Properties
public virtual bool Decision { get; set; }
public virtual System.DateTime? ApprovedDate { get; set; }
public virtual System.DateTime? AcceptedDate { get; set; }
public virtual System.DateTime? CompletionTargetDate { get; set; }
public virtual string RejectionReason { get; set; }
#endregion
#region Navigation Properties
public virtual IList<User> ShortlistedMentors { get; set; }
public virtual User ApprovedMentor { get; set; }
public virtual RefData College { get; set; }
#endregion
}
It looks to me that you just want to ignore the ShortlistedMentors property which you need to do in your mapping class like this:
map.IgnoreProperty(p => p.ShortlistedMentors);
This answer was posted in this question.
I think i have solved this, when binding the UI to the controller in MVC, MVC creates an empty User object and because that object has required fields set on it using nhib validator and nhib was trying to create a new user object, I got round this by checking if there is a user realtionship to add, if not I set the Appraisal.ApprovedMentor==null

How to model this classes withN Hibernate and Fluent.NHibernate Maps?

I'm using ASP.NET MVC with NHibernate and Fluent.NHibernate Maps.
I would like to know how to map the classes on Fluent and to create the database tables on my MySQL:
public class AgenteDeViagem {
public virtual int Id { get; set; }
public virtual string Email { get; set; }
public virtual AgentePessoa AgentePessoa { get; set; }
}
public interface AgentePessoa {
}
public class AgenteDeViagemPJ:AgentePessoa {
public virtual int Id { get; set; }
public virtual AgenteDeViagem AgenteDeViagem { get; set; }
public virtual string Razao { get; set; }
}
public class AgenteDeViagemPF:AgentePessoa {
public virtual int Id { get; set; }
public virtual AgenteDeViagem AgenteDeViagem { get; set; }
public virtual string Nome { get; set; }
}
Thank you very much!
Looks to me like you're halfway there. You're already using virtual and relations are set, so using the Automapping strategy, you only need to build the session factory:
private static ISessionFactory InitializeNHibernate()
{
var cfg = Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(c =>
c.Database("agente").Server("localhost")
.Username("user").Password("password")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<AgenteDeViagem>())
.ExposeConfiguration(configuration =>
{
// Comment to disable schema generation
BuildDatabaseSchema(configuration);
});
return cfg.BuildSessionFactory;
}
private static void BuildDatabaseSchema(Configuration configuration)
{
var schemaExport = new SchemaExport(configuration);
schemaExport.SetOutputFile("mysql_script.sql");
schemaExport.Create(false, true);
}