Possible patterns and good practices for an sales-administrative app? - c#

In my asp.net mvc 2 application I have the following specifications:
I have to make a POS system that extensively use JQuery (so I'm not interested in patterns in this part) and generate sales and sales reports classified in periods of time so in my model.
Also I need to generate orders to products providers.
I have entities such as sales, products, sales reports, purchase orders and products providers.
I will use Entity Framework, linq2Sql, automapper and viewmodels to pass information to aspx pages.
My problem with patterns is that I understand the examples over the internet but I hardly can imagine applying to my model.
Do you think in any common pattern which can be applied to this scenario? Maybe some "similar" example using any pattern?
On the other hand, is it a good practice to write the linq2sql sentences within the models classes?
For example, is it right to do the following to get the list of sales within Models/Sales.cs ?
public List<Sales> GetSales(DateTime Date1, DateTime Date2){
var sales = from item in data.Sales
where ((item.Date> Date1) && (item.Date< Date2)) &
select item;
//Rest of code
.......
}
Thanks in advance!

My problem with patterns is that I understand the examples over the internet but I hardly can imagine applying to my model
Trying to fit low-level design patterns to a high-level concept like you have described simply won't work. In order to even start writing low-level software, you have to have these high-level concerns ironed out:
your entire domain model (not code)
your required business scenarios
your IT topology to support your app
which pieces of software you need to write
how each piece of software interacts with other pieces
Once that is well established, you can start working on things like your high-level architecture for your individual application, the corresponding classes that will be required to implement your business requirements and interactions, and the collaborations those classes will have with each other.
Low-level design patterns really apply to this final piece - collaborations between individual classes, or families of classes.
Of course, you can always try the bottom-up approach and start writing code before your design is solidified. But you're only going to be able to apply patterns once you already know which classes you'll be using, and how they need to interact.
In other words, I'd have to look at your code to tell you which low-level design patterns you should be using.
The details of your description show that you are already using higher-level patterns:
Asp.net mvc 2
Entity Framework
linq2Sql
automapper
viewmodels
Each of these components has a host of patterns naturally built into them. ORM, iterators and MVC are all design patterns, for example.
is it a good practice to write the linq2sql sentences within the models classes
If you only take your examples from common practice, then you probably would avoid it. People seem to like plain-old-objects in multi-tiered applications for some reason.
However, some experts consider this extremely common practice of having code-less domain (model) objects to be an Anti-Pattern: See http://en.wikipedia.org/wiki/Anemic_Domain_Model and http://www.martinfowler.com/bliki/AnemicDomainModel.html

Related

MVVM approach, what's a good way? How to improve/speed up development?

this post is meant to have a list of suggestions on MVVM approach... What tools do you use, what do you do to speed up development, how do you maintain your application, any special ways of finding defects in this design pattern......
here is what I do:
So first i create my model/db with EF.
Then I create Views (either user controls or windows) with their respective viewmodel. I usually place the viewmodel in the same location as my view. But while starting the name of my view with "UC-name", I call my viewmodel just "name-model".
In my viewmodel I implement InotifyPropertyChanged
in my xaml view I have a resource of my viewmodel, and bind my grids/controls via the itemsource to the staticresource.
I try to do a lot of front end logic with triggers and styles and also place some code in the xaml.cs file if it regards logic for behaviour of my controls.
I can reach my viewmodel from my view (xaml + xaml.cs).
for communiation between viewmodels I use MVVM lights.
that's pretty much it.
Things I'm thinking about
I'm thinking of using T4 templates for generating viewmodel/view. What do you guys think of this. is this worth it?
when using MVVM light Messenger, we get a subscription based communication, and sometimes I find it hard to track what has changed in my DataContext. Any suggestions on this?
any other improvements or suggestions are more than welcome !
Answering first question regarding View/ViewModel generation I think for CRUD cases it makes sense to use some tools, otherwise it won't be that beneficial.
Pretty nice basic scaffolding implementation example you can find here: WPF CRUD Generator. Also WPF solution by DevExpress looks really promising.
There are at least couple Codeplex projects addressing View/ViewModel generation:
WPF Scaffolder
ViewModel Tool by Clarius
But I am quite pessimistic about T4 for such scenarios. I think writing and polishing own T4's will take you much more time than adoption of existing tools.
Regarding MVVMLight messenger I can say that it will take you some time to get used to it. And as soon as you will understand difference between "regular" and message driven MVVM you'll be able to use it in most efficient way. Very nice article about messenger is Messenger and View Services in MVVM. And want to add a really important quote from there:
A Word of Caution About Messenger
Messenger is a powerful component that can greatly facilitate the task
of communication, but it also makes the code more difficult to debug
because it is not always clear at first sight which objects are
receiving a message. Use with care!
I'm very much a proponent of Domain-Driven Development (DDD). First I have the designer write specifications, roughly adhering to the methodologies in Behavior-Driven Development (BDD). This then forms the basis of unit tests for Test-Driven Development (TDD), for which I use NUnit. For the domain layer itself I start with an Anemic Domain Model i.e. entity classes containing mostly properties and virtually no methods; there are plenty of arguments both for and against this but personally I find it works well. Coupled with this is the Business Logic Layer (BLL) which knows only about the domain entities.
For the Data Access Layer (DAL) I prefer NHibernate, it supports all the usual things you would expect like lazy loading and repository management etc but particularly important is the Object Relational Mapping (ORM) i.e. the bit that translates between your domain entities and the underlying database representation.
One of the problems with NHibernate, in my opinion, is that it uses XML files to do the mapping for the ORM. This means two things: first is that any errors you introduce won't get picked up until run-time. Secondly it's not really a proper "solution" to ORM at all, instead of writing mapping classes you just wind up writing XML files. Both of these problems can be solved by using Fluent. Fluent solves the first problem by replacing XML files with C# files, so your mapping declarations are now done in code which will usually pick up errors at compile-time. It solves the second problem by providing an auto-mapper, which looks at your entities and generates the necessary mapping files automatically. This can be manually overridden if and where needed, although in practice I find I seldom need to. Since the auto-mapper uses reflection is does tend to be a bit slow but it can be run in an offline utility and then saved to a configuration file that is loaded at run-time for near-instant start-up; the same utility can also be used to create your database automatically. I've used this tech with MySql, MS Server and MS Server CE...they've all worked fine.
On the other side of the tier is your view model. I've seen a lot of projects create an almost 1:1 mapping of domain entities to view model classes, I may infuriate MVVM purists by saying this but I really don't see the point in doing all that extra work for something that isn't really needed. NHibernate allows you to provide proxies for the classes it creates, using Castle Dynamic Proxy you can set an intercepter to your NHibernate session factory that automatically injects INotifyPropertyChanged notification to all of your entity properties so that they work with the WPF binding mechanism. Another product, uNhAddIns, allows you to replace any lists with an ObservableCollection in order to get INotifyCollectionChanged support (for reasons I won't go into you can't just put an ObservableCollection into your entities without it seriously affecting performance).
If you're designing and building your application properly using technologies like these and fully unit-testing along the way then you're going to need some way of handling Inversion of Control (IoC) so that you aren't passing object references around all over the place, and for that you'll need a dependency injection framework. My personal preference is Ninject but Unity is pretty good too. Dependency injection is particularly important for good database session management (so that all relevant objects reference the same session), a good rule is one session per WPF form or one per web request.
There are lots of other little things I use to make life easier (MVVM Lite, log4net, Moq for mocking objects for unit testing etc) but this is my core architecture. It takes a while to set up but once you've got it all going you can build fully functional database applications in literally minutes without any of the headaches traditionally associated with layer management in tiered enterprise applications...you just create your domain entities and then start coding for them. Your schema is created automatically, your database is created automatically, you can use your entity classes to fill your database for immediate stress testing and you have full WPF support without having to pollute your entity classes with code or attributes not actually related to the domain. And since all development is driven by anemic domain entities your data is already in the perfect format for serialization into html/ajax/soap etc when you want to give your app web capablities.
You'll notice that I haven't discussed the presentation/XAML layer, mainly because that part is now straightforward. Using a decent architecture you can actually create a fully working and tested application that then only needs pure XAML added to turn it into a releasable product.

IRepository Pattern

For some reason, you always get people in life who know something but don't like to explain them - so I have come here in hope to gain some light into what the IRepository Pattern is.
I have about 1 years programming experience and would like for someone to clearly explain to newbies like me how the above pattern works.
I have had mixed messages from several sources and I am now starting to get *%&^$ confused. However, what I have noticed is that often when mentioning the IRepository pattern, other familiar terms are also mentioned such as Domain, Domain Objects, Domain Model, Application Services, Domain Services, Web Services..
Could anybody give an explanation (not massivley in depth but enough to get a good enough picture of what each component means)...please share your experience!
The repository pattern is normally discussed as part of domain driven design (DDD).
The following is over-simplified to get to the point.
DDD is an architecture for constructing applications. In it the developer will define models that mimic the business requirements. For instance, if you're building an e-commerce application you'd have a product model and a cart model (among other things).
In this architecture the repositories are responsible for persisting and retrieving models. After a visitor to our site adds a product to his/her cart we'd construct the cart object var cart = new Cart(sessionId, productId, yada...) then call repository.Save(cart).
To answer your question:
The IRepository and more likely IRepository<T> interfaces are used to simplify your repositories. They typically contain methods like Get(int id) and Save(object o) that aren't going to change whether you're saving a product or a cart (remember, all the information is in the model). In this type of application you'd use one repository to handle all your persistance and only create specialized repositories (e.g. CartRepository) for very specific uses.
Another part of DDD is that the application doesn't care where the models are persisted, just that they are persisted. By creating an interface the application can be configured to persist objects to whatever/wherever without having to change code. In our example application we could have SQLServerRepository, OracleRepository, XmlRepository, and MongoRepository. As long as they implement the IRepository interface our shopping cart will be able to persist (save) objects to a variety of databases or to an XML file.
Take a look here, for the best explanations about Repositories, Domain, etc...
http://en.wikipedia.org/wiki/Domain-driven_design
http://domaindrivendesign.org
http://www.infoq.com/minibooks/domain-driven-design-quickly
Key to understanding mentioned terms is Domain Driven Design. There is a good book Domain Driven Design by Eric Evans. Domain Driven Design is not a standard, not a technology or methodology. It's set of practices in software development. If you will keep these practices you will have some benefits. Benefits will be not in decreasing time for development, not in using some tools, but in maintainability of your code, in testability and so on.
Model is representation of some things from real world. Your goal is to keep the model clean, to do not allow to influence of programming technologies, of data storage restrictions. In this context is important to use Repository pattern.
Let me give a short example of how I use the IReporisotry pattern. Don't take this explanation as "the way of using it", this is just an example.
I have a Silverlight app wich uses EntityFramework on the server side to access the database. I don't know if you are familiar with EntityFramework but among other features it gives you a context where your entities are so you have ask the context for entitites or tell the context to save entities to the database.
That context has many Repositories to handle those entitites. So my app has a SQLReporsitory (implementing my IRepository) that 'knows' how to save entities to the database. So why the heck I implemented the IRepository? Because I also need to test the saving and retrieving of my entities and I can't afford to depend of the data in the database. So I created a "Memory Database" wich holds simple List<T> of entities and knows how to add, retrieve and remove entities from those lists.
So, when I'm running the app, the SqlRepository gets created, and when I'm running the tests the Fake Repository gets created. And the core of my business is not changed at all. I just 'ask' for an entity or whatever and depending on the context where I'm running I get the data from the database or from my in memory database.
Hope it helps
Edit: here's a good example, with code! http://azurecoding.net/blogs/brownie/archive/2010/09/22/irepository-lt-t-gt-and-iunitofwork.aspx
In short, IRepository is an anti-pattern -> http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/
In C#/.net land there is a great drive to overcomplicate / overdesign programs, even the simplest of CRUD-application has to be DDD and have a domain model and offcourse (wrongly) have a generic repository. Cargo Cult Programming at its finest
You can find a good resource for reviews of overdesigned architectures # http://ayende.com/blog/tags/reviews

Best way to deal with conflated business and presentation code?

Considering a hypothetical situation where an old, legacy presentation library has been maintained over the years, and has gradually had more and more business logic coded into it through a process of hasty corrections and lack of proper architectural oversight. Alternatively, consider a business class or namespace that is not separated from presentation by assembly boundaries, and was thus capable of referencing something like System.Windows.Forms without being forced to add a reference (a much more sobering action than a simple using clause).
In situations like this, it's not unimaginable that the business code used by this UI code will eventually be called upon for reuse. What is a good way to refactor the two layers apart to allow for this?
I'm loosely familiar with design patterns--at least in principle anyway. However, I don't have a whole ton of practical experience so I'm somewhat unsure of my intuitions. I've started along the path of using the Strategy pattern for this. The idea is to identify the places where the business logic calls up to UI components to ask the user a question and gather data, and then to encapsulate those into a set of interfaces. Each method on that interface will contain the UI-oriented code from the original workflow, and the UI class will then implement that interface.
The new code that wants to reuse the business logic in question will also implement this interface, but substitute either new windows or possibly pre-fab or parameterized answers to the questions originally answered by the UI components. This way, the biz logic can be treated as a real library, albeit with a somewhat awkward interface parameter passed to some of its methods.
Is this a decent approach? How better should I go about this? I will defer to your collective internet wisdom.
Thanks!
I humbly suggest Model–View–Controller - MVC has a high probability as a successful solution to your problem. It separates various logic, much as you describe.
HTH
You seem to be taking a good approach, in which you break dependencies between concrete elements in your design to instead depend on abstractions (interfaces). When you break dependencies like this, you should immediately start using unit tests to cover your legacy code base and to evolve the design with improved assurance.
I've found the book Working Effectively with Legacy Code to be invaluable in these situations. Also, don't jump right into the patterns without first looking at the principles of object oriented design, like the SOLID principles. They often guide your choice of patterns and decisions about the evolution of the system.
I would approach it by clearly identifying the entities and the actions they can do or can be done to them. Then one by one try to start creating independent business logic objects for those refactoring the logic out of the UI, making the UI call to the BL objects.
At that point if I understand your scenario correctly you would have a hand full of BL objects, some portion of which made win forms calls, the win forms calls would need to be promoted out into the UI layer.
Then as JustBoo says, I think you'll have a distinct enough situation to start abstracting out controllers from your BL and UI and make it all function in an MVC design.
Okay, given your various comments, I would take Mr. Hoffa's advice and extend it. I'm sure you've heard hard problems should be broken down into ever smaller units of work until they can be "conquered."
Using that technique, coupled with the methodologies of Refactoring could solve your problems. There is a book and lots of information on the web about it. You now have a link. That page has a ton of links to information.
One more link from the author of the book.
So, you refactor, slowly but surely to the creamy goodness of MVC, step-by-step.
HTH

Best practice to apply domain driven design in .NET?

I have been trying to learn and apply domain driven concept into my software development. The first thing that I try to do is creating my domain model based on business logic needs. I often also use OR Mapping tool, such as LLBLGen, NHibernate, or Linq to SQL, to create data model and data access layer. The domain model and data model, however, are often very similar which make me wonder what benefit I really get by maintaining two models.
Can someone share their practical thoughts about domain driven design? Furthermore, how would you deal with data model or data access layer when applying DDD in your application?
Thanks in advance.
EDIT
Found a good article, with sample code, about Repository Pattern.
I abstract my data access via the Repository pattern, so keep my domain objects completely POCO and data provider agnostic.
This allows me to sculpt my application from a domain perspective, concentrating on the logic, primarily via Unit Tests.
Once this has settled I put in the Presentation layer (usually web pages) and then commit to the concrete database schema. I then implement my concrete Repository classes, which can be L2S.
I've drafted a couple of articles here - http://www.duncangunn.me.uk/dasblog/2009/04/11/TheRepositoryPattern.aspx
http://www.duncangunn.me.uk/dasblog/2009/06/27/MockingLinqToSQLRepositories.aspx
Keep an eye out over the next couple of weeks as I will be documenting and providing sample code of my implementation which uses Unit of Work pattern also.
We map domain objects directly to the database, means that we do not have separate layer for data access, and rather we treat this as infrastructure code.
We use Fluent NHibernate for most of the configuration.
Splitting bounded contexts is also a big DDD benefit, you resolve each problem in its context, even if you must duplicate data between contexts.
Good aggregate roots definition gives a simpler design and leads to potential performance improvement (scalability through grid computing, see Gojko Adzic post).
When your design becomes really Domain Driven, your applications is more supple to new business needs, because implementation becomes really an implementation detail.

Can I use the NerdDinner sample project as a base template for a larger project?

I'm new to the MVC framework and have just run through the NerdDinner sample project. I'm loving this approach over form-based asp.net.
I'd like to spin of a more sizable side project using this same approach. Do you see anything in that project that would prevent me from enlarging the basic structure to a more complex website?
Examples of things that make me wary:
1) The NerdDinner sample accesses a db of only two tables, my db has around 30.
2) The NerdDinner project uses the LinqToSQL classes directly... all the way from the model, through the controller, to the view... is that kosher for a larger project?
Do you see any other parts of the NerdDinner framework that might cause me future grief?
I agree with others that the model should be the only place you use linq2sql and my little addendum to that is only use linq2sql in models in small projects. For larger sites it might be worth the overhead to create a separate Web Service project that does all the talking to the database and utilize the web service in your Model.
I never fully checked out the Nerd Diner example but other best practices include Typed Views and using a datamodeler that allows for easy validation (see xval or the DataAnnotations model binder). To me these are 2 of the most important best practices/
Stephen Walter has alot of excellent tips on his website that are worth checking out and taking into account when setting up a new MVC project.
I would add a service layer between the repositories and controllers. The service layer will contain all of your business logic leaving your controllers to deal mainly with processing form inputs and page flow.
Within the repositories I map LinqToSql classes and fields to domain models and then use the domain models within the service layer, controllers and views. For a larger system the extra layers will prove their worth in the long run.
There's alot of debate around the internet when it comes to the Linq to Sql classes. Some feel that it's not enough abstraction when you use the classes directly, and some feel that that's what they're there for. At work we starting revamping our site, and we're using MVC. The way we decided to go was basically each one of the LINQ to SQL classes implements an interface. IE:
public partial class LinqToSqlClass //generated class
{
public int Id{get;set;}
}
interface ILinqToSqlClass
{
int Id{get;set;}
}
public partial class LinqToSqlClass : ILinqToSqlClass
{
}
This is just a very small part of it. We then have a repository that gets you any of these generated class, but only as that of their interface type. This way, we're never actually working directly with the Linq to Sql classes. There are many many different ways to do this, but generally I would say yes, if you're dealing with a large database (especially if the schema may change) or if you're dealing with data that may come from more than one source, definitely don't use the classes directly.
Bottom line is, there's alot of good info in that Nerd Dinner chapter, but when creating your own project, you'll obviously run into issues of your own so take it as you go.
The Nerd Dinner text makes the claim that the MVC framework can equally well accommodate other common data abstractions. (It's true.) It sounds like your organization already has one it likes. A good learning strategy would probably be to adapt one to the other.

Categories