I want to learn Xamarin and i took a look at a sample project called 'Tasky'
But i don't understand why theres a BusinessEntityBase class...
A task also needs it's ID to be PK and incremented so why doesn't it implement
the BusinessEntityBase class instead of the IBusinessEntity interface?
public class Task : IBusinessEntity
{
public Task ()
{
}
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
// new property
public bool Done { get; set; }
}
public abstract class BusinessEntityBase : IBusinessEntity
{
public BusinessEntityBase ()
{
}
/// <summary>
/// Gets or sets the Database ID.
/// </summary>
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
}
public interface IBusinessEntity
{
int ID { get; set; }
}
IBusinessEntity interface is just that - an interface, the properties of which (in this case, ID) would be a part of every business entity. Read up on the use of Interfaces in C# to get a better understanding of why this is done.
Another example would be:
Lets say you have an employee management application which contains three different kinds of users - Manager, Developer, Tester. You have a class for each of these.
It is very likely that all three of them contain an ID field, a first name and a last name.
Instead of adding the same properties to each of their classes, you create an interface called IEmployee, which has three fields - ID, FirstName and LastName and get each of the three classes to implement it.
Functionally, implementing the properties on an interface and adding them manually has the same effect on the class. Although, having an interface connecting all three of them, you now have a more abstract way to access your data (For example, to count the number of employees, you could check the count of IEmployee objects, rather than counting all three separate and then adding the numbers up).
TL;DR Doing it this way is not mandatory. In this scenario you could simply have a BusinessEntity class that has an ID field. It is simply a good practice and makes your applications easy/possible to maintain when they grow.
Related
I recently started to learn about Azure Mobile Services, I followed this tutorial about it and the classes for my model are required to inherit from the EntityData class.
From the EntityData source code, an Id property is already defined to act as a primary key, but it is defined as string which doesn't work for my Model that uses int.
My class looks like this:
public partial class Role : EntityData
{
public Role()
{
this.Users = new HashSet<User>();
}
[Key]
public int RoleId { get; set; }
public string Title { get; set; }
public virtual ICollection<User> Users { get; set; }
}
If I try to use this class, I get an error message saying an Id property is already defined.
Is there a way to define a different property as a primary key? In case this change is not possible, is there a way to use this string Id property as an incremental primary key?
The best solution is to use automapper. Here's a blog post that outlines how to do it, essentially you store an int, but transform it into a string when it is sent over the wire:
http://blogs.msdn.com/b/azuremobile/archive/2014/05/22/tables-with-integer-keys-and-the-net-backend.aspx
We are at a point in our development cycle (asp.net mvc applciation), where we need to introduce changes to our existing commands and events (say adding/removing a few properties etc).
I have been trying to find a way to introduce commands/events versioning in the system. I have read many posts on google/stackoverflow etc but am still to see an example of code that implements it. Is there a recommended pattern one should follow when versioning. If yes any examples/snippets?
Edit: This is how far i have gotten with this
i have versioned my events backwards, such that the latest will always be called the same, while the ones that go obsolete will have a suffix added to it like '_V1', '_V2' etc.
So if i have an event
public class OrderSubmittedEvent : IDomainEvent
{
public int OrderId { get; private set; }
public OrderSubmittedEvent(int orderId)
{
OrderId = orderId;
}
}
and if i have to add a few properties i rename my event above to
public class OrderSubmittedEvent_V1 : IDomainEvent
{
public int OrderId { get; private set; }
public OrderSubmittedEvent_V1(int orderId)
{
OrderId = orderId;
}
}
and introduce another event with the same name as my original event but with added properties, like so
public class OrderSubmittedEvent : IDomainEvent
{
public int OrderId { get; private set; }
public OrderSubmittedEvent(int version = 1, int orderId = 0, string customerName =
"Joe blogs", string address = "Earth")
{
OrderId = orderId;
CustomerName = customerName;
Address = address;
CurrentVersion = version;
}
public static int LatestVersion
{
get { return 2; }
}
public int CurrentVersion { get; set; }
public string CustomerName { get; set; }
public string Address { get; set; }
}
i still have to go ahead and change my code which publishes this event to include values for new properties.
any given point of time when i get all my events from the event store (say, for replaying) they will always be of the same type after deserialization (in this case OrderSubmittedEvent) with new properties which were not part of the old events populated with their default values.
At the time of replaying my events i make my events go through an IEventUpgrader
This first verifies if the events is the latest version available. since the type will always be the event type, this check is based on the properties "LatestVersion" and "CurrentVersion"
what does everyone think of this approach?
next todo
If event is an old version publish an 'UpdateMYEVENT' Event
thanks
usually you only need to version the events, you can ignore the commands since you don't store them in the event store.
There are few ways to implement versioning.. my method is quite simple:
[Obsolete]
public class CompanyCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class CompanyCreated_V2
{
public Guid Id { get; set; }
public string CompanyName { get; set; }
public string TaxNumber { get; set; }
}
You need to handle conversion of events from the old one to the new one as you read the events from the event store.
also, you need to be aware that you never remove any old event classes, hence why I decorate them as Obsolete, to let other developers know not to use the event.
If you are only adding & removing properties, there might be no need to version events; just ignore the serialized properties that are removed, and use sensible defaults for the ones you add.
I would be cautious with mixing events and commands. They have different purposes and solve different problems.
To give a better feeling of what I mean, think of it like so
Commands are more like RESTful API, client-server communication.
While Event Sourcing is more of a way to store the data.
Both need versioning as a way to provide backward compatibility through immutability, but once again for different reasons. Hence implementation and exceptions are different.
I would definitely recommend a book Event Versioning by Greg Young to get more insides into versioning for event sourced systems..
For more information on the commanding, check out the CQRS series and particularly CQRS via HTTP.
Admittedly I have not had the opportunity to try the following but I'd like go bake in the versioning from day one:
Since the full type name is relevant I would go for namespaces.
namespace Primary.Messages.V1
{
public class CompanyCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
namespace Primary.Messages.V2
{
public class CompanyCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
}
}
These could be in different assemblies and you could mark the older ones as obsolete (as suggested by Sarmaad). It may be that older version are not necessarily obsolete though.
Any ideas?
I am totally out of reasons while considering why would one need event-versioning the way it has been asked in question and more specifically the way it has been suggested in the answers?
I can think of only two use cases
1- the event class currently being used is deprecated and no more needed.
Then that class can be tracked down in the git anytime needed. So why bother and complicate the active code by keeping the dead classes?
2- The business requirement is changed and now you need to keep the base event but you also need another similar event with some parameter differences.
That can be solved in a number of ways, like decorator pattern can help to handle such variations to a great extent
Alternately the new event might be representing a unique domain concept and instead of trying to force the concept into existing model, it might be better to name it more semantically and use it that way.
I have two database classes as defined below:
public class TopDate
{
[Key]
public int DateId { get; set; }
public DateTime Date { get; set; }
}
public class TopSong
{
[Key]
public int SongId { get; set; }
public string Title { get; set; }
public int DateId { get; set; }
}
where DateId is foreign key to TopSong
I am creating a controller through which i can create, delete or edit these database values.
When i right click on controller class and add controller i can only select one of the two classes defined above. Is there a way to make 1 controller to handle database updates to both these tables on one page?
Error Image:
Your controller should not be dealing directly with domain objects (meaning those things that are directly associated with your database). Create a ViewModel that contains the properties that you need, use your service layer to populate the ViewModel and your controller will use that as the Model for its base. An example of your ViewModel could be something like the following given your description above:
public class MusicViewModel
{
public int SongId {get;set;}
public string Title {get;set;}
public IEnumerable<DateTime> TopDates {get;set;}
}
This view model would contain a list of all dates that a specific song was a Top Song.
The objects you showing (code) are database classes (so called domain objects).
What you need to do is to define a view model, a standard ASP MVC practice:
you define a class, that is tailored for specific view and only containing data relevant to that particular view. So you will have a view model for a view that will create a song, another that will update it etc.
Actually situation you describing is classical situation to use view models. Using domain objects in the views, however, is really really bad practice and prone to more problems than you want to deal with.
Hope this helps.
I have a data model that requires tracking changes. I could have as many ~100,000 changes/updates to my model per month. My model involves tracking HOW a task is completed and can be broken down into 3 basic types.
I currently have my model like this but have divided the types of sandwiches into 3 separate controllers because each sandwich is made very differently:
public class Sandwich
{
public int Id { get; set; }
public int SandwichTypeId { get; set; } //This is an enum type
//About a dozen other properties that define HOW the sandwich gets made
}
I could break it apart like this and match it more to my controllers:
public class PeanutButterAndJellySandwich
{
public int Id { get; set; }
//No enum sandwich type
//About a dozen other properties that define HOW the sandwich gets made
}
public class HamSandwich
{
public int Id { get; set; }
//No enum sandwich type
//About a dozen other properties that define HOW the sandwich gets made
}
//etc
2 Part Question:
Is there any advantage(s) to breaking up the model?
If so, would those advantages be defeated because I would have to add separate tracking tables as well?
Thanks.
In EF I have done something like subclassing the Sandwich class, and using those in the specific controllers.
On the other hand, I've handled things like this by, for example, creating just one more field:
public class Sandwich
{
public int? CurrentVersion { get; set; }
public int Id { get; set; }
public int SandwichTypeId { get; set; } //This is an enum type
//About a dozen other properties that define HOW the sandwich gets made
}
This way, a single sandwich can have a lot of previous versions, all of which would point to the current one. In my update routine, I created a duplicate (with the old version's CurrentVersion pointing to the original, now updated, version Id).
This of course requires you to change other places where you list Sandwiches to look only for those which are not revisions.
If you need to reference immediately previous or next versions then you could create int? PreviousVersion and/or int? NextVersion to avoid searches in your database.
Greetings all,
I have researched and found a number of discussions on designing a MVC service layer, but I haven't found an answer to my exact questions. The post on service layer interdependency has an image illustrating what I have in mind, but I have a further question that I don't believe is covered in the referenced post.
My application will track data for a non-profit that interacts with humans in multiple contexts. Maybe the human was a client, maybe they were an adviser, or maybe they were an adversary. They can be multiple. A client may later become an adversary (think lawyers' clients).
My idea is that the creation of a new client or a new adversary always creates two records: 1 record in the person table and one record in the ancillary table. My thoughts behind this is that there will be one place (the person table) to check to see if the business has had any past interaction with a given person.
My question is , when representing entities in a 1 to 0..1 relationship to the controller layer, (1) Should the controller be involved in combining and splitting classes before passing them to a view? (2) If not, should the service layer construct the viewmodel?
I've read the post about the 1800 line Controller here.
I've also read this post that says your service layer shouldn't know about the view model, which makes me think it lives and dies in the controller layer. If the service layer doesn't touch the viewmodel, for example, (3) is it good design for the workerService to return both Person and Worker objects to the Controller?
Here are my entity classes:
public class Record
{
public DateTime datecreated { get; set; }
public DateTime dateupdated { get; set; }
public string Createdby { get; set; }
public string Updatedby { get; set; }
}
public class Person : Record
{
public int ID { get; set; }
public virtual Worker Worker { get; set; }
publiv virtual Defendant defendant {get; set;}
...
}
public class Worker : Record
{
public int ID { get; set; }
public virtual Person person { get; set; }
...
}
public class Defendant : Record
{
public int ID { get; set; }
public virtual Person person { get; set; }
...
}
I think you should try and find a balance between whats "good design" and what works for you.
For instance, I have an MVC application that uses ASP.NET Membership, but I also have a custom User table, where I store things like a user's fiendly name, or OpenID. In that same application I have an IAdminService that handles everything concerning user administration.
What IAdminService returns to the controller is an AdminUser class, which looks like:
public class AdminUser
{
public string UserName { get; set; }
public User User { get; set; }
public MembershipUserWrapper MembershipUser { get; set; }
}
MembershipUserWrapper is just a wrapper around the default MembershipUser to allow for testing and more flexibility in general.
Anyway, you could argue that AdminUser is actually a view model and indeed I do have a couple of views strongly typed to AdminUser. It would be complicating matters unnecessarily to not let IAdminService return an AdminUser just because it is in the "service layer", and in this case, you don't want the controller performing the "transformation" from User and MembershipUserWrapper to AdminUser every time.
is it good design for the workerService to return both Person and Worker objects to the Controller?
I think in this case it probably is. You could have two separate services, but most of the logic for fetching a Worker and a Person is probably the same, so you'd be forcing yourself to either repeat a lot of code or create a third service that performs the common tasks.
You should pay attention to proper desing, but take also K.I.S.S. and YAGNI into account. Do what makes sense now, and refactor accordingly whenever needed.