I'm learning WCF, and tried to make a small service that exposes a Project and its tasks (the standard Entity Framework hello world).
The class structure is the following:
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
public class Task
{
public int TaskId { get; set; }
public string Title { get; set; }
public virtual Project RelatedProject { get; set; }
}
The DB context comes after:
public class ProjectContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<Task> Tasks { get; set; }
}
Finally, the service endpoint:
public IEnumerable<Project> getProjects()
{
ProjectContext p = new ProjectContext();
return p.Projects.AsEnumerable();
}
The problem is that this model will throw a System.ServiceModel.CommunicationException, but, If I remove the virtual properties from the model, It would work, but I would loose the entity framework links between Project and Task.
Anyone with a similar setup?
I banged my head against the wall several hours with this one. After extensive debugging, google gave the answer and I feel right to post it here since this was the first result I got in google.
Add this class on top of your [ServiceContract] interface declaration (typically IProjectService.cs
public class ApplyDataContractResolverAttribute : Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
{
}
public void ApplyClientBehavior(OperationDescription description, System.ServiceModel.Dispatcher.ClientOperation proxy)
{
var dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void ApplyDispatchBehavior(OperationDescription description, System.ServiceModel.Dispatcher.DispatchOperation dispatch)
{
var dataContractSerializerOperationBehavior =
description.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractSerializerOperationBehavior.DataContractResolver =
new ProxyDataContractResolver();
}
public void Validate(OperationDescription description)
{
// Do validation.
}
}
Requirements are
using System.ServiceModel.Description;
using System.Data.Objects;
using System.ServiceModel.Channels;
Then under the [OperationContract] keyword add [ApplyDataContractResolver] keyword and you are set!
Big thanks to http://blog.rsuter.com/?p=286
For sending data trough WCF you should disable lazy loading (dataContext.ContextOptions.LazyLoadingEnabled = false;).
To be sure the data you want is loaded you need to use eager loading ( trough the Include method).
You need to change your function to:
public IEnumerable<Project> getProjects()
{
ProjectContext p = new ProjectContext();
p.ContextOptions.LazyLoadingEnabled = false;
return p.Projects.Include("Tasks").AsEnumerable();
}
Related
I am working on a new ASP.NET Core 3.1.1 API with Microsoft.AspNetCore.OData v 7.3.0, AutoMapper v9.0.0 and Microsoft.AspNetCore.Mvc.NewtonsoftJson v3.1.1
I am getting the following error when I make a POST to the Accounts endpoint using Postman v7.18.0;
AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
I have reviewed the similar questions list when creating this question but was unable to find a solution.
In reviewing google searches for AutoMapper OData Enums all I could find were the recommendation to decorate my dto class with...
[AutoMap(typeof(Account))]
... and to decorate my dto enum properties with ...
[JsonConverter(typeof(StringEnumConverter))]
However, I still get the error. I found references to using an AutoMapperProfile class with a mapper defined as
CreateMap<Account, AccountModel>().ReverseMap();
But it appears that AutoMapper v9.0.0 no longer has a CreateMap method. My understanding was that adding the [AutoMap(typeof(Account))] to the dto class had the same effect as creating the map in the profile class.
I feel like I am going in circles at this point here so I though I would reach out to the SO community. I am sure it is something simple, I am just not seeing it.
Here is my POST request body from Postman;
{
"#odata.context": "https://localhost:44367/v1/$metadata#Accounts",
"AccountName": "Test Provider",
"AccountType": "Provider",
"IsTaxExempt": false,
"Status": "Active"
}
Here is my AccountsController Post method;
[ODataRoute]
[Produces("application/json;odata.metadata=minimal")]
[ProducesResponseType(typeof(AccountModel), Status201Created)]
[ProducesResponseType(Status400BadRequest)]
public async Task<IActionResult> Post([FromBody] AccountModel record)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
record.Id = new Guid();
var entity = _mapper.Map<Account>(record);
_context.Add(entity);
await _context.SaveChangesAsync();
var createdRecord = _mapper.Map<AccountModel>(entity);
return Created(createdRecord);
}
Here is my Account entity class;
public class Account : EntityBase
{
[Required]
[Column(TypeName = "nvarchar(50)")]
[MaxLength(50)]
public string AccountName { get; set; }
public AccountTypes AccountType { get; set; }
public bool IsTaxExempt { get; set; }
}
Here is the EntityBase class;
public class EntityBase
{
[Required]
public Guid Id { get; set; }
public DateTimeOffset? DateTimeCreated { get; set; } = DateTime.UtcNow;
public DateTimeOffset? DateTimeLastModified { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public StatusTypes Status { get; set; }
public bool DeleteFlag { get; set; }
}
Here is my Account DTO class;
[Filter, Count, Expand, OrderBy, Page, Select]
[AutoMap(typeof(Account))]
public class AccountModel : BaseModel
{
[Required]
[MaxLength(50)]
public string AccountName { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public AccountTypes AccountType { get; set; }
public bool IsTaxExempt { get; set; }
}
Here is my BaseModel class;
[Select, Filter]
public class BaseModel
{
public Guid Id { get; set; }
public DateTimeOffset DateTimeCreated { get; set; } = DateTime.UtcNow;
public DateTimeOffset DateTimeLastModified { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public StatusTypes Status { get; set; }
public bool DeleteFlag { get; set; }
}
And here are my Enums for AccountTypes and StatusTypes
public enum AccountTypes
{
Customer = 0,
Reseller = 1,
Provider = 2,
}
public enum StatusTypes
{
Active = 0,
Inactive = 1,
}
Any ideas?
It turns out that I needed to create an instance of an AutoMapper MapperConfiguration and assign it to the mapper.
I ended up putting in in the constructor of the Controller, for example;
public AccountsController(CdContext context, IMapper mapper)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
var config = new MapperConfiguration(cfg => cfg.CreateMap<Account, AccountModel>().ReverseMap());
_mapper = new Mapper(config);
}
After I did this, everything worked as expected.
Here is a link to AutoMappers docs on the subject.
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);
}
}
}
First of all, thanks for reading my question.
I am developing a solution using VS 2012 using ADO.NET Entity Framework (5 i think, the latest version). All is working fine until I introduce a WCF service as a Business Layer (this is an assignment for school, I cannot scrap WCF from Business Layer).
The issue is that when I request data from the database. When I have a method that returns a string from the database, it works just fine (since its a primitive). But when it returns an Entity object (Such as Account), it all goes to hell.
Exception: (Yeah, its very vague).
An error occurred while receiving the HTTP response to http://localhost:8733/Services/AccountsManager. 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.
What I tried: I tried modifying the Entites.tt file to add the [DataContract] [DataMember] Attribute. This is because in the older versions of EF, it seemed to be doing it on its own. But I do not know if this is neccessary since it allows me to compile and does not complain that it is not serializable.
This is how it looks at first:
namespace CommonLayer
{
using System;
using System.Collections.Generic;
public partial class Account
{
public Account()
{
this.Transactions = new HashSet<Transaction>();
this.Transactions1 = new HashSet<Transaction>();
}
public System.Guid ID { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public int Currency { get; set; }
public decimal Balance { get; set; }
public System.DateTime DateOpened { get; set; }
public Nullable<int> Duration { get; set; }
public string UserName { get; set; }
public virtual AccountType AccountType { get; set; }
public virtual Currency Currency1 { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Transaction> Transactions1 { get; set; }
}
}
How it looks after modification:
namespace CommonLayer
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract] public partial class Account
{
public Account()
{
this.Transactions = new HashSet<Transaction>();
this.Transactions1 = new HashSet<Transaction>();
}
[DataMember] public System.Guid ID { get; set; }
[DataMember] public int Type { get; set; }
[DataMember] public string Name { get; set; }
[DataMember] public int Currency { get; set; }
[DataMember] public decimal Balance { get; set; }
[DataMember] public System.DateTime DateOpened { get; set; }
[DataMember] public Nullable<int> Duration { get; set; }
[DataMember] public string UserName { get; set; }
public virtual AccountType AccountType { get; set; }
public virtual Currency Currency1 { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public virtual ICollection<Transaction> Transactions1 { get; set; }
}
}
Any pointers are greatly appreciated.
My WCF Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
[ServiceContract]
interface IAccountsManager
{
[OperationContract]
List<CommonLayer.Account> GetAccounts(String UserName);
[OperationContract]
String GetData();
[OperationContract]
CommonLayer.Account GetAccount(String UserName);
}
class AccountsManager: IAccountsManager, IDisposable
{
public List<CommonLayer.Account> GetAccounts(String UserName)
{
return DataLayer.AccountsRepository.Instance.GetAccountList(UserName).ToList();
}
public String GetData()
{
CommonLayer.Account acc = this.GetAccounts("test").FirstOrDefault();
return acc.DateOpened.ToString();
}
public CommonLayer.Account GetAccount(String UserName)
{
return this.GetAccounts(UserName).FirstOrDefault();
}
public void Dispose()
{
DataLayer.AccountsRepository.Reset();
}
}
}
You need to use a DTO (Data Transfer Object) and map from your EF object to your DTO.
So the service might accept an object called MyDto looking like:
[DataContract]
public class MyDto {
[DataMember]
public int Id {get;set;}
}
and a static mapping class with methods
public static MyEntity Map(MyDto dto) {
return new MyEntity { Id = dto.Id };
}
public static MyDto Map(MyEntity entity) {
return new MyDto { Id = entity.Id };
}
You can then map as required so that the service can use the DTO and Entity Framework can use the Entity.
It seems that when the EF class has Navigation properties (like ICollection<Transaction> Transactions in your class) it will fails when being transferred over WCF.
After many searches I could not find any solution except mapping an EF class into equivalent DTO class that is exactly the same as the EF class except the Navigation propertis and the constructor (i.e. I have stripped all virtual propertis (like ICollection ones) and the ctor from the EF class and have created from that a new class called the same as my EF class plus Dto suffix (e.g. CustomerDto).
I've used AutoMapper to automatically map an EF object into Dto-equivalent one. E.g:
var customer = getCustomer(cid);
var customerDto = Mapper.Map<CustomerDto>(customer);
return customerDto;
My WCF contract includes
[OperationContract]
CustomerDto getCustomerData(int cid);
In addition I needed to do one time initialization of the Mapper. I've done it within Global.asax as follows:
Mapper.CreateMap<Customer, CustomerDto>();
What I have done is changed my Entities.Edmx file. Firstly, I deleted all (2) ".tt" files. Then i changed Code Generation Strategy from None to Default. This seemed to solve all my problems.
We're using RavenDB saga storage, but the saga data isn't being persisted after the starting message handler. I only see a handful of subscription documents in the database. I'm not sure what to check next. Ideas?
I have a saga:
public class BuyerWaitingOnDocumentsDistributor :
Saga<BuyerDocumentDistributorData>,
IAmStartedByMessages<DocumentVersionRequiresBuyerSignature>
{
public void Handle(DocumentVersionRequiresEmployeeSignature message)
{
Data.DocumentVersionId = message.DocumentVersionId.Value;
// Business logic goes here
}
// Other handlers & methods here
}
and saga entity:
public class BuyerDocumentDistributorData : IContainSagaData
{
public virtual Guid Id { get; set; }
public virtual string Originator { get; set; }
public virtual string OriginalMessageId { get; set; }
public virtual Guid DocumentVersionId { get; set; }
public virtual EmployeeId[] AuthorizedToSign { get; set; }
}
and saga finder:
public class BuyerWaitingOnDocumentsDistributorSagaFinder :
IFindSagas<BuyerDocumentDistributorData>.Using<DocumentVersionRequiresBuyerSignature>,
IFindSagas<BuyerDocumentDistributorData>.Using<DocumentVersionSignedByBuyer>,
IFindSagas<BuyerDocumentDistributorData>.Using<DocumentVersionNoLongerRequiresSignature>
{
private static readonly ILog Log = LogManager.GetLogger(typeof (BuyerWaitingOnDocumentsDistributorSagaFinder));
public ISagaPersister Persister { get; set; }
public BuyerDocumentDistributorData FindBy(DocumentVersionRequiresBuyerSignature message)
{
return Persister.Get<BuyerDocumentDistributorData>("DocumentVersionId", message.DocumentVersionId.Value);
}
public BuyerDocumentDistributorData FindBy(DocumentVersionSignedByBuyer message)
{
return Persister.Get<BuyerDocumentDistributorData>("DocumentVersionId", message.DocumentVersionId.Value);
}
public BuyerDocumentDistributorData FindBy(DocumentVersionNoLongerRequiresSignature message)
{
return Persister.Get<BuyerDocumentDistributorData>("DocumentVersionId", message.DocumentVersionId.Value);
}
}
I've also asked this question on the NServiceBus Yahoo group: http://tech.groups.yahoo.com/group/nservicebus/message/13265
You did not give your endpointconfig, so I'm unsure which container you are using.
We experience the same (saga not getting persisted) when using the NinjectBuilder. Using the DefaultBuilder works ok.
I am new to WCF services. I was asked to manually create a WCF service. I did the following:
Created a new project Console App.
Created a class called Evaluation
Created an interface called IEvaluatorService
Created a class EvaluationService implementing the interface IEvaluatorService
I need to use the following address: http://localhost:8000/Evaluations then test my service via WcfTestClient. I am not sure what to do next. Code below.
Thanks in advance for any help!
namespace Evaluations
{
[ServiceContract]
interface IEvaluatorService
{
[OperationContract(Name="AddEvaluation")]
int Add(string user, string content);
[OperationContract(Name="RemoveEvaluation")]
void Remove([MessageParameter(Name="existingID")] int id);
[OperationContract(Name="GetAllEvaluations")]
Evaluation[] GetAll();
[OperationContract(Name="GetEvaluation")]
Evaluation Get(int id);
[OperationContract(Name="GetAllEvaluationsFrom")]
Evaluation[] GetAll([MessageParameter(Name = "username")] string submitter);
}
}
namespace Evaluations
{
class EvaluationService : IEvaluatorService
{
List<Evaluation> myList = new List<Evaluation>();
static int count = 0;
public int Add(string user, string content)
{
Evaluation eval = new Evaluation()
{
UniqueID = count++,
Submitter = user,
SubmissionTime = DateTime.Now,
Text = content
};
myList.Add(eval);
return eval.UniqueID;
}
public void Remove(int id)
{
myList.RemoveAt(id);
}
public Evaluation[] GetAll()
{
return myList.ToArray<Evaluation>();
}
public Evaluation Get(int id)
{
throw new NotImplementedException();
}
public Evaluation[] GetAll(string submitter)
{
throw new NotImplementedException();
}
}
}
namespace Evaluations
{
[DataContract]
class Evaluation
{
[DataMember]
public string Submitter { get; set; }
[DataMember]
public int UniqueID { get; set; }
[DataMember]
public DateTime SubmissionTime { get; set; }
[DataMember]
public string Text { get; set; }
}
}
The easiest thing to do is...
go into Visual Studio
right click on your project
select Add New
choose WCF Service
See what code Visual Studio added and follow that pattern for your service.