Azure table entity model design - azure

In most examples of table entity models I see something like:
public class CustomerEntity : TableEntity
{
public CustomerEntity(string lastName, string firstName)
{
this.PartitionKey = lastName;
this.RowKey = firstName;
}
public CustomerEntity() { }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
As we see here lastname and firstname used as partition key and row key accordingly. So later after saving and retrieving an entity I can access those info from PartitionKey and RowKey properties. But what if I want to send this model to client side later as json, I suppose PartitionKey and RowKey of TableEntity base class would not be serialized. So if i add LastName and FirstName as properties to model, then unnecessary data duplication will occur in storage. What is the best way avoid data duplication in storage and in the same time have an access to lastname and firstname after model been serialized.

You can always use a getter method on your class to avoid confusion:
public class CustomerEntity : TableEntity
{
public CustomerEntity(string lastName, string firstName)
{
this.PartitionKey = lastName;
this.RowKey = firstName;
}
public CustomerEntity() { }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string FirstName { get { return this.RowKey; } }
public string LastName { get { return this.PartitionKey; } }
}
Or, you could map the data to an anonymous object in your API and return that via JSON:
var customerJson = new
{
Firstname = customer.RowKey,
LastName = customer. PartitionKey,
customer.Email,
customer.PhoneNumber
};
return JsonConvert.SerializeObject(customerJson);

Related

How To Update Properties In Domain Aggregate Root Object

In a clean architecture project the domain layer contains: DTO interfaces, Events, Factories, Models, Exceptions, etc...
Every domain object contains a constructor with arguments through which data is passed.
I am using factories which accept a DTO interface from which domain objects are created.
The data models in the infrastructure layer implement the DTO interfaces in the domain layer.
DTO:
namespace Acme.Core.Domain.Identity.DTO
{
public interface IBuyerDto : IPersonDto
{
IAddressDto BillingAddress { get; set; }
IAddressDto ShippingAddress { get; set; }
}
}
Domain Models:
namespace Acme.Core.Domain.Identity.Models.BuyerAggregate
{
public sealed class Buyer : Aggregate<Buyer, BuyerId>, IPerson
{
public Buyer(BuyerId id, PersonName name, DateOfBirth dateOfBirth, Gender gender, string pictureUrl, Address billingAddress, Address shippingAddress, Account account) : base(id)
{
Name = name;
DateOfBirth = dateOfBirth;
Gender = gender;
BillingAddress = billingAddress;
ShippingAddress = shippingAddress;
Account = Guard.Against.Null(account, nameof(account));
PictureUrl = pictureUrl;
}
public Account Account { get; private set; }
public PersonName Name { get; private set; }
public DateOfBirth DateOfBirth { get; private set; }
public string PictureUrl { get; private set; }
public Gender Gender { get; private set; }
public Address BillingAddress { get; private set; }
public Address ShippingAddress { get; private set; }
public void UpdateName(PersonName personName)
{
Name = personName;
}
public void UpdateBillingAddress(Address billingAddress)
{
BillingAddress = billingAddress;
}
public void UpdateShippingAddress(Address shippingAddress)
{
ShippingAddress = shippingAddress;
}
}
}
namespace Acme.Core.Domain.Identity.Models
{
public class Account : Entity<Account, AccountId>
{
public Account(AccountId id, string userName, string normalizedUserName, string passwordHash, string concurrencyStamp, string securityStamp, string email, string normalizedEmail, bool emailConfirmed, string phoneNumber, bool phoneNumberConfirmed, bool twoFactorEnabled, DateTimeOffset? lockoutEnd, bool lockoutEnabled, int accessFailedCount, AccountStatus status, List<RoleId> roles, List<AccountClaim> accountClaims, List<AccountLogin> accountLogins, List<AccountToken> accountTokens) : base(id)
{
UserName = Guard.Against.NullOrWhiteSpace(userName, nameof(userName));
NormalizedUserName = Guard.Against.NullOrWhiteSpace(normalizedUserName, nameof(normalizedUserName));
PasswordHash = Guard.Against.NullOrWhiteSpace(passwordHash, nameof(passwordHash));
ConcurrencyStamp = concurrencyStamp;
SecurityStamp = securityStamp;
Email = Guard.Against.NullOrWhiteSpace(email, nameof(email));
NormalizedEmail = Guard.Against.NullOrWhiteSpace(normalizedEmail, nameof(normalizedEmail));
EmailConfirmed = emailConfirmed;
PhoneNumber = phoneNumber;
PhoneNumberConfirmed = phoneNumberConfirmed;
TwoFactorEnabled = twoFactorEnabled;
LockoutEnd = lockoutEnd;
LockoutEnabled = lockoutEnabled;
AccessFailedCount = accessFailedCount;
Status = Guard.Against.Null(status, nameof(status));
_roles = Guard.Against.Null(roles, nameof(roles));
_accountClaims = accountClaims;
_accountLogins = accountLogins;
_accountTokens = accountTokens;
}
public string UserName { get; private set; }
public string NormalizedUserName { get; private set; }
public string PasswordHash { get; private set; }
public string ConcurrencyStamp { get; private set; }
public string SecurityStamp { get; private set; }
public string Email { get; private set; }
public string NormalizedEmail { get; private set; }
public bool EmailConfirmed { get; private set; }
public string PhoneNumber { get; private set; }
public bool PhoneNumberConfirmed { get; private set; }
public bool TwoFactorEnabled { get; private set; }
public DateTimeOffset? LockoutEnd { get; private set; }
public bool LockoutEnabled { get; private set; }
public int AccessFailedCount { get; private set; }
public AccountStatus Status { get; private set; }
private List<RoleId> _roles;
public IReadOnlyCollection<RoleId> Roles
{
get
{
return _roles;
}
}
private List<AccountClaim> _accountClaims;
public IReadOnlyCollection<AccountClaim> AccountClaims
{
get
{
return _accountClaims;
}
}
private List<AccountLogin> _accountLogins;
public IReadOnlyCollection<AccountLogin> AccountLogins
{
get
{
return _accountLogins;
}
}
private List<AccountToken> _accountTokens;
public IReadOnlyCollection<AccountToken> AccountTokens
{
get
{
return _accountTokens;
}
}
public void AddRole(long roleId)
{
var role = _roles.Where(x => x.GetValue().Equals(roleId)).FirstOrDefault();
if (role == null)
{
_roles.Add(new RoleId(roleId));
}
}
public void RemoveRole(long roleId)
{
var role = _roles.Where(x => x.GetValue().Equals(roleId)).FirstOrDefault();
if (role == null)
{
_roles.Remove(role);
}
}
public void ActivateAccount()
{
Status = AccountStatus.Active;
}
public void BanAccount()
{
Status = AccountStatus.Banned;
}
public void CloseAccount()
{
Status = AccountStatus.Closed;
}
public void LockAccount()
{
Status = AccountStatus.Locked;
}
public void NewAccount()
{
Status = AccountStatus.New;
}
}
}
Factories:
namespace Acme.Core.Domain.Identity.Factories
{
public class BuyerAggregateFatory : IBuyerAggregateFactory
{
private readonly IPersonNameFactory _personNameFactory;
private readonly IDateOfBirthFactory _dateOfBirthFactory;
private readonly IGenderFactory _genderFactory;
private readonly IAccountFactory _accountFactory;
private readonly IAddressFactory _addressFactory;
public BuyerAggregateFatory(IPersonNameFactory personNameFactory,
IDateOfBirthFactory dateOfBirthFactory,
IGenderFactory genderFactory,
IAccountFactory accountFactory,
IAddressFactory addressFactory)
{
_personNameFactory = Guard.Against.Null(personNameFactory);
_dateOfBirthFactory = Guard.Against.Null(dateOfBirthFactory);
_genderFactory = Guard.Against.Null(genderFactory);
_accountFactory = Guard.Against.Null(accountFactory);
_addressFactory = Guard.Against.Null(addressFactory);
}
public Buyer Create(IBuyerDto dto)
{
BuyerId aggregateId = new BuyerId(dto.Id);
PersonName name = _personNameFactory.Create(dto.Name);
DateOfBirth dob = _dateOfBirthFactory.Create(dto.DateOfBirth);
Gender gender = _genderFactory.Create(dto.GenderId);
Address billingAddress = _addressFactory.Create(dto.BillingAddress);
Address shippingAddress = _addressFactory.Create(dto.ShippingAddress);
Account account = _accountFactory.Create(dto.Account);
return new Buyer(aggregateId, name, dob, gender, dto.PictureUrl, billingAddress, shippingAddress, account);
}
}
}
From the application layer a service class does the orchestration for the use case, using the repository interface and factory interface.
Use case 1: During an update operation I fetch existing data of the aggregate, from the database using a repository. I need to update one or two properties of a domain aggregate root object. Example: I need to update billing address or shipping address.
Use case 2: During an update operation, I fetch existing data of the aggregate, from the database using a repository. I need to update the account status. I am calling the status update method from domain aggregate root object. Example: buyerAggregate.Account.ActivateAccount()
Am i updating the domain aggregate root object and its properties in right way?
In use case 2, your aggregate would be the Account, not the Buyer. There's no need for the Buyer to be involved in the transaction.
So, for this case, you would retrieve Account from the repository and then call ActivateAccount() directly.
Any aggregate that you have designed for a use case should provide the full interface for making changes to the aggregate. In other words, your application layer will only work with properties and methods on the aggregate root. If a child entity needs changing that method should be implemented on your aggregate root. You should not directly interact with child properties of an aggregate. It is the aggregate's responsibility to avoid any invariants within its scope. If you change a child object directly, you may put the whole aggregate in an invalid state because the aggregate was not able to enforce controls.

Create a complex type model validation attribute with server and client validation

I'm trying to create an attribute that can validate a complex type both on the server and client side. This attribute will be used for required and non required complex types such as the following Address Class
public partial class AddressViewModel
{
[DisplayName("Address 1")]
[MaxLength(100)]
public virtual string Address1 { get; set; }
[DisplayName("Address 2")]
[MaxLength(100)]
public virtual string Address2 { get; set; }
[MaxLength(100)]
public virtual string City { get; set; }
[MaxLength(50)]
public virtual string State { get; set; }
[MaxLength(10)]
[DisplayName("Postal Code")]
public virtual string PostalCode { get; set; }
[MaxLength(2)]
public virtual string Country { get; set; }
}
The problem is that this model could be required sometimes and optional other times. I know that I could simply create another RequiredAddressViewModel class that has the Required attribute associated with the properties I deem required. I feel like there could be a reusable solution, such as a ValidationAttribute.
I created the following classes and they work server side, but do not work for client side.
public class AddressIfAttribute : ValidationAttribute, IClientValidatable
{
public string Address1 { get; private set; }
public string Address2 { get; private set; }
public string City { get; private set; }
public string State { get; private set; }
public string PostalCode { get; private set; }
public string Country { get; private set; }
public bool IsRequired { get; private set; }
public AddressIfAttribute(bool isRequired) : base("The field {0} is required.")
{
IsRequired = isRequired;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var address = value as AddressViewModel;
Address1 = address.Address1;
Address2 = address.Address2;
City = address.City;
State = address.State;
Country = address.Country;
PostalCode = address.PostalCode;
var results = new List<ValidationResult>();
var context = new ValidationContext(address, null, null);
Validator.TryValidateObject(address, context, results, true);
if (results.Count == 0 && IsRequired)
{
if (string.IsNullOrEmpty(Address2))
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
else if (results.Count != 0)
{
var compositeResults = new CompositeValidationResult(string.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[]
{
new ModelClientValidationAddressIfRule(string.Format(ErrorMessageString,metadata.GetDisplayName()), Address1, Address2, City, State, Country, PostalCode,IsRequired)
};
}
}
public class ModelClientValidationAddressIfRule : ModelClientValidationRule
{
public ModelClientValidationAddressIfRule(string errorMessage, object address1, object address2, object city, object state, object country, object postalCode, bool isRequired)
{
ErrorMessage = errorMessage;
ValidationType = "addressif";
ValidationParameters.Add("address1", address1);
ValidationParameters.Add("address2", address2);
ValidationParameters.Add("city", city);
ValidationParameters.Add("state", state);
ValidationParameters.Add("country", country);
ValidationParameters.Add("postalCode", postalCode);
ValidationParameters.Add("isrequired", isRequired.ToString().ToLower());
}
Since the AddressIf attribute is on a complex type the necessary markup isn't added and unobtrusive javascript doesn't validate these fields.
So if I want the rendered HTML to have the proper data-* fields, is my only solution to create another RequiredAddressViewModel? At this point, it might be the easiest.

ArangoDb.Net upsert always insert

I'm making a small application with CRUD functions with ArangoDatabase and its driver:
http://www.arangoclient.net/
Here is my code:
var insert = new Account
{
Email = "email01#gmail.com",
FirstName = "Adam",
LastName = "Smith"
};
var update = new Account
{
Email = "email01#gmail.com",
FirstName = "John",
LastName = "Peterson"
};
using (var arangoDatabase = new ArangoDatabase(new DatabaseSharedSetting()
{
Url = "http://127.0.0.1:8529/",
Database = "_system",
Credential = new NetworkCredential()
{
UserName = "root",
Password = "xvxvc"
}
}))
{
arangoDatabase.Query()
.Upsert(_ => new Account() {Email = insert.Email},
_ => insert, ((aql, x) => update))
.In<Account>()
.Execute();
}
For the first time running, [insert] object is added to database.
Therefore, my database now is :
But at the second time of running code, it throws me an error :
unique constraint violated (while executing). ErrorNumber: 1210 HttpStatusCode: 409
The question is: What is my problem and how to solve it?
Thank you,
Problem could be upsert search expression serialization:
Assume Account class definition is:
public class Account
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
upsert search expression: new Account() {Email = insert.Email} will serializes to:
{ Email: "email01#gmail.com", FirstName: null, LastName: null }
but what is expected is:
{ Email: "email01#gmail.com" }
Since search expression will never found a document, then insert will occur and you get unique constraint violated.
There are two solution to avoid serializing FirstName and LastName members:
One is we could use Json.net JsonProperty attribute to ignore nulls in serialization:
public class Account
{
public string Email { get; set; }
[Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FirstName { get; set; }
[Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string LastName { get; set; }
}
And the other way is to use an anonymous object for search expression:
arangoDatabase.Query()
.Upsert(_ => new Account() {Email = insert.Email}
// should be
arangoDatabase.Query()
.Upsert(_ => new {Email = insert.Email}
One note about using anonymous object is that Email member could resolve to something else base on what you specify for its naming convention, for example:
public class Account
{
[DocumentProperty(Identifier = IdentifierType.Key)]
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
If you specify Email as a Key identifier, then you should use _key in the anonymous object:
arangoDatabase.Query()
.Upsert(_ => new { _key = insert.Email }

Azure Table Storage - TableEntity map column with a different name

I am using Azure Table Storage as my data sink for my Semantic Logging Application Block. When I call a log to be written by my custom EventSource, I get columns similar to the ff.:
EventId
Payload_username
Opcode
I can obtain these columns by creating a TableEntity class that matches the column names exactly (except for EventId, for some reason):
public class ReportLogEntity : TableEntity
{
public string EventId { get; set; }
public string Payload_username { get; set; }
public string Opcode { get; set; }
}
However, I would like to store the data in these columns in differently named properties in my TableEntity:
public class ReportLogEntity : TableEntity
{
public string Id { get; set; } // maps to "EventId"
public string Username { get; set; } // maps to "Payload_username"
public string Operation { get; set; } // maps to "Opcode"
}
Is there a mapper/attribute I can make use of to allow myself to have the column name different from the TableEntity property name?
You can override ReadEntity and WriteEntity methods of interface ITableEntity to customize your own property names.
public class ReportLogEntity : TableEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Id { get; set; } // maps to "EventId"
public string Username { get; set; } // maps to "Payload_username"
public string Operation { get; set; } // maps to "Opcode"
public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
this.PartitionKey = properties["PartitionKey"].StringValue;
this.RowKey = properties["RowKey"].StringValue;
this.Id = properties["EventId"].StringValue;
this.Username = properties["Payload_username"].StringValue;
this.Operation = properties["Opcode"].StringValue;
}
public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
var properties = new Dictionary<string, EntityProperty>();
properties.Add("PartitionKey", new EntityProperty(this.PartitionKey));
properties.Add("RowKey", new EntityProperty(this.RowKey));
properties.Add("EventId", new EntityProperty(this.Id));
properties.Add("Payload_username", new EntityProperty(this.Username));
properties.Add("Opcode", new EntityProperty(this.Operation));
return properties;
}
}

How to serialize a custom class with YamlDotNet

I'm trying to serialize a custom class with YamlDotNet library.
Here is my class:
public class Person
{
string firstName;
string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
And here is how I tried to serialize it:
StreamWriter streamWriter = new StreamWriter("Test.txt");
Person person = new Person("toto", "titi");
Serializer serializer = new Serializer();
serializer.Serialize(streamWriter, person);
But in my output file, I only have this : { }
What did I forget to do to serialize my class?
The default behavior of YamlDotNet is to serialize public properties and to ignore fields. The easiest fix is to replace the public fields with automatic properties:
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Person(string first, string last)
{
FirstName = first;
LastName = last;
}
}
You could alter the behavior of YamlDotNet to serialize private fields relatively easily, but I do not recommend that.

Resources