Orchard CMS record mapping from external Assembly - orchardcms

I have an Orchard CMS module that uses external library. And I need to use some classes from that library as part of Orchard records.
For example, external assembly contains class
public class Operation {
public virtual long Id { get; set; }
public virtual string OperationType { get; set; }
}
I have to store it in the database, to use it with Orchard IRepository and use it as part of other Orchard CMS records, such as
public class HistoryRecord {
public virtual long Id { get; set; }
public virtual DateTime Updated { get; set; }
public virtual Operation Operation { get; set; }
}

I was able to get a partial solution, based on Fluet Configuration. However, it works only if the classes correspond to the Orchard's naming conventions.
Here it is:
public class SessionConfiguration : ISessionConfigurationEvents {
public void Created(FluentConfiguration cfg, AutoPersistenceModel defaultModel) {
var ts = new TypeSource(new[] { typeof(OperationRecord) });
cfg.Mappings(m => m.AutoMappings.Add(AutoMap.Source(ts)
.Override<OperationRecord>(mapping => mapping.Table("Custom_Module_OperationRecord"))
));
}
public void Prepared(FluentConfiguration cfg) { }
public void Building(Configuration cfg) { }
public void Finished(Configuration cfg) { }
public void ComputingHash(Hash hash) { }
}
public class TypeSource : ITypeSource {
private readonly IEnumerable<Type> _types;
public TypeSource(IEnumerable<Type> types) {
_types = types;
}
public IEnumerable<Type> GetTypes() {
return _types;
}
public void LogSource(IDiagnosticLogger logger) {
throw new NotImplementedException();
}
public string GetIdentifier() {
throw new NotImplementedException();
}
}

Related

DDD Service Method Granularity

So, I'm building a system for managing contacts. My contact domain model has quite a few string properties, as well as booleans. In the spirit of keeping behavior inside of the domain models, I've gone down the path of creating "update methods." I'm starting to feel like it's getting a bit burdensome. In the past, CRUD apps would just have a single update method and it would set all of the properties in one shot.
Am I on the right path? I'm concerned about having 10 - 15 update methods on my domain service and domain entities.
FYI, the example given is a bit contrived, so imagine a model with lots of string and boolean properties.
// Application Layer Stuff
public class UpdateContactCommand
{
public UpdateNamePredicate UpdateName { get; set; }
public UpdatePhonePredicate UpdatePhone { get; set; }
public int ContactId { get; set; }
}
public class UpdateNamePredicate
{
public string NewFirstName { get; set; }
public string NewLastName { get; set; }
}
public class UpdatePhonePredicate
{
public string NewPHone { get; set; }
}
public class UpdateContactResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
public interface IWcfService
{
UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand);
}
public class WcfService : IWcfService
{
private readonly IContactService _contactService;
public WcfService(IContactService contactService)
{
_contactService = contactService;
}
public UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand)
{
if (updateContactCommand.UpdateName != null)
{
_contactService.UpdateName(updateContactCommand.ContactId, updateContactCommand.UpdateName.NewFirstName,
updateContactCommand.UpdateName.NewLastName);
}
if (updateContactCommand.UpdatePhone != null)
{
_contactService.UpdatePhone(updateContactCommand.ContactId, updateContactCommand.UpdatePhone.NewPHone);
}
return new UpdateContactResponse();
}
}
// Domain Layer
public interface IContactService
{
// There are lots more of these
void UpdateName(int contactId, string newFirstName, string newLastName);
void UpdatePhone(int contactId, string newPhone);
}
public class ContactService : IContactService
{
private readonly IContactRepository _contactRepository;
public ContactService(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
public void UpdateName(int contactId, string newFirstName, string newLastName)
{
var contact = _contactRepository.GetById(contactId);
contact.SetName(newFirstName, newLastName);
_contactRepository.Commit();
}
public void UpdatePhone(int contactId, string newPhone)
{
var contact = _contactRepository.GetById(contactId);
contact.SetPhone(newPhone);
_contactRepository.Commit();
}
}
public interface IContact
{
int Id { get; set; }
// There are lots more of these
void SetName(string newFirstName, string newLastName);
void SetPhone(string newPhone);
}
public class Contact : IContact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public void SetName(string newFirstName, string newLastName)
{
FirstName = newFirstName;
LastName = newLastName;
}
public void SetPhone(string newPhone)
{
Phone = newPhone;
}
}
public interface IContactRepository
{
IContact GetById(int id);
void Commit();
}
public class ContactRepository : IContactRepository
{
public IContact GetById(int id)
{
// Not important
throw new NotImplementedException();
}
public void Commit()
{
// Not important
throw new NotImplementedException();
}
}
First of all, not all applications lend themselves well to a DDD approach. If you say your application could pretty much have been implemented in a CRUDish way before, chances are it's still CRUD now. Don't try to apply DDD on any app because it's the shiny new thing.
That being said, you don't just write "update methods" for the fun of it. They have to reflect the domain tasks your user wants to perform. Why does the user want to update a Contact ? Has the contact moved or just changed phone number ? Changed marital status and name ? Has the point of contact in a company been taken over by another employee ?
Usually, you won't have tons of update methods for a given entity. There's always a way to group changes in operations that are meaningful for the domain. Good ways to force yourself to do it are :
Think about the maximum number of form fields you can reasonably display to the user. Couldn't you split that complex UI into smaller, more meaningful screens ? From there you have to start reasoning (preferably with the help of a domain expert) about the tasks these should reflect.
Make your entity fields immutable from the outside. Thus you'll have to think harder about their true nature -- what should be in the constructor ? what should some other manipulation methods be ?

ServiceStack and FluentValidation NOT firing

I must be overlooking something around getting the fluent-validation to fire within basic Service-Stack application I created.
I have been following the example found here. For the life of me I can't seem to get my validators fire????
Crumbs, there must be something stupid that I'm missing....???
I'm issuing a user request against the User-Service (http://my.service/users), the request goes straight through without invoking the appropriate validator registered.
Request is :
{"Name":"","Company":"Co","Age":10,"Count":110,"Address":"123 brown str."}
Response :
"user saved..."
Here is the code :
1.DTO
[Route("/users")]
public class User
{
public string Name { get; set; }
public string Company { get; set; }
public int Age { get; set; }
public int Count { get; set; }
public string Address { get; set; }
}
2.Validator
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(r => r.Name).NotEmpty();
RuleFor(r => r.Age).GreaterThan(0);
}
}
3.AppHostBase
public class ValidationAppHost : AppHostBase
{
public ValidationAppHost()
: base("Validation Test", typeof(UserService).Assembly)
{
}
public override void Configure(Funq.Container container)
{
Plugins.Add(new ValidationFeature());
//This method scans the assembly for validators
container.RegisterValidators(typeof(UserValidator).Assembly);
}
}
4.Service
public class UserService : Service
{
public object Any(User user)
{
return "user saved...";
}
}
5.Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
new ValidationAppHost().Init();
}
Ok....found the issue....I (in error) installed (via nuget) and referenced within my project the FluentValidation.dll with Service-Stack's FluentValidation implementation (see namespace ServiceStack.FluentValidation).
Once I removed this the sole incorrect FluentValidation reference and ensured that my validator extended from the service-stack implementation of the AbstractValidator the validators fired correctly...

ServiceStack empty metadata

Seeing a strange problem, getting empty metata pages for xml,json and jvs.
Using the following command line app. How does one debug these issues?
namespace ConsoleApplication2
{
public struct NativeUser
{
public int login;
public string group;
public string name;
}
[DataContract]
public class User
{
private NativeUser _native;
public User() { }
public User(NativeUser native)
{
_native = native;
}
public static implicit operator NativeUser(User user)
{
return user._native;
}
public static implicit operator User(NativeUser native)
{
return new User(native);
}
// ReSharper disable InconsistentNaming
[DataMember]
public int login
{
get { return _native.login; }
set { _native.login = value; }
}
[DataMember]
public string group
{
get { return _native.group; }
set { _native.group = value; }
}
[DataMember]
public string name
{
get { return _native.name; }
set { _native.name = value; }
}
}
[Description("GET account, all or by list of groups or by list of logins")]
[Route("/accounts/{groups}", "GET")]
[Route("/accounts/{logins}", "GET")]
[Route("/accounts/", "GET")]
public class Accounts : IReturn<User[]>
{
public string[] groups { set; get; }
public int[] logins { set; get; }
public Accounts() { }
public Accounts(params int[] logins)
{
this.logins = logins;
}
public Accounts(params string[] groups)
{
this.groups = groups;
}
}
public class Host : AppHostHttpListenerBase
{
public Host() : base("Test",
typeof(Accounts).Assembly)
{
}
public override void Configure(Funq.Container container)
{
}
}
public class Servce : IService
{
public object Get(Accounts request)
{
return new List<User>(){new User(new NativeUser())};
}
}
class Program
{
static void Main(string[] args)
{
var host = new Host();
host.Init();
host.Start("http://+:12345/");
global::System.Console.ReadLine();
}
}
}
Nm, found the bug :
public class Accounts : IReturn<User[]>
needs to be
public class Accounts : IReturn<List<User>>
Another very note worthy thing: All DTO's and objects being passed back and fourth in the DTO's require an empty constructor in order for the metata data to be properly generated.
Not sure if this is by design or a bug

ServiceStack registration

I created a custom RegistrationFeature:
public class CustomRegistrationFeature: IPlugin
{
private string AtRestPath {get; set;}
public CustomRegistrationFeature ()
{
AtRestPath = "/register";
}
public void Register (IAppHost apphost)
{
appHost.RegisterService <CustomRegistrationService>(AtRestPath);
appHost.RegisterAs <CustomRegistrationValidator, IValidator <CustomRegistration>>();
}
}
I configured in AppHost:
Plugins.Add (new CustomRegistrationFeature ());
but in the metadata page there are CustomRegistration and Registration.
Why?
Thanks.
Update
The CustomRegistrationService:
[DefaultRequest(typeof(CustomRegistration))]
public class CustomRegistrationService : RegistrationService
{
public object Post(CustomRegistration request)
{
//base.Post( request);
return new CustomRegistrationResponse();
}
}
The CustomRegistration (Request dto):
[DataContract]
public class CustomRegistration : IReturn<CustomRegistrationResponse>
{
[DataMember]
public string Name{ get; set; }
}
The CustomRegistrationResponse (Response dto):
[DataContract]
public class CustomRegistrationResponse
{
[DataMember]
public string Test { get; set; }
}
The CustomRegistration service should appear although as we can't see the implementation of it, I can't tell if the service has been written correctly or not.
But there's no reason why Registration would appear in the /metadata pages since you haven't registered the RegistrationFeature.

Repository that accesses multiple tables

This model is simplified, only used for demonstration.
In my application got:
Data
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Repository
public interface IRepository<T>
where T : class
{
T Add(T entity);
T Remove(T entity);
IQueryable<T> GetAll();
int Save();
}
public class ProductRepository : IRepository<Product>
{
public Product Add(Product entity) { ... }
public Product Remove(Product entity) { ... }
public IQueryable<Product> GetAll() { ... }
public int Save() { ... }
}
public class CategoryRepository : IRepository<Category>
{
public Category Add(Category entity) { ... }
public Category Remove(Category entity) { ... }
public IQueryable<Category> GetAll() { ... }
public int Save() { ... }
}
Services
public interface ICategoryService
{
Category Add(Guid gidProduct, Category category);
}
public class CategoryService : ICategoryService
{
public Category Add(Guid gidProduct, Category category){ ... } //Problem here
readonly IRepository<Category> _repository;
public CategoryService(IRepository<Category> repository) //Problem here
{
_repository = repository;
}
}
As I have a repository for each class when I need information from another repository in my service, what should I do?
In the example above, in my service layer I have a method to Add a product (where I found the code for it) and a category.
The problem is that I do a search in the repository of products to recover it, but in my service class category, there is no repository of products., how to solve this problem?
First you need to create a repository for each aggregate root not for each class.
and if you need to access more than one repository in your service, simply you depend on all of them then you can add them as parameters to the constructor for dependency injection.
public CategoryService(CategoryRepository categoryRepository, ProductRepository productRepository)
{
_categoryRepository = categoryRepository;
_productRepository = productRepository;
}

Resources