I have a xaml file that needs to convert into objects, Is there anyone done this before?
using (var stream = File.OpenRead(filename)) {
var yourObj = XamlReader.Load(stream);
}
//Configuration Class
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class PostFordelerConfiguration
{
private readonly ReceiverAddressList _receiverAddresses;
private readonly DocumentTypeList _documentTypes;
public PostFordelerConfiguration()
{
_receiverAddresses = new ReceiverAddressList();// I don't want to implement like this.
_documentTypes = new DocumentTypeList(); //// I don't want to implement like this.
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ReceiverAddressList ReceiverAddresses
{
get { return _receiverAddresses; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DocumentTypeList DocumentTypes { get {return _documentTypes;} }
public static PostFordelerConfiguration Load(string location)
{
return (PostFordelerConfiguration)XamlReader.Load(new XmlTextReader(location));
}
}
}
//Document Entity
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class DocumentType
{
public String Id { get; set; }
}
}
//Document List
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class DocumentTypeList : List<DocumentType>{ }
}
//ReceiverAddress Entities
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class ReceiverAddress
{
public String Id { get; set; }
public String Routable { get; set; }
public String Description { get; set; }
}
}
//ReceiverAddress List
namespace SKAT.Postfordeler.Shared.DataTypes
{
[Serializable]
public class ReceiverAddressList : List<ReceiverAddress>{ }
}
// Load XAML file and Convert into objects
SKAT.Postfordeler.Shared.DataTypes.PostFordelerConfiguration loader =
Postfordeler.Shared.DataTypes.PostFordelerConfiguration.Load(
#"D:\projects\skatpostfordeler\SKAT.Postfordeler.Client.UI\PostfordelerConfiguration.xaml");
Related
I use DTO class in API layer and I struggle to map DTO class to "model" class in generic Repository.cs in core layer.
Repository.cs :
namespace DTOMap.Core.Repository.Generic
{
public class Repository<T> : IRepository<T> where T : class
{
private DTOMapContext _context;
private DbSet<T> _table;
private IMapper _mapper;
public Repository(DTOMapContext context)
{
_context = context;
_table = _context.Set<T>();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<MyMapper>();
});
_mapper = config.CreateMapper();
}
public T Add(T obj)
{
// Here how to use My Mapper to save a book or an author generically
// Sth like :
// temp = _table.Add(_mapper.Map<T>(obj)); Here I want to map Dto to model to save in the db
// return = (_mapper.Map<T>(temp)); Here I want to map Model to DTO to collect it in API
// but I can't have a reference to TDTO
throw new NotImplementedException();
}
}
}
I show you the other classes that I find useful (I only implement Add function for this example and I am a beginner in .Net) :
Author.cs
namespace DTOMap.Core.Models
{
[Table("Author")]
internal class Author
{
[Key]
public int id { get; set; }
[Required, MaxLength(255)]
public string firstName { get; set; }
[Required,MaxLength(255)]
public string lastName { get; set; }
}
}
Book.cs
namespace DTOMap.Core.Models
{
[Table("Book")]
internal class Book
{
[Key]
public int id { get; set; }
[Required,MaxLength(255)]
public string name { get; set; }
[Required]
public int authorId { get; set; }
[Required]
public Author author { get; set; }
}
}
AuthorDTO.cs
namespace DTOMap.Domain.DTO
{
public class AuthorDTO
{
public int id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
}
BookDTO.cs
namespace DTOMap.Domain.DTO
{
public class BookDTO
{
public int id { get; set; }
public string name { get; set; }
public int authorId { get; set; }
public AuthorDTO author { get; set; }
}
}
IRepository.cs
namespace DTOMap.Domain.Interface
{
public interface IRepository<T>
{
T Add(T obj);
}
}
MyMapper.cs
namespace DTOMap.Core
{
public class MyMapper : Profile
{
public MyMapper()
{
CreateMap<Book, BookDTO>();
CreateMap<BookDTO, Book>();
CreateMap<Author, AuthorDTO>();
CreateMap<AuthorDTO, Author>();
}
}
}
program.cs
... Some Fcts
builder.Services.AddTransient<IRepository<BookDTO>, BookRepository>();
builder.Services.AddTransient<IRepository<AuthorDTO>, AuthorRepository>();
... Some Fcts
If you need any other information, please ask me.
I am trying to apply the odata query to my automapper - mappings at my efcore context. Everything works as expected until I use the $select query option.
When I try to use the select keyword in the request to my odata - controller, I get the exception:
SerializationException: 'SourceSourceInjectedQuery`2' cannot be serialized using the ODataMediaTypeFormatter.
I am using the UseAsDataSource - Extension method because it was recommended here on github.
This is my oDataController:
public class StudentsController : ODataController {
private readonly SchoolContext schoolContext;
public StudentsController(SchoolContext schoolContext) {
this.schoolContext = schoolContext;
}
[EnableQuery]
public IActionResult Get() {
return Ok(
schoolContext
.Students
.UseAsDataSource()
.For<StudentVM>()
);
}
}
This is my Entity for EFCore:
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
And this is my mappingprofile for automapper:
public class StudentVM {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
}
public class StudentProfile : Profile {
public StudentProfile() {
CreateMap<Student, StudentVM>();
}
}
Do I need some specific mapping to do this?
I figured out I had a mistake in my configuration of the odataservice inside my startup.cs
private static IEdmModel GetEdmModel() {
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Student>("Students");
builder.EntitySet<Course>("Courses");
return builder.GetEdmModel();
}
I put my Entities instead of my ViewModels there. This is the fixed code:
private static IEdmModel GetEdmModel() {
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<StudentVM>("Students");
builder.EntitySet<CourseVM>("Courses");
return builder.GetEdmModel();
}
Now it's working as expected
i'm trying to apply LAYERS Concept on demo project developed using mvc and entity framework both
Data Annotations : for validations in Data Access Layer and
Fluent API : for mapping and tables relations
Problem : DbContext didn't Create DB and there is a Runtime Exception :
The type 'Domain.DataLayer.Member' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
Code : my solutions consists of :
1- class library (Domain.Classes project): where i wrote all of my classes
public class Member
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FullName { get; set; }
}
2- DAL (Domain.DataLayer project): also another class library and i referenced domain.classes
namespace Domain.DataLayer.Repositories
{
[MetadataType(typeof(MemberMetadata))]
public partial class Member : Classes.Member , IValidatableObject
{
public Member()
{
Tasks = new HashSet<Task>();
History = new HashSet<Commint>();
}
public string ConfirmPassword { get; set; }
public HashSet<Task> Tasks { get; set; }
public HashSet<Commint> History { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (!string.Equals(Password,ConfirmPassword))
{
result.Add(new ValidationResult("mismatch pwsd", new[] {"ConfirmPassword" }));
}
return result;
}
}
}
and i used repository pattern :
public class MemberRepository : IRepository<Member>
{
public Task<IQueryable<Member>> GetAllEntities()
{
return Task<IQueryable<Member>>.Factory.StartNew(() => new Context().Members.AsQueryable());
}
}
3-BLL : for sake of simplicity : there is no Business Logic Layer
4- PL (Domain.Application MVC Project) : Member Controller :
public async Task<ActionResult> Index()
{
var members = await _repository.GetAllEntities();
return View(members);
}
Note : i depended on DbContext to create DB with name like : Domain.DataLayer.Context but it didn't craete DB so i created the DB and passed the connectionString through Context constructor like this :
namespace Domain.DataLayer
{
public class Context : DbContext
{
public Context(): base("InterviewDemo") // i tried also base("name=InterviewDemo")
{
}
public DbSet<Member> Members { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Commint> TaskHistory { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MemberConfig());
modelBuilder.Configurations.Add(new TaskConfig());
modelBuilder.Configurations.Add(new CommintConfig());
base.OnModelCreating(modelBuilder);
}
}
}
I'm having the following error in my wcf client.
NetDispatcherFaultException was unhandled.
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:GetVehicleResult. The InnerException message was 'Error in line 1 position 266. Element 'http://tempuri.org/:GetVehicleResult' contains data from a type that maps to the name 'http://schemas.datacontract.org/2004/07/WCFServer:Car'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'Car' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
Can anyone help me where is the fault.
WCF Server
IVehicle
--------
[ServiceContract]
public interface IVehicleService
{
[OperationContract]
Vehicle GetVehicle(int type);
[OperationContract]
int GetNumberOfWheels(Vehicle vehicle);
}
VehicleService
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class VehicleService : IVehicleService
{
public Vehicle GetVehicle(int type)
{
switch (type)
{
case 0:
return new Car()
{
ID = 10,
Brand = "Volvo",
SteeringWheelPosition = "left"
};
case 1:
return new bike()
{
ID = 11,
Brand = "Scott",
HasFrontWheelBreak = true
};
case 2:
return new Kidsbike()
{
ID = 12,
Brand = "Kid Scott",
HasFrontWheelBreak = false,
HasSupportingWheels = true
};
default:
return null;
}
}
public int GetNumberOfWheels(Vehicle vehicle)
{
return vehicle.NoOfWheels;
}
}
abstract class
[KnownType(typeof(Car))]
[KnownType(typeof(bike))]
[DataContract]
public abstract class Vehicle
{
[DataMember]
public int ID { get; set; }
abstract public int NoOfWheels { get; }
[DataMember]
public string Brand { get; set; }
}
concrete classes
[DataContract]
public class Car : Vehicle
{
override public int NoOfWheels { get { return 4; } }
[DataMember]
public string SteeringWheelPosition { get; set; }
}
[KnownType(typeof(Kidsbike))]
[DataContract]
public class bike : Vehicle
{
override public int NoOfWheels { get { return 2; } }
[DataMember]
public bool HasFrontWheelBreak { get; set; }
}
[DataContract]
public class Kidsbike : bike
{
[DataMember]
public bool HasSupportingWheels { get; set; }
}
WCF Client
namespace WCFClient
{
[ServiceContract]
public interface IVehicleService
{
[OperationContract]
Vehicle GetVehicle(int type);
[OperationContract]
int GetNumberOfWheels(Vehicle vehicle);
}
}
namespace WCFClient
{
[KnownType(typeof(Car))]
[KnownType(typeof(bike))]
[DataContract]
public abstract class Vehicle
{
[DataMember]
public int ID { get; set; }
abstract public int NoOfWheels { get; }
[DataMember]
public string Brand { get; set; }
}
[DataContract]
public class Car : Vehicle
{
override public int NoOfWheels { get { return 0; } }
[DataMember]
public string SteeringWheelPosition { get; set; }
}
[KnownType(typeof(Kidsbike))]
[DataContract]
public class bike : Vehicle
{
override public int NoOfWheels { get { return 0; } }
[DataMember]
public bool HasFrontWheelBreak { get; set; }
}
[DataContract]
public class Kidsbike : bike
{
[DataMember]
public bool HasSupportingWheels { get; set; }
}
}
private void btnGetVehicle_Click(object sender, EventArgs e)
{
Car carObj = (Car)fclient.GetVehicle(0);
}
just creating proxy in client side . I can able to call the service successfully, but in response im having the problem. I try with Knowntype attribute. Whats wrong in this.
The following code work fine without error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1 {
[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(bike))]
[ServiceKnownType(typeof(Kidsbike))]
[ServiceContract]
public interface IVehicleService {
[OperationContract]
Vehicle GetVehicle(int type);
[OperationContract]
int GetNumberOfWheels(Vehicle vehicle);
}
[DataContract]
public abstract class Vehicle
{
[DataMember]
public int ID { get; set; }
abstract public int NoOfWheels { get; }
[DataMember]
public string Brand { get; set; }
}
[DataContract]
public class Car : Vehicle
{
override public int NoOfWheels { get { return 0; } }
[DataMember]
public string SteeringWheelPosition { get; set; }
}
[KnownType(typeof(Kidsbike))]
[DataContract]
public class bike : Vehicle
{
override public int NoOfWheels { get { return 0; } }
[DataMember]
public bool HasFrontWheelBreak { get; set; }
}
[DataContract]
public class Kidsbike : bike
{
[DataMember]
public bool HasSupportingWheels { get; set; }
}
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class VehicleService : IVehicleService
{
public Vehicle GetVehicle(int type)
{
switch (type)
{
case 0:
return new Car()
{
ID = 10,
Brand = "Volvo",
SteeringWheelPosition = "left"
};
case 1:
return new bike()
{
ID = 11,
Brand = "Scott",
HasFrontWheelBreak = true
};
case 2:
return new Kidsbike()
{
ID = 12,
Brand = "Kid Scott",
HasFrontWheelBreak = false,
HasSupportingWheels = true
};
default:
return null;
}
}
public int GetNumberOfWheels(Vehicle vehicle)
{
return vehicle.NoOfWheels;
}
}
}
Svc file:
<%# ServiceHost Language="C#" Debug="true" Service="WcfService1.VehicleService" CodeBehind="Service1.svc.cs" %>
Testing service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WcfService1;
namespace Test {
class Program {
static void Main(string[] args) {
BasicHttpBinding hproxy = new BasicHttpBinding();
hproxy.MaxReceivedMessageSize = 2147483647;
hproxy.MaxBufferSize = 2147483647;
hproxy.MaxBufferPoolSize = 2147483647;
EndpointAddress eaddrr = new EndpointAddress("http://localhost:62807/Service1.svc");
ChannelFactory<IVehicleService> CFactoryobj1 = new ChannelFactory<IVehicleService>(hproxy, eaddrr);
IVehicleService isclientobj1 = CFactoryobj1.CreateChannel();
Car ve = (Car)isclientobj1.GetVehicle(0);
}
}
}
The KnownType should be used on the service contract interface itself not the vehicle class since it is the one that is returning the Vehicle object for one of its operations. Adding KnownType to the Vehicle class does nothing I think. because by default now, you don't need to add DataContract to your class for them to be useable in WCF. so you should have something like below.
[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(bike))]
[ServiceKnownType(typeof(Kidsbike))]
[ServiceContract]
public interface IVehicleService
{
[OperationContract]
Vehicle GetVehicle(int type);
[OperationContract]
int GetNumberOfWheels(Vehicle vehicle);
}
I am having an issue with using Fluent NHibernate automapping with Inheritance. Below is my entity setup (abbreviated for simplicity). I have configured Fluent NHibernate to create 1 class for the hierarchy with a discriminator column. The automapping appears to be working correctly as when I generate a database, one table is created named "AddressBase" with a discriminator column that signals what type of address each row is.
The problem lies in the face that when I call the method "GetPrimaryBillingAddress()" on the UserAccount class, instead of just querying Billing Addresses, NHibernate is creating a query that looks at both Billing and Shipping Addresses. It doesn't take into account the discriminator at all. I am assuming there is some sort of configuration I can set but have not been able to find anything.
public abstract class AddressBase : ActiveRecord<AddressBase>
{
public virtual long Id { get; set; }
public virtual string Address1 { get; set; }
}
public class AddressBilling : AddressBase
{
public class TypedQuery : ActiveRecordQuery<AddressBilling> { }
public virtual bool IsPrimary { get; set; }
}
public class AddressShipping : AddressBase
{
public class TypedQuery : ActiveRecordQuery<AddressShipping> { }
[Display(Name = "Is Primary")]
public virtual bool IsPrimary { get; set; }
}
public class UserAccount : ActiveRecord<UserAccount>
{
public virtual long Id { get; set; }
public virtual IList<AddressBilling> BillingAddresses { get; set; }
public virtual IList<AddressShipping> ShippingAddresses { get; set; }
public UserAccount()
{
BillingAddresses = new List<AddressBilling>();
ShippingAddresses = new List<AddressShipping>();
}
public virtual AddressBilling GetPrimaryBillingAddress()
{
if (BillingAddresses.Any(x => x.IsPrimary))
{
return BillingAddresses.Single(x => x.IsPrimary);
}
return BillingAddresses.FirstOrDefault();
}
public virtual AddressShipping GetPrimaryShippingAddress()
{
if (ShippingAddresses.Any(x => x.IsPrimary)) {
return ShippingAddresses.Single(x => x.IsPrimary);
}
return ShippingAddresses.FirstOrDefault();
}
}
UPDATE:
Here is the Mapping override functions used in the automapping:
private static FluentConfiguration GetFluentConfiguration(string connectionStringName = "CS")
{
var autoMapping = AutoMap
.AssemblyOf<Product>(new Mapping.AutoMappingConfiguration())
.Conventions.Setup(c =>
{
c.Add<Mapping.ForeignKeyConvention>();
c.Add<Mapping.DiscriminatorConvention>();
})
.IgnoreBase<AddressBilling.TypedQuery>()
.IgnoreBase<AddressShipping.TypedQuery>()
.IncludeBase<AddressBase>();
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey(connectionStringName)))
.Mappings(m => m.AutoMappings.Add(autoMapping));
}
public class AutoMappingConfiguration : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
var isStatic = type.IsAbstract && type.IsSealed;
return type.Namespace == typeof(Entities.Product).Namespace && !isStatic;
}
public override bool IsDiscriminated(Type type)
{
if (type == (typeof(Entities.AddressBase))) {
return true;
}
return false;
}
public override string GetDiscriminatorColumn(Type type)
{
return "Type";
}
public class DiscriminatorConvention : ISubclassConvention
{
public void Apply(ISubclassInstance instance)
{
//Address
if (instance.Name == typeof(AddressBilling).AssemblyQualifiedName)
{
instance.DiscriminatorValue(Enums.AddressType.BillingAddress);
}
else if (instance.Name == typeof(AddressShipping).AssemblyQualifiedName)
{
instance.DiscriminatorValue(Enums.AddressType.ShippingAddress);
}
}
}
Thanks!
Please, try to change your class UserAccount like this:
public class UserAccount : ActiveRecord<UserAccount>
{
public virtual IList<AddressBase> Addresses { get; set; }
public virtual IList<AddressBilling> BillingAddresses { get {return this.Addresses.OfType<AddressBilling>();} }
public virtual IList<AddressShipping> ShippingAddresses { get {return this.Addresses.OfType<AddressShipping>();} }
// ...
}
Of course, only Addresses property should be mapped here.