.NET Desktop Application (Service) 3-tier application - c#

I have just started to design a .NET library that is going to be used by either an application or a service (but this should not matter with 3-tier architecture?) and I'm struggling to find a proper separation of concerns and at the same time link DAL with BL in a proper way.
I was looking for tutorials, etc., but they all point to ASP.NET and Entity Framework, but I'd like to use ADO.NET (DataSets, DataTables) to build a library for desktop application / windows service usage.
Would anyone point me to a right direction by providing any sample/example implenentation or a tutorial/guide??
#EDIT
I was thinking about something like that:
DbManager - abstract class
XDbManager - X being a provider, SQL, etc. deriving from DBManager, being a singleton class (I'd prefer static, but these can't implement interface or derive from classes)
DbConnection - an object returned by DbManager method, containing methods for querying
BaseDbo - abstract class for Database Object
XDbo - X being the name of DBO, using DbManager => DbConnection to query (save, retrieve, retrieve sets, save sets? this is where I'm a bit confused, I need few persistent DataSets to save, update, retrieve data from tables - should they be implemented as Database Objects deriving from DataSets?)
BaseBo - abstract class for Business Object
XBo - business object class to handle and process data, etc.
Saying above I can't find a proper way to "link" both layers.
I also need to make use of SOAP web service in here, should that be implemented on business layer? Or should I introduce a new sub-layer?

If your application is properly designed, using EF or ADO.Net shouldn't matter much: that's the point of the DAL abstraction. I.e. you'll still have a method such as:
public IEnumerable<User> GetAllUsers()
{
....
}
that will returns all of your users. How it's implemented (i.e. Entity Framework or ADO.Net) is not important. The only difference is that your DAL won't be able to return IQueryable<T> (i.e. deferred execution won't work, or you'll need another abstraction layer on top of ADO.Net).
Same as for ASP.Net vs Desktop application: this shouldn't vary much either. You should use WCF services instead of ASP.Net MVC controllers. Instead of directly calling the BL from your controller, you would call a method of a WCF generated client proxy.
Everything that you could read about 3-tier application should apply for your use case too.

Related

Switchable XML and SQL backend

I have an architectural question, we need to develop information system with two frontends: lightweight web-app (ASP.NET) and desktop (WIN-FORMS) app. Nothing special so far, but these two frontends should be able to communicate with two shared and switchable (after app restart) database backends, one SQL database (SQL server) and one, most probably, some kind of XML store (everything in one file would suffice). These two stores won't be synchronized.
Both applications will be very simple, only few forms.
Please, is there any out-of-the-box stuff, e.g. in Entity framework, which can be tuned as described above?
Or what architectural design would you recommend?
Hmm.
Your best bet is to have a class library project for your data repository.
Give it a known interface and use a factory pattern to decide at runtime whether it generates a SQL instance or a XML instance.
Best have the repository based on a singleton pattern.
Thus you'd have something like Repository base inheriting IRepository, with XMLRespository and SQLRepository inheriting from Repository.
Your business logic then just refers to IRepsository or Repository and doesn't care about what is actually there (XMLRepository or SQLRepository).
This is similar to the Repository pattern.
If you want to use the same business logic with different front ends and your sticking to ASP.NET Webforms and Winforms then I'd do the same with the business logic i.e. place it into a class library and call from ASP or Winform code as necessary.

MVC 3 Repository Pattern via SOAP

appreciate any help with this.
We are currently working on remodelling a legacy project that is now heading towards being too much of a nightmare to maintain. So, we've decided to properly normalise the data structure and use Entity Framework 4 Code First development in an MVC 3 project using a repository pattern. The issue we face at the moment is that the legacy application is hosted on a server outside of our main infrastructure for security reasons - therefore all CRUD operations are done via web services, there is no direct connection string to the MS SQL database.
My "proposed" solution is to define my repository contracts, during development there will be a direct connection to the database but once deployed there won't be (there may be scope to getting that changed later). So, would it be reasonable for me to provide two concrete versions of the repository working to the same contract. One that uses LINQ to perform CRUD operations (development and possible the infrastructure we can move to later) and another version that uses SOAP to pass objects (that would mean my POCOs would need to be defined as Serializable) and perform the CRUD operations this way?
Does this sound feasible or is there a much better way of achieving this?
Thanks!
If you are responsible for developing both client and service part you can use some simple approach:
Use some shared interface for repository and service client
When working with remote repository in client inject service client - the service will use repository implementation directly
When working with local repository in client inject repository directly
By using this approach you will have single repository implementation for both scenarios and your upper level logic will not change. There will be only additional web service layer for remote repository. Your repository will have to encapsulate all data access logic and queries = no linq queries outside of the repository which is not the issue in your architecture because linq queries are not serializable without your own custom development or without using WCF Data Services (but it would have other impacts on your architecture).
Btw. it is not very common to place repository behind the web service. More common is to place whole service layre / business logic behind the web service.

Entity Data Framework and Web app architecture

I Am creating a web application and first use Entity Framework. I created Entity Data Model and now I am not sure, how to proceed now.
Premise: My database is really simple (Rating, WebPage, Visitor) and database tables corresponds to the business objects.
My suggestion is 3tier architecture but how to make it?
It is good idea create partial classes with the same name as Entity Framework objects (Rating, Visitor) and declare here new methods (GetAverageRating()...)? Or is better create some VisitorProvider, RatingProvider and place logic here?
It is better use EF objects in BLL and Presentation Layer or I should create my own BO objects on my BLL layer and transform EF object to BO?
I'm think, it is more practical use static methods on my DAL than instantiate classes on BLL. Do you agree?
Can you recommend me some best practices? I have many ideas how to create it, but I do not know what is the right.
3 layer architecture is quite popular but what it really means?
Presentation layer
Application layer
Database layer
If you ask what each layer means you can be pretty sure you will get several different answers. You can further divide each layer into sublayer and build layered hell like:
Client side presentation layer
Server side view layer
Controller layer
Service facade layer
Service layer
Domain objects layer
Repository + Factory layer
ORM layer
Stored procedure layer
Database view layer
Database table layer
WTF? That is just example that application can be easily over architected. It can go even worse if you insist that only neighbours can exchange data and if you decide to add special type of objects to be exchanged between layers instead of flowing sing set of objects through multiple layers.
Add layers which you need to make you more comfortable with developing the application and which will do reasonable separation of concerns and maintainability needed for the scale of your application. You can simply do the most simplest application which will be used just few weeks and must be developed as fast as possible. In such case you can do that within few days simply by using ASP.NET web forms and data source controls (or ASP.NET dynamic data). It can be badly extensible but in such situation it is exactly what you need to implement application quickly. Writing layers and doing all the stuff around maintainability and extensibility is reasonable if you need it. Another quick prototyping technique is ASP.NET MVC Scaffolding which can create quick multilayered skeleton of the application which can be further modified.
Both approaches are correct and it only depends on the approach you like. The first is called active record pattern but it is not used very often with entity framework. The second approach is more popular. You can either use EF directly in some middle class which you called Provider (common name is also Service). This class will do both data access logic and business logic. In more complex applications developers like to somehow wrap EF to separate class following repository pattern and call the repository either from service or directly from web app. code behind or controller (depending on amount of business logic). Try to do it without repository first. My personal opinion is that people should start to use repository only once they understand EF itself.
Again both approaches are correct. In a simple application it is fully acceptable to create EF model with POCO classes (EFv4.x) and use them in all layers. If you are using ASP.NET MVC you can find that you need special classes as view models to fully represent needs of your individual views. In a more complex application you can have separate objects exposed from a business layer - this is especially used if the business layer is exposed as a remote service (WCF).
It depends how you write these DAL methods - it is absolutely necessary to not share the EF context among requests! It also depends if you want to write some test or not. Layer defined by static methods is something which goes directly against testable architecture where you want unit test just single layer (unit testing with EF can be hard). It also depends if you want to use dependency injection which is based on instances.

Services and Repositories in DDD (C#)

How do Services and Repositories relate to each other in DDD? I mean, I've been reading up on DDD for the past 2 days and everywhere I go, there's always a Service layer and there's always a Repository layer. How do these differentiate or compliment each other?
From what I've read, isn't the Repository the layer responsible for delegating interactions between the application and the data?
So, what's the need for the Service layer if it has to implement the Repository to interact with the data anyway even though the Repository probably already implements the methods needed to do so?
I'd appreciate some enlightenment on the subject.
P.S. Don't know if this will help any, but I'm working with an ASP.NET MVC 2 application in which I'm trying to implement the Repository pattern. I just finished implementing the Dependency Injection pattern (for the first time ever)...
UPDATE
Okay, with so many answers, I think I understand what the difference is. So, to review (correct me if I'm wrong):
A Repository layer interacts only with a single object out of the database or the ORM, IEmployeeRepository -> Employee.
A Service layer encapsulates more complex functionality on objects returned from Repositories, either one or multiple.
So, then I have a sub question. Is it considered bad practice to create abstract objects to be sent to my views? For example an AEmployee (A for abstract because to me I means interface) which contains properties from Employee and X or X?
Actually, one more subquestion. If a Service layer can be considered "tuned" for an application does it need to be implemented with an interface?
The Service will use a Repository to retrieve an Entity and then call methods on it (the Entity) to perform the Command/task.
True, a repository works with data (ie. SQL, Webservice etc.) but that's the only job. CRUD operations, nothing more. There is no place for stored procedure based busines logic.
The service (or business logic layer) provides the functionality. How to fullfill a business request (ie. calculate salary), what you have to do.
Oh, and this is a really nice DDD book:
http://www.infoq.com/minibooks/domain-driven-design-quickly
As a concrete example a Shopping Cart application might have the following services:
ShoppingCartService - manages a cart of items with add/remove/update support etc.
OrderService - take a cart, converts it to an order and handles the payment process etc.
each of these services needs to talk a "data source" for CRUD operations. This is where the Repository pattern comes in handy as it abstracts the loading and saving of data to and from the data source be it a database, web service or even in-memory cache.
When you want to create a quick prototype of your application without having to deal with database setup, schema, stored procedures, permissions, etc. you can create a cache or fake repository in a matter of minutes.
For the example above your prototype might start off with the following:
FakeCustomerRepository
FakeAddressRepository
FakeCartRepository
FakeCartLineItemRepository
FakeOrderRepository
FakeOrderLineItemRepository
once your prototype is ready to evolve to the next level you can implement these against a real database:
SQLCustomerRepository
SQLAddressRepository
SQLCartRepository
SQLCartLineItemRepository
SQLOrderRepository
SQLOrderLineItemRepository
From what I can remember, the repository is the final class before the data. The service class can act on data retrieved from the repository. The repository is really just meant to get data to somebody else to do the work. The service layer can provide things such as business logic that all data must pass through. It could also provide for a translation between the application logic and the data layer. But again, this is just what I can remember.
There's no golden standard that defines a service or a repository. In my applications a repository is (as you say) an interface into a database. A service has full access to a repository - but the service exposes a subset of functionality to its consumers.
Think of the repository as more low level. The repository has to expose many ways of accessing the underlying database. A service might combine calls to a repository with other code that only makes sense at a code level (i.e. not in the database), such as access to other state in the application, or validation/business logic that can't easily be applied in a database.

Data Access Layer

how we can create a generic data access layer that can be used by any asp.net application using different datasource provider or webservices?
Can we create data access layer for application that consumes webservice?
You might look into the Repository Pattern. Repository is a facade that presents persisted objects as though they are in a collection in memory. Whichever provider you choose to get data is hidden behind the Repository interface.
IRepository with LINQ to SQL
Code Project Tutorial
A sample by Fredrik Kalseth
You have plenty of options! :-)
You mention you want to use the data access layer (DAL) from asp.net and web services. No problem.
Basically, what you need to figure out is a basic design you want to follow, and encapsulate the DAL into its own assembly which can be used / referenced from various consumers.
There are numerous ways of doing this:
create a Linq-to-SQL mapping for your tables, if you're using SQL Server as your backend, and use the Linq-to-SQL entities and methods
create a repository pattern (for each "entity", you have an "EntityRepository" class, which can be used to retrieve entities, e.g. EntityReposity.GetByID(int id), or EntityRepository.GetByForeignKey(string fk) or whatever
use some other means of accessing the data (NHibernate, your own ADO.NET based mapper)
you could actually also use webservice calls as your data providers
Your biggest challenge is to define a standard way of doing things, and sticking to it.
See some articles - maybe they'll give you an idea:
Creating a Data Access Layer in .NET - Part 1
Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0
Try the tutorials at www.asp.net:
DataAccess
Woah, there are a ton of resources out there. Best advice to start is to find a pattern that you feel comfortable with and stick to it for the project, there is nothing worse then changing your mind 3/4 the way in.
One that I have found and like to use is the Repository or Provider patter. The Repository pattern just makes sure you have standard access to repositories, like your store catalog or CMS system. You create an interface that in my case expose sets of IQueryable the object or the data model are just standard c# classes with now extra fluff POCO (Plain Old CLR Objects).
public interface ICMSRepository {
IQueryable<ContentSection> GetContentSections();
void SaveContentSection(ContentSection obj);
}
Then just implement the interface for your different providers, like a LINQ to SQL context, making sure to return the POCO objects as queryable. The nice thing about this is that you can then make extension methods off of the IQueryable to get what you need easily. Like:
public static IQueryable<ContentSection> WithID(this IQueryable<ContentSection> qry, int ID) {
return from c in qry select c;
}
//Allow you to chain repository and filter to delay SQL execution
ICMSRepository _rep = new SqlCMSRepository();
var sec = _rep.GetContentSections().WithID(1).SingleDefault();
The nice thing about using the Interface approach is the ability to test and mock it up or dependency inject your preferred storage at run time.
Another method I have used and is used in the ASP.Net framework a lot is the Provider model. This is similar except instead of an Interface you create a singleton abstract class, your implementations on top of the abstract class will then define the storage access means (XML, Flat file, SQL, MySql, etc). The base abstract class will be also be resonsible for creating it's singleton based on configuration. Take a look at this for more info on the provider model.
Otherwise you can look at this similar question.
IRepository of T is general good approach. This Interface should expose GetAll, GetByID, Insert, Delete and Submit methods.
But it's important to keep your business logic out of Repository class, and put it to custom logic/service class.
Also, if you return IQueriable in your GetAll method, what you can often see in various implementation of IRepository, UI layer can also query against that IQueriable interface. But querying of object graph should remain in Repository layer. There's a lot debate around this issue.
Look at using the Interfaces:
IDbConnection
IDbCommand
IDbDataAdapter
IdataReader

Categories

Resources