Im a little confused. I saw some code in one of the projects where we use Linq To SQL
<MetadataType(GetType(Customer.CustomerMeta))> Partial Public Class Customer
Friend Class CustomerMeta
<Required(), StringLength(50)> Public Name As String
<Required(), StringLength(50)> Public Address As String
<Required(), StringLength(20)> Public EmailAddress As String
<StringLength(20)> Public Country As String
End Class
And wasnt sure why it was created like this but it looked like a different method had been used from what im used to.
After reading around it seemed like the technique maybe Scaffolding (http://msdn.microsoft.com/en-us/library/cc488469(v=vs.90).aspx) but half way through this walkthrough i realised that many areas dont exist (like the global.asax file) or apply to the project i saw the above code in therefore i could be on the wrong track here.
Does anyone know what technique/framework is being used above and if there are articles i could refer to, to get up to speed? If books or training course is required here then again im happy for someone to point me towards the right direction.
Thanks
These are data validation annotations (I don't know the exact 'framework' using them in your case, as they're exposed in the .NET framework and anyone programming against it can use them): basically, you can decorate members with these attributes (ValidationAttributes) and this metadata can then be used to do some validation, either manual or automated by some data schema rule checker.
In this case, the property Name is:-
a required field (i.e. it must have something in it, and not be empty),
and must be 50 characters in length
And so on and so forth.
The latter constraint might make the former redundant, depending on what's analysing the rules.
Related
I have a question regarding read models. I use read models when i get data from database and eqivalent entity/aggregate models to use in repositories. My question is can read model class have constructor which would check properties? For instance could I have such read model class. From the other hand i already have such checks in eqivalent domain model EmployeeModel therefore i am not convinced as it would be a bit of duplication. The additional question would be if in my EmployeeModel (domain) has not nullable EmploymentDate can i mark it nullablein read model means can read model be a diffrent that eqivalent domain model?
class EmployeeReadModel
{
public DateTime? EmploymentDate { get; set; }
}
can i add constructor and check for such read model?
class EmployeeReadModel
{
public DateTime? EmploymentDate { get; set; }
EmployeeReadModel(DateTime? employeeDate)
{
EmploymentDate = employeeDate?? throw new Exception();
}
}
A read model is something that I see as going over-the-wire. As such it should be easily serializable and methods usually present a problem. Also, if there isn't a default constructor then you also have issues.
Since a read model represents existing data there isn't too much sense in validating it. I would rather leave the validation to the domain model.
Given that a read model is more of a data transfer object chances are that once it leaves your system the receiving system is going to use it plainly as data. For instance, even a web front-end would parse a json representation of the data to consume it.
If you really would like methods on your read model classes then perhaps consider extension methods as these don't interfere with any serialization.
Can domain-driven-design read model have basic logic?
You won't normally have domain logic, in the sense of "state machines" in the read model.
However, you do have constraints that you may need to satisfy, that are inconsistent with the data that you have available.
For example, suppose I'm sent a query with ID:12345, and I'm supposed to respond with a message using the Foo schema, which includes a Bar member that is restricted to the integer values 0-9. We look in the book of record using ID:12345, and discover that the domain model has decided "this one goes to eleven".
So the data that is available doesn't match the required pre-conditions. Now what?
One thing to notice in this sort of setting is that you've got conflicting requirements; if you manage to get all the way to production without discovering that conflict, then you've failed at a number of quality inspection points in your pipeline.
In other words, you're supposed to not have this problem by having discovered it and fixed it a long time ago.
One of the nice things about crash on conflict is that it pulls the Andon cord hard -- everything screeches to a halt. Bonus - that's really easy to detect. The downside, of course, is that you lose revenue until you get a fix deployed.
The downside is that a lot of things can get caught in the blast radius of the crash. And in particular if your monitoring and repairing tools can't run because you are crashing on conflict, it's going to be a real pain to fix.
In other words, we want to be very precise - it's not the responsibility of the read model to detect whether the write model or the human operators are behaving correctly; it's only the job of the read model to determine if read model can satisfy its own requirements with the data that has been provided.
For a new project, I was recently asked to investigate a method of attaching information related to UI rendering to business objects in a WPF application. For example a report class:
class ExecutionReport
{
[Displayable(Bold, Background=Color.Red)]
public String OrderId{get; private set;}
[Displayable(Normal, HAlignment=Center)]
public String Symbol {get; private set;}
// this should be hidden as it doesn't have DisplayableAttribute
public String ClientOrderId {get; private set;}]
[Displayable(Normal, HAlignment=Right,
Format("If [Position] < 0 then Background=Color.Red"),
Format("If [Position] > 0 then Background=Color.Lime"),
DisplayFormat("+#;-#;0")]
public Int Position {get; private set;}
}
This is a very new approach for me as typically in most wpf MVVM applications I have worked on there has been a clear separation of the view and viewmodel and I strive as much as possible to keep UI specific details out of the VM. Instead I would lean towards writing this using resource dictionaries and simple converters applied on the bindings in the view layer.
My questions are: Are there any wpf/mvvm frameworks out there that use this kind of an implementation? If so I'm curious to see how it would be achieved.
Are there any obvious pitfalls? The first couple things that come to my mind are
Change notification (ie. INotifyPropertyChanged to trigger an update of the view). Would the implementation of this be a lot harder now?
Difficulty in being able to leverage resource dictionaries for system wide values. For example, maybe I wanted to change the color of red being used throughout the application. I would have to ctrl + f through and find every place in business objects where it was used and change it instead of being able to modify a single StaticResource
Inability to leverage DesignTime DataContexts
Performance. Seems likes this would require heavy use of reflection which might not be as performant as typical value converters
I'm very interested to see if I'm correct on the second and third points or if both of these things could still be acheived?
Ultimately I feel that this is a bad design and I'm leaning towards writing a different implementation to show the interested party how I would typically approach this kind of problem. Just want to make sure I'm not missing something obvious that might actually make this more elegant.
IMO this seems like a horrible idea, they all seems like examples that should be implemented as XAML converters.
All of the points list seem to be valid reasons to avoid doing this.
Note: There are a set of attributes in the framework which provide some UI functionality already (very limited), see the System.ComponentModel.DataAnnotations namespace.
This approach is very popular and it's called aspect oriented programming (ASP.NET MVC leverages it a lot). The most popular library to write this fast is PostSharp (see customers case studies, there are some companies which have used it for WPF). The best thing in PostSharp is that uses compile-time weaving.
For the first point:
PostSharp got well tested NotifyPropertyChanged aspect, you can add [NotifyPropertyChanged] attribute to class and all properties will call PropertyChanged when value gets changed.
For the second point: you can always make your attribute to look for StaticResources and pass resource key in attribute.
For the third (although I'm not 100% sure about it) and fourth point: compile time weaving means that aspect is "appended" to code on compilation - like you would have written it inside method/property to which you have appended attribute. It's like post-build compiler and doesn't use reflection (if aspect you wrote doesn't use reflection) so performance is really good.
However in example you gave I'd rather go with value converters and styles like #AwkwardCoder said - but aspects(attributes) are also useful with "view" for example: they're great for validiation.
I agree that this seems like a horrible idea, and your comment ...
in most wpf MVVM applications I have worked on there has been a clear
separation of the view and viewmodel and I strive as much as possible
to keep UI specific details out of the VM. Instead I would lean
towards writing this using resource dictionaries and simple converters
applied on the bindings in the view layer
... I think sums up why and how to avoid it.
Tying your business objects directly to implementation details such as colour, horizontal alignment, or position, seems like a short-term win (but long term hell).
I am kinda not getting my head around this and was wondering if someone could please help me understand this.
So here is the problem, I have a class in which there are no required parameters. If user does not set the fields I can take the default value and carry on. Previously, I designed the same class as Joshua Bloch's Builder Pattern (Effective Java) (immutable object). I didn't had any good reason for making the class immutable except for the fact that I didn't wanted to have telescopic constructors and I didn't wanted to expose the data of the class.
But now, a fellow programmer friend is trying to convince me that it's okay to expose the data from the class using C# properties. I am not sure about this and I still feel that I should not be allowing user to muck with data.
Maybe I am completely wrong in my understanding. Could someone please clear my doubt about this, that whether it's good or bad to expose the data from the class?
If it is good then in what case it is good? Or else if someone can please point me to the article/book that clarifies this I would really appreciate it.
Thanks!
Expose the data in the class if it is needed or of interest outside the class, and do not do so if it is not. Expose it read-only if it's only needed to be read outside, and expose it as a full read/write property if it should be able to be changed. Otherwise, keep it in a private field.
immutable classes are easier to reason about especially in a multi tasking application, but they usually pay in performance (because when you need to change the value of a field you need to build the whole class again with the new value).
So, you could be ok or (depending on what you're coding) even better off with properties but as usual there's no silver bullet.
Settable properties are also the only way to code objects for some specific frameworks or libraries (e.g. ORMs like NHibernate), because you can't control how the library/framework initializes the object.
About constructors, C# 4 has optional parameters, that could help you avoid a long chain of constructors and also communicate much more clearly the fact that the parameters are optional.
However I can't think of many cases where you would end up with classes with a long list of optional parameters. If you find that you're coding classes like that too often (especially with the builder pattern, which is very elegant looking on the consumers' side of the class but complicates the code for the class itself) you may be using the wrong design. Are you sure you are not asking your classes to have too many responsibilities?
It basically depend on what's the purpose of your Class in the application context (could you give us more details?).
Anyway reckon that you could make a property safe from external changes by declaring is setter as private:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public string UserName { get; private set; }
It's "good" when the consumer of the class needs the data. You have two possibilities to offer properties.
if you only want to offer a property for information purpose, then choose a read only property like this:
public string MyInformation { get; private set; }
If you have the need to allow the consumer to change that property, then make the setter public like that:
public string MyChangeableInformation { get; set; }
But if the consumer has no need to get the information, then hide it in your class!
But now, a fellow programmer friend is trying to convince me that it's
okay to expose the data from the class using C# properties. I am not
sure about this and I still feel that I should not be allowing user to
muck with data.
As a rule of thumb, methods should represent actions whereas properties represent data. What your friend might have tried telling you is that you can expose the data of your class to outside world and still maintain full control on how other classes are accessing the data. In your case, as other have mentioned, you can use properties with private setters, such that the caller should not be able to modify the data.
I have been searching for an answer to this question for days and it is driving me insane. Currently I am working on a project using ASP.NET MVC 3 and am trying to utilize a ViewModel per controller approach as has been suggested by so many articles and tutorials I have checked out. To better illistrate what I am asking I will outline below:
Lets say I have a pretty simple and straight forward model. Users, Customers, Addresses, Phone Numbers, Orders, Products, Categories, etc... When a user registers for a new account on my site I would like to:
1) create an account for them (this is just an account id, customer type)
2) Add their customer demographic data to Customers
3) Add N-addresses and address types
4) Add N-phone numbers with type as well.
As far as I have got is deciding that I need a RegisterCustomerForRegistrationControllerViewModel. My predicament is what does this model look like? I am trying to be as DRY as possible yet when implementing this pattern I seem to repeat myself at each turn. At what level do I put DataAnnotations for validation? So do I simply new up a new Customer() even if I only want to use one property from the class in a given ViewModel?
I'm not even confident at this point that this is a correct assumption. There seems to be so much opinion on the topic yet so few concrete examples of implementation. I am hoping someone can point me in the right direction and maybe present some code snippets along the way... I hope this is all clear enough and if not please feel free to ask follow up questions.
Again, Thanks in advance!
Repeating simple properties across two distinct layers of an application is not a violation of DRY. Its just good design.
DataAnnotations go on ViewModels.
ViewModel will look something like
public class RegisterCustomerViewModel
{
[Required]
public string Name { get; set; }
public List<AddressViewModels> Addresses { get; set; }
public List<PhoneNumberViewModel> PhoneNumbers { get; set; |
}
Just like jfar, I would take a simple approache: one view, one view model with DataAnnotations.
That being said... I know how you feel (not confident) and I understand because I've been through that myself. My conclusions: unless you consider your web application to require the overhead of so many layers, principles and patterns, keep it simple. I believe that there is no perfect architecture. There's just what works and there's overhead. Sometime, what works is indeed complexe. Ask yourself if you need that complexity.
Take my first sentence as an answer to your question and the rest as my humble opinion.
If my domain object should contain string properties in 2 languages, should I create 2 separate properties or create a new type BiLingualString?
For example in plant classification application, the plant domain object can contain Plant.LatName and Plant.EngName.
The number of bi-lingual properties for the whole domain is not big, about 6-8, I need only to support two languages, information should be presented to UI in both languages at the same time. (so this is not locallization). The requirements will not change during development.
It may look like an easy question, but this decision will have impact on validation, persistance, object cloning and many other things.
Negative sides I can think of using new dualString type:
Validation: If i'm going to use DataAnattations, Enterprise Library validation block, Flued validation this will require more work, object graph validation is harder than simple property validation.
Persistance: iether NH or EF will require more work with complex properties.
OOP: more complex object initialization, I will have to initialize this new Type in constructor before I can use it.
Architecture: converting objects for passing them between layers is harder, auto mapping tools will require more hand work.
While reading your question I was thinking about why not localization all the time but when I read information should be presented to UI in both languages at the same time. I think it makes sense to use properties.
In this case I would go for a class with one string for each languages as you have mentioned BiLingualString
public class Names
{
public string EngName {get;set;}
public string LatName {get;set;}
}
Then I would use this class in my main Plant Class like this
public class Plant: Names
{
}
If you 100% sure that it will always be only Latin and English I would just stick with simplest solution - 2 string properties. It also more flexible in UI then having BiLingualString. And you won't have to deal with Complex types when persisting.
To help decide, I suggest considering how consistent this behavior will be at all layers. If you expose these as two separate properties on the business object, I would also expect to see it stored as two separate columns in a database record, for example, rather than two translations for the same property stored in a separate table. It does seem odd to store translations this way, but your justifications sound reasonable, and 6 properties is not un-managable. But be sure that you don't intend to add more languages in the future.
If you expect this system to by somewhat dynamic in that you may need to add another language at some point, it would seem to make more sense to me to implement this differently so that you don't have to alter the schema when a new language needs to be supported.
I guess the thing to balance is this: consider the likelihood of having to adjust the languages or properties to accommodate a new language against the advantage (simplicity) you gain by exposing these directly as separate properties rather than having to load translations as a separate level.