BsonSerializationException when passing concrete Parameter in constructor to fill more general Property with .net driver - mongodb

I have a Identity class that is extended by two classes StringIdentity and GuidIdentity. I want to use them in Objects as Property and save them in a MongoDb. For Example a class would look like this:
public class MyEvent : IDomainEvent
{
public MyEvent(GuidIdentity entityId)
{
EntityId = entityId;
}
public Identity EntityId { get; }
}
IDomainEvent forces me to implement the Identity Property, so I can (and do not want to) change the property type to GuidIdentity.
When I deserialize my class I get an exception like this:
Creator map for class Microwave.Eventstores.UnitTests. MyEvent has 1
arguments, but none are configured.
Which seems logical according to the .net driver doku, as my property does not match the type of the parameter and therefore can not be serialized. I had the solution to use the Identity as constructor parameter or make the constructor private and instantiate the class with a static Create method that takes the GuidIdentity as parameter. I also messed around with the BsonClassMap, but I really do not want to write all this kind of duplicate code for every class that implements IDomainEvent
So is there a way to tell the .net Driver to use the concrete class from the constructor instead of the more general PropertyType for all Types? Some kind of silver bullet solution? ;)
I am very new to mongodb so I am not aware of all the tricks that come with it, maybe someone can help me out here.

Related

Is it possible to have a one-to-many relation in EF7 between two generic classes?

I have a class called GatewayClaims and a class called GatewayItems. And yes, the project I'm working on is a gateway.
I have several classes derived from GatewayItems: GatewayUser, GatewayCompany, GatewayRole and a few more. Each of these derived classes will hold claims. (Actually, just values. Simplified here.) And these claims gets passed forward to another service as a JWT token. This should work just fine.
But the problem is this:
public class GatewayClaim
{
public GatewayItem Item { get; set; } = new();
}
public abstract class GatewayItem
{
public List<GatewayClaim> Claims { get; set; } = new();
}
The "abstract" is part of the challenge here...
The problem is that I want separate tables for each item/claim pair so I have UserItems/UserClaims, CompanyItems/CompanyClaims, etc. So, preferably I would make the Claims type a generic class GatewayClaim<T> where T:GatewayItem, new() but then List<GatewayClaim> becomes invalid. And I don't weant to create a lot of derived classes just to support the various configurations that would be possible. I could use List<GatewayClaimValue<GatewayItem>> in GatewayItem which seems to work. But then I need to configure the DBSet and IEntityTypeConfiguration class for the various Claims tables and things become really messy by then.
So, I'm looking for an elegant solution to keep the amount of code to a minimum. And keep it readable!
To be clear: GatewayItem is NOT directly mapped to an entity, but a public class GatewayItemConfiguration<T> : IEntityTypeConfiguration<T> where T : GatewayItem is used to allow inheritance of basic configuration for any derived classes. This has an public virtual void Configure(EntityTypeBuilder<T> builder) method that gets overridden in the child configuration classes. Again, I'm trying to stay DRY in my code.
So the GatewayUser class uses a public class GatewayUserConfiguration : GatewayItemConfiguration<GatewayUser> {} class to configure the GatewayUser entity. I do the same way for a GatewayUserClaim which is derived from GatewayClaim at this moment. But the derived Claim types don't differ from their parent class, except the Items list is of a different type. Which is why I want to use GatewayClient<T> instead of GatewayClient.
I have several classes derived from GatewayItems: GatewayUser, GatewayCompany, GatewayRole
These are not closely-enough related to use inheritance in the database. If you want to have a common base class in code, simply don't map GatewayItem to an EF entity.
I want separate tables for each item/claim pair so I have UserItems/UserClaims
Great. Just introduce a UserClaim type, again perhaps inheriting from an unmapped Claim type, and it will map to a separate UserClaim table.

HTL Access Property Without Getter

I'm writing an AEM component and I have an object being returned that is a type from an SDK. This type has public properties and no getters. For simplicity, it might be defined like this:
class MyItem {
public String prop1;
public String prop2;
}
Now normally, I would need a getter, like so:
class MyItem {
public String prop1;
public String prop2;
public String getProp1() {
return prop1;
}
}
But I do not have this luxury. Right now, I've got a Java implementation that uses another type to resolve this, but I think it's sort of crazy that HTL doesn't allow me to just access prop1 directly (it calls the getter). I've reviewed the documentation and can't see any indication of how this could be done. I'd like to be able to write:
${item.prop1}
And have it access the public property instead of calling getProp1().
Is this possible?
You don't need getters for public fields if those fields were declared by your Java Use-class. There's actually a test in Apache Sling that covers this scenario:
https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/testing-content/src/main/resources/SLING-INF/apps/sightly/scripts/use/repopojo.html
This also applies to Use-classes exported from bundles.
For Sling Models using the adapter pattern [0] I've created https://issues.apache.org/jira/browse/SLING-7075.
[0] - https://sling.apache.org/documentation/bundles/models.html#specifying-an-alternate-adapter-class-since-110
From the official documentation
Once the use-class has initialized, the HTL file is run. During this stage HTL will typically pull in the state of various member variables of the use-class and render them for presentation.
To provide access to these values from within the HTL file you must define custom getter methods in the use-class according to the following naming convention:
A method of the form getXyz will expose within the HTL file an object property called xyz.
For example, in the following example, the methods getTitle and getDescription result in the object properties title and description becoming accessible within the context of the HTL file:
The HTL parser does enumerate all the public properties just like any java enumeration of public fuields which include getters and public memebers.
Although it is questionable on whether you should have public variable but thats not part of this discussion. In essence ot should work as pointed by others.

basic info about C# classes and inheriting from other classes

I'd like to write a class which extends the functionality of the MembershipProvider and MembershipUser. But my knowledge in this area is woefully lacking.
My cs file looks something like this:
namespace Mech
{
public class Mechs : MembershipProvider
{
private static Database dbConn = DatabaseFactory.CreateDatabase("main");
public override MembershipUser GetUser(string username, bool userIsOnline)
{
}
}
}
At this point it's complaining about all the abstract members not being implemented. I don't really need to change every single member of membershipProvider, just a handful. So what would be the correct way of doing this?
Take a look at this article at codeguru. You only need to implement what you're going to use, and you can leave the rest throwing NotImplementedExceptions. Additionally, you can extend an existing provider (e.g. SqlMembershipProvider) and override ValidateUser or anything else your heart desires.
As you are inheriting from an abstract class you need to implement all the non-abstract methods and proporties.
You don't necessarily have to change everythingthing . You can just leave them as it after implementation.
You can use VS smart features to save you from lots of typing and the parent class has lots and lots of abstract members and methods.
Click on MembershipProvide , Wait for Intellisences to show you the hint as in below picture:
(Alternatively press Alt+Shift+F10)
Now that's it , you will have your class implementing all the abstract methods and proporties.
So what will happen when you will try to access Field1:
StackOverflow stackOverFlow = new StackOverflow();
String myString = stackOverFlow.Field1;

EF Codefirst, One class, multiple tables with discriminator

I doing a little investigation and I am wondering if the following is possible.
I am looking to create a BaseEntityWithDetails class that I can reuse for any type that I would like to have extendable. For example
public abstract class EntityDetail
{
}
This class is used to persist a key and value for the entity.
"Products" would be extended by doing the following...
public class ProductDetail : EntityDetail
{
}
public class Product : BaseEntityWithDetails<ProductDetail>
{
}
The base class "BaseEntityWithDetails" will provide some helper methods for setting and getting. What do you think?
What is the most effective way of mapping this with EF CodeFirst while being super easy to allow another type implement an DetailsEntityTypeConfiguration like the following
public class ProductMap : DetailsEntityTypeConfiguration<Product, ProductDetail>
{
}
Thanks in advance!
I would like to quote someone really smart on this: Reuse is a fallacy. Don't bother doing stuff like this because it will only make your design more obfuscated and complex. Save your inheritance to the entities in your domain which really share the same behavior, don't do this type of assumptions up front.
As a side note: You can map this as a table per type if you put your "EntityDetail" into your database, but as I said before, this is just not a good idea.

what is a stateless class?

I would like to know what are drawbacks of a stateless class (if any)?
Has anyone seen a real-world application where some use case mandated the creation of a stateless class (No hello world please )?
I think a stateless class means a class without any fields.
Here's a real world example:
Writing plugins for Microsoft Dynamics CRM.
In that doc you'll see a note that says: "The plug-in's Execute method should be written to be stateless".
And basically what it means to be a stateless class is that there should be no global variables (except for a few special cases, which I won't get into unless asked).
The reason why this is mandated by CRM upon plugin developers is because CRM tries to improve performance by caching and re-using instances of plugin classes.
The way CRM executes its plugins is something roughly like this:
Main thread:
YourCustomPlugin yourCustomPluginCached = new YourCustomPlugin();
then later:
Thread1:
yourCustomPluginCached.Execute(context1);
and Thread2:
yourCustomPluginCached.Execute(context2);
What some developers do wrong is they will create a global variable to store the Context, which they set as the first line in the Execute() method. That way they don't have to pass it between all their methods. But this is actually a huge mistake.
Because if they do that, and in the scenario above, if the execution in thread2 begins before the execution from thread1 finishes. That would mean that context1 in thread1 would be overwritten with context2. And now that plugin will have some unexpected result. In 99% of cases, even when developed incorrectly this way, there are no problems, or no noticeable problems. But in 1% of cases, it will cause something to go wrong, and that something will be incredibly difficult for the dev to figure out what went wrong, and will probably never occur when they are testing/debugging. So it will probably go unfixed for a long time.
I never heard "stateless class", but I think you mean immutable objects (very useful notion!).
Or maybe a class which doesn't have any fields, so usually it looks like just bunch of pure functions.
If by stateless class you mean a class of immutable objects, then the drawback is that mutating operations need to copy an object instead of changing it in-place. That might be expensive.
I use these things quite often, pretty much whenever an object's behavior is determined by some input that can be processed all at once. A recent example is a statistical language model that I implemented: the model parameters were determined entirely in the constructor based on training input, and then the model could be queried for probability estimates on unseen text, but not modified. Immutability wasn't strictly mandated, but modifying the object didn't make sense, since there was no need to add data later on (in which case much of the computation had to be redone anyway).
I too am not sure what you mean by that term, but I assume it to mean a class with no fields, as the state of an object is actually the content of its fields.
Now, usually you'd use this kind of class as a collection of related functions - say, a certain Utils class. The common way to use this kind of class is by making its method static, so you don't actually have to create an instance of the class.
The only reason I can think of to actually create such a stateless object is if you'd like the actual functionality to be determined at run-time. So, if you have a UtilsBase class which offers a bunch of virtual methods and a UtilsDerived which overrides some of the methods, you can pass whoever needs to use the utils a reference to UtilsBase, and create the actual utils object at run-time, according to the specific needs.
A bit late, but here is my share.
I am sure the poster meant a stateless object. Please, people don't make it so dramatic.
Let's get to business. Some commenters asked about static. When static is used in a class, which should be used sparingly, all those members holding the static keyword now belong to the class and not anymore to the object. They are part of the class.
For example:
Declaring a Person class with a static property called Name does not make sense
public class Person
{
public **static** string Name { get; set; }
}
by the way another word for static is "Shared" which is used in VB.NET.
If we once set the name on the Person, then that name is shared everywhere because it does not belong to the object, but to the class itself. In real world you would not call all people "Jhon", or all your customers "Customer1". Each one will have a different name, surname, phone, address, etc. The moment we set these properties, this object becomes stateful, instead of stateless. It has a name, an address, etc. The properties of an object defined in a class make it stateful.
Here Name property belongs to the class, not part of the object:
Person.Name="Fili" //You would not call every person Fili in your application.
Let's redeclare the Person class by removing the static keyword:
public class Person
{
public string Name { get; set; }
}
In the example below, the object is stateful. It has a state, it has been given a name, "Jhon", which can be changed later. A person can change his name to Jimmy, for example. Once that is done, then the state of that object has changed from Jhon to Jimmy.
//From
Person person1 = new Person {
Name = "Jhon";
}
//to
person1.Name = "Jimmy"
The object 'person1' still is the same object, but its state has changed. It is not the same anymore. It has a different name.
So, person1 had a state until a cetain point in time, but then its state was changed. Now, it is in a different state.
Now, creating a new person is something new which has nothing to do with the person1. Person2 has its own state.
Person person2 = new Person {
Name = "Imir";
}
Using the static class: Person.Name="Fili" it has a state, but it belongs to the class and it is shared everywhere.
So, a stateless object will be one that has nothing to be changed, doesn't hold a value. Will you create a person without a Name? Would you create a customer object which does not exist? No, of course not. The moment you name a person or a customer, they have a state. They exists and can change their state.
Take the example of a Airplane. When you delcare it you add a Status property for example.
public class Airplane {
public string Status {get;set;}
}
var plane1 = new Airplane{ Status="Flying"};
So, the question arises: what is the state (status) of the plane at this moment?
One would reply: it is "flying". If you change the state to "taxing", then its state is "taxing", or it is "stationary", etc.
In stateless class, all field members should be readonly type. Although c# don't have any such features which will check statelessness at compile time like:
public readonly class MyReadonlyClass
{
public readonly double X {get;set;}
public readonly double Y {get;set;}
public readonly double Z {get;set;}
public MyReadonlyClass(double x_,double y_,double z_)
{
X=x_;Y=y_;Z=z_;
}
}
public readonly static class MyStaticReadonlyClass
{
public readonly static double X {get;set;}
public readonly static double Y {get;set;}
public readonly static double Z {get;set;}
static MyStaticReadonlyClass(double x_,double y_,double z_)
{
X=x_;Y=y_;Z=z_;
}
}
Stateless is something which should not preserve its state or in other words we can say that every time we use the any functionality or member of that class then previously used/set variables should not affect the next use of that class/functionality.
Consider the following code snippet (Ignore the standards)-
class Maths {
int radius;
public void setRadius(int r) {
this.radius = r;
}
public float getCircleArea() {
return (float) (3.14 * radius * radius);
}
}
public class Geometry {
public static void main(String[] args) {
Maths m = new Maths();
m.setRadius(14);
System.out.println(m.getCircleArea());
}
}
if some other running thread changes the value of radius in class Maths then getCircleArea() would give us different results because the state of the variable 'radius' can be change as it is a global variable. This problem occurs mainly in web application where we use bean containers. Most of the beans are Singleton and only has one copy. If we use global variables then there is a possibility that value of a global variable will change.
To make a stateless class try to use local variable so that the scope of the variable will be limited.
Example of the above getCircleArea() will be.
public float getCircleArea(int radius) {
return (float) (3.14 * radius * radius);
}