Automapper ignore properties while mapping - automapper

Is there a provision in Automapper to ignore certain properties while mapping. For example, I have two classes Manager and Employee. Manager has a list of employees and other information.
I need employees list in Manager most of the times but in few cases I do not need employees list to be returned to the client (say while just editing manager names). So, when I create map, I included Employees to be mapped too. Now is there a way to specify employees property to be ignored at the time of mapping.
// <--- Employees is included.
Mapper.CreateMap<Manager, ManagerDto>();
// <--- I want to ignore employees list here.
ManagerDto dto = Mapper.Map<Manager, ManagerDto>(manager);

You could possibly use conditions in your mapping configuration. For example:
Mapper.CreateMap<Manager, ManagerDto>()
.ForMember(d => d.Employees,
opt => {
opt.Condition(s => s.NeedEmployees);
opt.MapFrom(s => s.Employees);
});
I don't believe you can do it at the time you're actually applying the mapping.

Related

Create additional orders in Shopware 6 on onOrderTransactionWritten event

I need to create multiple orders after an order is placed in Shopware 6.
I have managed to create the plugin, set up the OrderSubscribe and listen to the event, but i can't figure it out how to easily create multiple orders based on the informations of the placed order.
I can update the order like this:
$this->orderRepository->upsert([[
'id' => $payload['orderId'],
'customFields' => ['order_type' => $this->getOrderType($orderObject->lineItems)]
]], $event->getContext());
i can delete it like this:
$this->deleteOrder($payload['orderId'], $event->getContext());
How i can create other orders taking advantages for example of:
$this->getOrderObject($event, $payload)->getOrderCustomer();
It's better approach to use the create method:
$this->orderRepository->create([], $event->getContext());
or using the Cart somehow?

Shopware6 : How to create rules for custom field in order

My goal is to achieve something like the following with flowbuilder:
Trigger: order placed (achievable with the flowbuilder)
If : if order.customFields.customtextField not empty (trying to implement this)
Action : send email with (achievable with the flowbuilder)
For this, I am trying to add a custom rule for order following this : https://developer.shopware.com/docs/guides/plugins/plugins/framework/rule/add-custom-rules#create-custom-rule
But, I see that the last created order is not easily accessible in the rule class. Is there a better/recommended way to do check for an order custom field after order is placed?
Within the flow the order is converted back to a cart with the order line items becoming cart line items once again. This is done to make existing rules work for both evaluating carts and orders. This also means the custom fields of a placed order are not available in the context of the cart as they wouldn't be available yet during checkout. Unfortunately within a rule condition there is no ideal way to identify if the cart was converted from an existing order, no less which order it is.
What you could do however is add a new flow action. Within the scope of the action you could have access to the order entity and then decide within the action what to do with it. The triggers for order placed or enter/leave states will dispatch CheckoutOrderPlacedEvent or OrderStateMachineStateChangeEvent respectively. Both of these have a getter for the order entity which you will be able to access from within your action.
public function handle(FlowEvent $event): void
{
$baseEvent = $event->getEvent();
if (!$baseEvent instanceof CheckoutOrderPlacedEvent && !$baseEvent instanceof OrderStateMachineStateChangeEvent) {
return;
}
$order = $baseEvent->getOrder();
// evaluate the order and decide what to do with it
}
I see that another approach that worked for me was with adding a custom trigger(event) which is dispatched when checkout.order.placed event is fired and if that event's order has the custom field that I am looking for.

DDD/CQRS: Combining read models for UI requirements

Let's use the classic example of blog context. In our domain we have the following scenarios: Users can write Posts. Posts must be cataloged at least in one Category. Posts can be described using Tags. Users can comment on Posts.
The four entities (Post, Category, Tag, Comment) are implemented as different aggregates because of I have not detected any rule for that an entity data should interfere in another. So, for each aggregate I will have one repository that represent it. Too, each aggregate reference others by his id.
Following CQRS, from this scenario I have deducted typical use cases that result on commands such as WriteNewPostCommand, PublishPostCommand, DeletePostCommand etc... along with their respective queries to get data from repositories. FindPostByIdQuery, FindTagByTagNameQuery, FindPostsByAuthorIdQuery etc...
Depending on which site of the app we are (backend or fronted) we will have queries more or less complex. So, if we are on the front page maybe we need build some widgets to get last comments, latest post of a category, etc... Queries that involve a simple Query object (few search criterias) and a QueryHandler very simple (a single repository as dependency on the handler class)
But in other places this queries can be more complex. In an admin panel we require to show in a table a relation that satisfy a complex search criteria. Might be interesting search posts by: author name (no id), categories names, tags name, publish date... Criterias that belongs to different aggregates and different repositories.
In addition, in our table of post we dont want to show the post along with author ID, or categories ID. We need to show all information (name user, avatar, category name, category icon etc).
My questions are:
At infrastructure layer, when we design repositories, the search methods (findAll, findById, findByCriterias...), should have return the corresponding entity referencing to all associations id's? I mean, If a have a method findPostById(uuid) or findPostByCustomFilter(filter), should return a post instance with a reference to all categories id it has, all tags id, and author id that it has? Or should my repo have some kind of method that populates a given post instance with the associations I want?
If I want to search posts created from 12/12/2014, written by John, and categorised on "News" and "Videos" categories and tags "sci-fi" and "adventure", and get the full details of each aggregate, how should create my Query and QueryHandler?
a) Create a Query with all my parameters (authorName, categoriesNames, TagsNames, if a want retrive User, Category, Tag association full detailed) and then his QueryHandler ensamble the different read models in a only one. Or...
b) Create different Queries (FindCategoryByName, FindTagByName, FindUserByName) and then my web controller calls them for later
call to FindPostQuery but now passing him the authorid, categoryid, tagid returned from the other queries?
The b) solution appear more clean but it seems me more expensive.
On the query side, there are no entities. You are free to populate your read models in any way suits your requirements best. Whatever data you need to display on (a part of) the screen, you put it in the read model. It's not the command side repositories that return these read models but specialized query side data access objects.
You mentioned "complex search criteria" -- I recommend you model it with a corresponding SearchCriteria object. This object would be technnology agnostic, but it would be passed to your Query side data access object that would know how to combine the criteria to build a lower level query for the specific data store it's targeted at.
With simple applications like this, it's easier to not get distracted by aggregates. Do event sourcing, subscribe to the events by one set of tables that is easy to query the way you want.
Another words, it sounds like you're main goal is to be able to query easily for the scenarios you describe. Start with that end goal. Now write your event handler to adjust your tables accordingly.
Start with events and the UI. Then everything else will fit easily. Google "Event Modeling" as it will help you formulate ideas sound what and how you want to build these style of applications.
I can see three problems in your approach and they need to be solved separately:
In CQRS the Queries are completely separate from the Commands. So, don't try to solve your queries with your Commands pipelines repositories. The point of CQRS is precisely to allow you to solve the commands and queries in very different ways, as they have very different requirements.
You mention DDD in the question title, but you don't mention your Bounded Contexts in the question itself. If you follow DDD, you'll most likely have more than one BC. For example, in your question, it could be that CategoryName and AuthorName belong to two different BCs, which are also different from the BC where the blog posts are. If that is the case and each BC properly owns its own data, the data that you want to search by and show in the UI will be stored potentially in different databases, therefore implementing a query in the DB with a join might not even be possible.
Searching and Reading data are two different concerns and can/should be solved differently. When you search, you get some search criteria (including sorting and paging) and the result is basically a list of IDs (authorIds, postIds, commentIds). When you Read data, you get one or more Ids and the result is one or more DTOs with all the required data properties. It is normal that you need to read data from multiple BCs to populate a single page, that's called UI composition.
So if we agree on these 3 points and especially focussing on point 3, I would suggest the following:
Figure out all the searches that you want to do and see if you can decompose them to simple searches by BC. For example, search blog posts by author name is a problem, because the author information could be in a different BC than the blog posts. So, why not implement a SearchAuthorByName in the Authors BC and then a SearchPostsByAuthorId in the Posts BC. You can do this from the Client itself or from the API. Doing it in the client gives the client a lot of flexibility because there are many ways a client can get an authorId (from a MyFavourites list, from a paginated list or from a search by name) and then get the posts by authorId is a separate operation. You can do the same by tags, categories and other things. The Post will have Ids, but not the extra details about those IDs.
Potentially, you might want more complicated searches. As long as the search criteria (including sorting fields) contain fields from a single BC, you can easily create a read model and execute the search there. Note that this is only for the search criteria. If the search result needs data from multiple BCs you can solve it with UI composition. But if the search criteria contain fields from multiple BCs, then you'll need some sort of Search engine capable of indexing data coming from multiple sources. This is especially evident if you want to do full-text search, search by categories, tags, etc. with large quantities of data. You will need to use some specialized service like Elastic Search and it won't belong to any of your existing BCs, it'll be like a supporting service.
From CQRS you will have a separeted Stack for Queries and Commands. Your query stack should represent a diferente module, namespace, dll or package at your project.
a) You will create one QueryModel and this query model will return whatever you need. If you are familiar with Entity Framework or NHibernate, you will create a Façade to hold this queries togheter, DbContext or Session.
b) You can create this separeted queries, but saying again, if you are familiar with any ORM your should return the set that represents the model, return every set as IQueryable and use LET (Linq Expression Trees) to make your Query stack more dynamic.
Using Entity Framework and C# for exemple:
public class QueryModelDatabase : DbContext, IQueryModelDatabase
{
public QueryModelDatabase() : base("dbname")
{
_products = base.Set<Product>();
_orders = base.Set<Order>();
}
private readonly DbSet<Order> _orders = null;
private readonly DbSet<Product> _products = null;
public IQueryable<Order> Orders
{
get { return this._orders.Include("Items").Include("Items.Product"); }
}
public IQueryable<Product> Products
{
get { return _products; }
}
}
Then you should do queries the way you need and return anything:
using (var db = new QueryModelDatabase())
{
var queryable = from o in db.Orders.Include(p => p.Items).Include("Details.Product")
where o.OrderId == orderId
select new OrderFoundViewModel
{
Id = o.OrderId,
State = o.State.ToString(),
Total = o.Total,
OrderDate = o.Date,
Details = o.Items
};
try
{
var o = queryable.First();
return o;
}
catch (InvalidOperationException)
{
return new OrderFoundViewModel();
}
}

Orchard connected parts

I have a complex scenario that I'm trying to model using Orchard CMS parts.
Now here it is the simplified version to make clear my question.
I have a part name, as example, PersonPart that has just one property: Name.
I have another part that contains the person role, name it PersonRolePart and has just one property, Role
In Orchard I have created all the appropriate plumbing (Handlers, Drivers, Views...)
In migrations I created a new content type named Person that contains the two parts.
ContentDefinitionManager.AlterTypeDefinition("Person", cfg => cfg
.WithPart("PersonPart")
.WithPart("PersonRolePart")
.WithPart("CommonPart")
.Creatable(false) );
So far so good, I can create a new person and edit both parts.
Another part that I have is a ServicePart that is bound to one of the PersonRoleParts defined above.
Now the question:
For reporting purpose I need to get all services by PersonRole and get the person details that belong to that role or, in other words, get all the (only one indeed) PersonPart that is used in the Person compound type defined above.
How to do that?
Now in a non-orchard world I would create a simple 1:1 relationship between the 2.
My (failed) attempt so far was to add a PersonRoleRecord_Id field to PersonPartRecord and a PersonRecord_Id to Person role... but I have no idea how to set to correct id on driver or handler since both see just the own part.
Is it possible from driver get an instance of the other fellows parts in content type?
Merge Person and Role is not possible. The scenario is more complex than that and I need same Person Part an 3 different Role-like part for different purposes and I want to avoid duplicate common person data 3 times.
Another idea was to create an appropriate handler but I do not know how to create an Handler for a virtual content type like the one I did.
I have managed to solve using the advice on another question that addressed a different problem (validation).
Orchard CMS - determining if Model is valid in Content Item Driver
So my solution was to add an handler to both and cast the part and set the appropriate reference to the other part.
OnPublishing<PersonPart>((context, part) =>{
var person = part.As<PersonPart>();
var role= part.As<PersonRolePart>();
if (person != null && role != null) {
if (role.Person == null) {
role.Person = person.Record;
}
}
});
In this specific case since it is a 1:1 relation so i I use just that combined part, both id are the same, at least if the role is just of one type.
I will see when I will create more role-like parts.

Is there a plugin to show the pages that link to a certain document?

Does anyone know of a plugin for modx that will show all the pages that link to each document ID or would I have to create my own?
You could write a snippet for yourself. Use the code
$weblinkArray = $modx->getCollection('modWeblink',$criteria);
where $criteria is the set of criteria, restrictions or constraints you want to set, like
$criteria = array(
'published' => 1,// this is optional, more parameters can be optionally added as well
)
This gives you an array of the documents that link. Further, you know how to access data of an array.

Resources