Entities Framework 4 Code First: Business Methods - asp.net

Could anyone tell me where is the best place to put my business methods when using EF4 code first POCOs? Should they go in the POCO class? E.g.
public class customer
public property Id as int32
public property Name as string
public property Archived as boolean
public sub MarkAsArchived
me.Archived = true
end sub
public function EmailAllInvoices as boolean
...
end function
end class
Or should the POCO class be as clean as possible and a seperate class be used for business logic which accepts an instance of a customer POCO in the constructor to work on?
Thanks.

#Ladislav Mrnka is right, it depends on your architecture.
How complex are your business rules? Are they likely to change often? What clients will consume your Model, just your own Web Site, or are you exposing API's, OData, etc?
All questions that need to be answered.
Personally, we have simple business rules, and a fairly straightforward architecture.
Therefore, i do all validation in a service layer, and i create partial classes for my POCO's to faciliate the business rules, and throw Custom Exceptions.
E.g
public void Add(Order order)
{
try
{
order.Validate(); // method in Order.cs partial class
repository.Add(order);
}
catch (InvalidOrderOperationException exc) // custom exc
{
// do something
}
}
As i said - depends on your architecture.
If you have very complicated business rules, consider using the Specification pattern.
The "DDD-God" (Martin Fowler) has a good write-up on it here.

That is definitely dependent on "architecture" of your business layer. You can use POCO as data transfer object and have some upper level business layer class which will handle business operations - basically we can talk about Transaction script pattern. Or you can place methods to your POCO objects and "promote" them to Domain objects. Then your business logic will be inside your domain objects and domain services (some business logic functionality is for several domain objects so it should be placed to separate class). This is called Domain driven design (but it suggests much more architecture related ideas).

Related

Where should Stored Proc business logic be placed in MVC?

I'm looking for a bit of experience and explanation here, given that different sources give different recommendations. I am totally new to MVC. I know this question has been asked before, but I am not (currently) using EF or Linq.
I have a SQL database with many stored procedures. Previously when used with webforms, there was a business layer that contained helper methods for calling the procedures and returning DataSets to the pages. The important part is that the procedures often interrogated about 20 tables; the pages do not simply reflect the database structure exactly (as I see in the majority of MVC tutorials):
SQL database <--> stored procedures <--> business layer <--> web forms
I want to take the best approach here to start on the right footing and learn properly but appreciate there may not be a correct answer. Therefore if you post, could you please offer some explanation as to "why"?
Should stored procedure logic (SQLCommand/business methods etc) go within Model or
Controller?
One post advises neither, but retain the business layer. Another expert advises that
[Models/Entities] should not have any addon methods outside of what's
coming back from the database
If the business layer is retained, where are the methods called from (e.g. Model or Controller)?
If the above answer is "Neither", does that mean the Model part will go unused?
That almost feels that things aren't being done properly, however in this tutorial that appears to be what happens.
Should I plug in the Entity Framework into the Model layer to call the business layer?
That feels like overkill, adding all that additional logic.
Your controllers should gather the information required to build the page the user is currently viewing. That's it.
Controllers should reference classes in your business logic layer.
For example here's your controller. All it does is translate the http request and call the business logic.
public class MyController : Controller
{
private IMyBusinessLogic _businessLogic;
public MyController(IMyBusinessLogic businessLogic)
{
_businessLogic = businessLogic;
}
[HttpPost]
public ActionResult UpdateAllRecords()
{
_businessLogic.UpdateAllRecords();
return Json(new Success());
}
}
And your business logic class
public class MyBusinessLogic : IMyBusinessLogic
{
public void UpdateAllRecords()
{
// call SP here
using(SqlConnection conn = new...
}
}
There are a number of advantages to this:
Your business logic is completely separated from your UI, there's no database code in your presentation layer. This means your controller can focus on it's job and code doesn't get polluted.
You can test your controller and see what happens when your business logic succeeds, throws exceptions etc.
For extra bonus points you should look into creating a data access layer.
public void DataAccess : IDataAccess
{
public void RunStoredProcedure(string spName)
{
}
}
Now you can test that your BLL is calling and processing your SP results correctly!
Expanded following the comment questioning the models:
Ideally your model should have no logic in it at all. It should simply represent the data required to build the page. Your object which you're loading represents the entity in the system, the model represents the data which is displayed on the page. This is often substantially lighter and may contain extra information (such as their address) which aren't present on the main entity but are displayed on the page.
For example
public class Person
{
public int PersonID {get;set;}
public string Firstname {get;set;}
public string Lastname {get;set;}
public Address Address {get;set;}
}
The model only contains the information you want to display:
public class PersonSummaryModel
{
public int PersonID {get;set;}
public string FullName {get;set;}
}
You then pass your model to your view to display it (perhaps in a list of FullNames in this case). Lots of people us a mapper class to convert between these two, some do it in the controller.
For example
public class PersonMapper
{
public PersonSummaryModel Map(Person person)
{
return new PersonSummaryModel
{
PersonID = person.PersonID,
FullName = string.Concat(person.Firstname, " ", person.Lastname)
};
}
}
You can also use some automatic solutions such at AutoMapper to do this step for you.
Your controller should really only be involved with orchestrating view construction. Create a separate class library, called "Data Access Layer" or something less generic, and create a class that handles calling your stored procs, creating objects from the results, etc. There are many opinions on how this should be handled, but perhaps the most
View
|
Controller
|
Business Logic
|
Data Access Layer
|--- SQL (Stored procs)
-Tables
-Views
-etc.
|--- Alternate data sources
-Web services
-Text/XML files
-and son on.
if you feel like learning tiers and best way
MSDN have great article on this link
MSDN

asp.net MVC 4 with Data Access Layer using Entity Framework 5?

In my project, i have first created my Data Access Layer using Entity Framework with the following projects in a single solution,
1.Domain Model - Entity Model (.edmx)
2.Services - Business Services, Dtos, Infrastructure(Configurator), Interfaces and Models(Repository)
Now the problem is, i want to connect this data access layer to my MVC project, i do not know how to make the data access layer projects to behave as the models for my mvc project. So can anyone tell me how to connect my data access layer into my controllers and views.. any references is appreciated. Thanks in Advance !
I think what you're asking is what's the best way for controllers to interact with your services and data layer?
One option is to use the mediator pattern, and decouple the services from the controllers.
There's a great implementation for ASP.NET MVC apps: ShortBus, also available on nuget that I've used in a number of projects, and so far it's worked great.
One of the nice things about ShortBus is it's support for dependency injection. In the example below, all the services are created with Ninject, and require the appropriate registration.
The basic idea is you define queries and commands that the controllers will use, and then add handlers to perform the actual work.
public class AddUser : ICommand<User>
{
public string Email { get; set; }
}
and then a handler:
public class AddUserHandler : ICommandHandler<AddUser, User>
{
private IDatabaseService _database;
private IEmailService _email;
public AddUserHandler(IDatabaseService database, IEmailService email)
{
_database = database;
_email = email;
}
public User Handle(AddUser command)
{
bool created = _database.CreateUser(command.Email);
if (created)
{
_email.SendWelcome(command.Email);
}
}
}
Then inside your controller, all you'd do is issue the command:
public class UsersController : Controller
{
private IMediator _mediator;
public UsersController(IMediator mediator)
{
_mediator = mediator;
}
public ActionResult Create(string email)
{
User user = _mediator.Send(new AddUser("foo#bar.com"));
}
}
The things I like about this pattern are:
Controllers don't need to know how to create a user. It issues a command, and the appropriate business logic handles it.
Each handler can require the services it needs. There's no need to pollute the controllers with services only used by a single action.
It's really easy to unit test. I use a mock, and only need to verify that _mediator.Send() was called with the correct parameters. Then to test the handler, I mock IDatabaseService and IEmailService and verify they are called correctly in the 2 cases.
Commands and queries can be reused, and again, the caller never needs to know what's required to handle the request.
As for the Views, I'd recommend ViewModels.
Each View gets it's own ViewModel, which holds whatever is required for showing that particular page. You'd then map your domain objects to their own individual ViewModels, possibly with AutoMapper.
What's nice about ViewModels is you can format the data appropriately (formatting a DateTime maybe), and then your Views don't need any special logic. If later you decide to update the DateTime format, you only need to change it in one place.
Create a (shared) interface to pass to the layer that's between the DAL and MVC, especially if you're unit testing. Use a repository pattern. Check it out here:
http://csharppulse.blogspot.com/2013/09/learning-mvc-part-5repository-pattern.html
This should get you going...

C#/ASP.NET MVC 4 Instantiate Object Derived From Interface In Factory Method

Currently have a Factory class that features a GetSelector function, which returns a concrete implementation of ISelector. I have several different classes that implement ISelector and based on a setting I would like to receive the appropriate ISelector back.
public interface ISelector
{
string GetValue(string Params);
}
public class XmlSelector : ISelector
{
public string GetValue(string Params)
{
// open XML file and get value
}
}
public static class SelectorFactory
{
public static ISelector GetSelector()
{
return new XmlSelector(); // Needs changing to look at settings
}
}
My question is what is the best way to store the setting? I am aware of using AppSettings etc. but I'm not sure whether I want to have to store strings in the web.config and perform a switch on it - just seems to be really tightly coupled in that if a new implementation of ISelector is made, then the Factory would need to be changed. Is there any way of perhaps storing an assembly name and instantiating based on that?
Thanks,
Chris
It is hard to say, because I don't know the architecture of your particular project, but at a first glance what I would do is if the objects associated with ISelector can be decoupled from your web application, I would put these objects in a class library along with the factory. Your factory will need to be changed if you implement a new ISelector, but if you can decouple the whole ISelector family from your actual web application the depth of the refactoring you will have to do will be minimal compared to a monolithic architecture.
Personally, I tend to avoid AppSettings, web.config settings and the like for mission-critical design questions. Using the web.config as an example, I have seen applications where architectural data is stored for ease of configurability. The problem is that after compilation your web.config can be changed (that is the purpose of it after all) and if the implementation of your classes depends on very specific values being chosen, you are running a risk of a crash when someone inadvertently modifies the wrong value.
Like I said all this depends entirely on your application architecture, but my reflex would be to split out the components that could be subject to future modification into a class library. Loose coupling is your friend ;).
Instead of doing it in AppSettings, I think a better approach will be to create a separate XML file, which will only hold the mappings and from that file you can iterate through the mappings and return correct instance in GetSelector().

How to Use Interface in my Code to make it more scalabale?

I have a ASP.NET web application which has a UI project and BL project. The BL project handles all business logic and data access part.I call the BL methods from my UI by Simply calling the method on the instances.
Public Class User
Public Property UserID As Integer
Public Property FirstName As String
//rest of the properties for user
Public Sub Save()
//save the details to the database
End sub
End Class
and from my UI (its in C#) i do this.
User objUser=new User();
objUser.FirstName="Happy";
objUser.Save();
Everything works fine. Since the project is growing, i thought about trying to add some kind of unit testing/dependency injections tests. Googled around and saw every example uses Interfaces. I read so much about interfaces but don't know how to include interfaces in my coding and makes it to follow a better (scalable & testable) pattern. Other than testability, will it give me some other advantage ?
Can someone provide me a sample how to do that ?
Take a look at the Model-View-Controller design pattern and the asp.net mvc framework. There is a good overview here that explains the benefits of this design strategy.
An excerpt here:
The MVC pattern helps you create applications that separate the
different aspects of the application (input logic, business logic, and
UI logic), while providing a loose coupling between these elements.
The pattern specifies where each kind of logic should be located in
the application. The UI logic belongs in the view. Input logic belongs
in the controller. Business logic belongs in the model. This
separation helps you manage complexity when you build an application,
because it enables you to focus on one aspect of the implementation at
a time. For example, you can focus on the view without depending on
the business logic.
The loose coupling between the three main components of an MVC
application also promotes parallel development. For example, one
developer can work on the view, a second developer can work on the
controller logic, and a third developer can focus on the business
logic in the model.
Coding to interfaces gives plenty of advantages, better testability being one side-effect related to the main advantage: decoupling an object from its dependencies.
Say I have a class A, and in its implementation it uses class B. If you don't provide an interface to B, then you tightly coupled the design of A and B together (you cannot consider A without this specific implementation of B, as it uses the concrete implementation).
If you write an interface to B (say IB) and use it in A instead of using directly B, then you decoupled the design, and made them independent. A is now able to function independently of the specific inplementation B, it only knows an interface to it (IB) and the methods it needs to run on it. So if later on, you decide that your implementation of B wasn't good, or if you want to have A able to work on two different IB depending on the context, you can replace B with B2, which also implements IB, so you don't have to modify A at all.
The action to create A by injecting an implementation of IB at runtime like that:
A myA = new A(new B()); // this could also be new A(new B2()); or anythign else that implements IB
is called dependency injection, and is the best way to achieve a much desirable feature of OO programming: inversion of control (It's not A that control the behaviour of its dependencies anymore, it's an independent class - the factory - that controls what is injected into A).
For testability purpose, you can then unit-test A without making assumptions on B (which obviously needs to be tested separately). So in your tests, you can inject into A a stub or a mocked implementation of B, that will help you test the behaviour you want.
(Sorry no actual codes examples, as I'm a Java developer and not very good with the syntax of C#)
An interface is a description of functionality for a class. Any class that implements the interface must implement the interface's properties, methods, indexers, and/or events. An interface contains no implementation, only the signatures for the functionality the interface provides.
There are a few advantages to using interfaces. One of the big ones is that it allows you to get around the lack of multiple inheritance in .NET. You cannot inherit from multiple classes in .NET, but you can implement multiple interfaces.
Other benefits include loose coupling, easier maintainability, and makes code reuse more accessible since implementation is separated from the interface.
Here's a simple example of how your code could use an interface (using VB.NET):
Public Interface iPerson
Property FirstName As String
Property LastName As String
'Rest of properties for a person
Sub Save()
End Interface
Public Class User
Implements iPerson
Public Property UserId As Integer
Public Property FirstName As String Implements iPerson.FirstName
Public Property LastName As String Implements iPerson.LastName
Public Sub Save() Implements iPerson.Save
'Add code to save user
End Sub
End Class
And from your UI you could then do:
Dim objUser as iPerson = New User
objUser.FirstName = "Bob"
objUser.LastName = "Mckenzie"
ctype(objUser, User).UserId = 12345
If you then decided to create a new class implementing iPerson (ie - SuperUser) most of the code in your UI could remain the same:
Dim objUser as iPerson = New SuperUser
objUser.FirstName = "Bob"
objUser.LastName = "Mckenzie"
'The next line would throw a runtime error since object is not of type user
ctype(objUser, User).UserId = 12345
You could add a layer to bridge the UI and BL. I'm not a fan of the UI knowing anything about the BL. This can be accomplished with interfaces, but it doesn't need to be done with them.

Handling security and be decoupled

I am trying to design an application in 3 layers :
1) Data access layer
2) business layer
3) UI
I try to keep classes decoupled so on the business layer I have created interfaces for the Data access classes like this :
public interface ICountryRepository:IRepository
{
Country GetCountry(int ID);
int CreateCountry(Country obj);
Boolean UpdateCountry(Country obj);
Boolean DeleteCountry(Country obj);
...
...
}
and i pass the interface as param to the service constructor :
public CountryService(ICountryRepository repository,ILanguageRepository lang_repository)
{
....
}
But on the CountryService for example I need to load the current user and his permissions so I can check if the operation can be applied :
public Country GetCountry(int ID)
{
if securityService.UserHasPermission(currentUser, GetPermission("CanGetCountry"))
{
return repository.GetCountry(ID);
}
else
{
Throw(New SecurityException("No permissions for that operation ...."))
}
}
That means I have to instantiate the SecurityDataAccess object and pass it to the constructor of the SecurityService on my business layer assembly which I try to avoid for keeping objects decoupled. Right now I even don't have a reference to any DataAccess assembly on my business assembly.
I am thinking of using an IoC container here. Using external configuration I could get the right class/assembly from a config file. But I am not sure that is the right solution because it is said that IoC containers should be used in one place to keep things simple and it should be the top level assembly (the UI assembly) most of the time.
Anybody has a suggestion for solving this problem ?
Why not add the security service into the constructor of the Country service? That way the IOC Container could resolve the dependency and inject the security if it is needed. That mean the IOC Container would take care of constructing your CountryService object. And you would use the container to get all Services.
Another option could be to "normalize" your repository a bit...
Trim it down to it only has 4-5 basic functions that are identical for all repositories, then use generics to make them all look alike, so no
UpdateCountry(...)
but
Update(T object)
Something like this:
http://codebetter.com/blogs/gregyoung/archive/2009/01/16/ddd-the-generic-repository.aspx
Then you can use a Chain of reponsibilty pattern to place your security code before the DB Code ( http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern )
So you could have a SecurityChecker that validates access, throws an exception if invalid, or passes down the request in the next link in the chain (You can also add a logging dynamically that way, or timing or whatever)
Do you need to implement security in the Data Access layer? If you move your security service to the business layer as Heiko suggests. In other words, perform security in the business layer and you avoid the IoC issue altogether.
This may be off-beam, apologies if it is, I'm a lurking Java EE programmer. It seems to me that authorisation is of methods is better addressed in the infrastructure, declaratively.
This article appears to suggest that .Net, like Java EE offers a facility to control access declaratively. Does this approach work for you?

Resources