Accessing HttpContext and User Identity from data layer - c#

I need to implement AddedBy/ChangedBy type fields on my Base Entity that all other entities inherit from ( Fluent Nhibernate ).
Accessing HttpContext.User.Identity from within my Repository/Data layer is probably not a good idea.. or is it ?
What's the best way to grab my user ( current identity ) information to record who the records were added or changed by ?
Re-factoring the entire application to include user information in repository calls would be silly. I'm sure there is a better, more generic way.

Access the HttpContext from the Data Layer makes the life harder, specially if you use Unit Tests. The solution is to create a service to provide application wide user information, something like:
public interface ICurrentUserService {
string UserName {get;}
string UserId {get;}
string HostIP {get;}
// etc.
}
Then you can implement the concrete service and inject it using your
preferred IoC container.
public class CurrentWebUserService : ICurrentUserService {
// implement interface members
public CurrentWebUserService(HttpContext context) { ... }
public string UserName { get { ... } }
// etc.
}
// maybe you want a stub service to inject while unit testing.
public class CurrentUserServiceStub : ICurrentUserService {
}
// data layer
public class MyDaoService {
public DaoService(ICurrentUserService currentUser) { ... }
}

You're correct. Referencing your HttpContext.User.Identity class from within your repository is not a good idea. The HttpContext is a UI concern and as such, should go no further than the UI layer.
What you should be doing is harnessing an IoC container (such as StructureMap) to inject your dependency (HttpContext.User.Identity) details into your repository, or any other layer such as the service layer via dependency injection.
For an example of how this can be setup (in this instance it's the session object) see the latter part of this answer.

HttpContext.Current is a static member that you can access anywhere in the application.
https://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx
Obviously there are problems, such as if you don't HAVE an HttpContext when the code is called.
So HttpContext.Current.User should work for you. I wouldn't recommend it, because your underlying data access code is now depending on stuff that should be kept to your display or controller logic, etc. Also, this assumes that your data access is in the web application itself and not part of, say, an external library.
Personally, I'd just pass in the salient details, like user ID and access time, as part of the add and modify database calls. Make an "AuditTrail" class or something. That would let you reuse that data access code (always a good thing) in another project without having to pull out all the HttpContext stuff.

The AddedBy/ChangedBy field is potentially important in any data backend. You may even want to have AccessedBy for logging purposes. Therefore, you would want to think that the user information is a central part of your data. It is also possible that you may want other details such as the client's IP address logged for security reasons. Probably a good idea to have the entire context rippled down to the data layer so that you have the flexibility to capture and save the client information.

I have used a factory to get the correct repo with or without a "CurrentUser" since sometimes you need to know who the user is and sometimes you don't.
//I have a current user that I got from the Identity
var repo = RepoFactory.GetRepo<Users>(currentUserId);
//I don't have a current user
var repo = RepoFactory.GetRepo<Users>()
This way you can pull the Identity from the HttpContext and pass only details you need to the repo.

HttpContext.User.Identity is of System.Security.Principal.IIdentity type. Don't mess it up with Microsoft.AspNet.Identity library (NuGet package) which is actually pointed by asp.net-identity tag in your question.
Identity lib consists of common part and its ORM implementation. Typically it is for Entity Framework. But if you're going to use Microsoft.AspNet.Identity package in the way you describe with NHibernate, then you most likely will need this package.
I didn't use it, but I used EF implementation. See this answer how to inherit of predefined IdentityDbContext<T> where T is your User class. I guess, NH has similar fluent configuration. Then you can link any of entities in your DbContext to AppUser

Related

Which class should be responsible for creating ID for entity?

I'm struggling a little bit with following problem. Let's say I want to manage dependencies in my project, so my domain won't depend on any external stuff - in this problem on repository. In this example let's say my domain is in project.Domain.
To do so I declared interface for my repository in project.Domain, which I implement in project.Infrastructure. Reading DDD Red Book by Vernon I noticed, that he suggests that method for creating new ID for aggregate should be placed in repository like:
public class EntityRepository
{
public EntityId NextIdentity()
{
// create new instance of EntityId
}
}
Inside this EntityId object would be GUID but I want to explicitly model my ID, so that's why I'm not using plain GUIDs. I also know I could skip this problem completely and generate GUID on the database side, but for sake of this argument let's assume that I really want to generate it inside my application.
Right now I'm just thinking - are there any specific reasons for this method to be placed inside repository like Vernon suggests or I could implement identity creation for example inside entity itself like
public class Entity
{
public static EntityId NextIdentity()
{
// create new instance of EntityId
}
}
You could place it in the repository as Vernon says, but another idea would be to place a factory inside the constructor of your base entity that creates the identifier. In this way you have identifiers before you even interact with repositories and you could define implementation per your ID generation strategy. Repository could include a connection to something, like a web service or a database which can be costly and unavailable.
There are good strategies (especially with GUID) that allow good handling of identifiers. This also makes your application fully independent of the outside world.
This also enables you to have different identifier types throughout your application if the need arises.
For eg.
public abstract class Entity<TKey>
{
public TKey Id { get; }
protected Entity() { }
protected Entity(IIdentityFactory<TKey> identityFactory)
{
if (identityFactory == null)
throw new ArgumentNullException(nameof(identityFactory));
Id = identityFactory.CreateIdentity();
}
}
Yes, you could bypass the call to the repository and just generate the identity on the Entity. The problem, however, is that you've broken the core idea behind the repository: keeping everything related to entity storage isolated from the entity itself.
I would say keep the NextIdentity method in the respository, and still use it, even if you are only generating the GUID's client-side. The benefit is that in some future where you want to change how the identity's are being seeded, you can support that through the repository. Whereas, if you go with the approach directly on the Entity, then you would have to refactor later to support such a change.
Also, consider scenarios where you would use different repositories in such cases like testing. ie. you might want to generate two identities with the same ID and perform clash testing or "does this fail properly". Having a repository handle the generation gives you opportunity to get creative in such ways, without making completely unique test cases that don't mimic what actual production calls would occur.
TLDR; Keep it in the repository, even if your identifier can be client-side generated.

Business logic integrated into entity framework

I've read some of the articles on BL, but the methodology seems counter intuitive to me. It seems to break up normal OOP principles. Here's an very simplified example: A client table contains the birthdate and gender of each client. A life expectancy table contains the clientId, age, and probability of survivorship to that age.
Wouldn't basic OOP principles call for methods to be integrated into the entity? E.g. the calculateSPTable() method in the client class.
class client {
int clientId;
int age;
bool male;
list<surviveProb> lifeExpectancy;
void calculateLifeExpectancy(); // calculates lifeExpectancy
}
class surviveProb {
int surviveProbId;
int clientId;
int age;
double probability;
}
Yet the methodologies today seem to suggest such operations must be in a separate layer and a separate class. Methods operating on entities should not be included in the entity framework entities. This seems counter intuitive. I really want to put methods into EF entities. Is this going to lead to problems? What am I missing here?
After some research I now use some patterns that I think are good for maintenance porpoises and understanding the application.
Let's say you want to register an account.
In the controller, I would have an AddAccountViewModel that only exposes the minimum properties to a user. No worries about him injecting something bad in an unexpected property. Now, using dependency injection, I would call a Facade. Let's say _accountsFacade.RegisterAccount and I would pass the View Model as a parameter.
Inside this method in the facade, I would do the mapping from the View Model to the Model and this Facade would be responsible for doing everything that needed to be done so the account could be created. In my opinion, here is where all the business logic goes. In this Facade, using dependency injection again, I use a unit of Work and add and edit entities to the context. _unitOfWork.AccountRepository.Add(account)
You see? Controllers only "route" the application, facades handle business, unit of work handles the context, the repository only communicates with the data base... And the model only expose properties.
This makes the mapping faster, as stated, and it separate concerns. Sometimes, the logic of adding an account may involve handling different objects that shouldn't be used inside the account object,
I hope you can understand what I want to explain, as my English is not so great.
Was it helpful?

How to add custom methods with database logic

I created an application with this architecture:
MyProject.Model: Contains POCO. Example:
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
}
MyProject.Repositories: Contains repositories and UnitOfWork
public class UnitOfWork
{
// ...
public Repository<Car> Cars { get; set; }
// ...
}
public class Repository<T>
{
// ...
// Add / Update / Delete ...
// ...
}
MyProject.Web: ASP.Net MVC application
Now I want to find a way to interact with data by using methods. For example in MyProject.Model.Car I want to add a method that will get data with non-navigation properties, a method named `GetSimilarCars()'. The problem is that the repository cannot interact with other repositories and thus cannot perform operations on the database.
I don't really know how to do this in a simple manner and what is the best place in my architecture to put this.
Another example could be UserGroup.Deactivate(), this method would deactivate each user and send them a notification by email. Of course I can put this method in the Web application Controller but I think this is no the place to put such code that could be called in many places in the application.
Note: I am using Entity Framework.
Any suggestion on how to implement such operations?
This type of stuff goes into your DAL (essentially your unit of work and repository, in this limited scenario). However, this is a pattern that bit me when I first starting working with MVC. Entity Framework already implements these patterns; your DbContext is your unit of work and your DbSet is your repository. All creating another layer on top of this does is add complexity. I personally ended up going with a service pattern instead, which merely sits on top of EF and allows me to do things like someService.GetAllFoo(). That way, the use of Entity Framework is abstracted away (I can switch out the DAL at any time. I can even remove the database completely and go with an API instead, without having to change any code in the rest of my application.) but I'm also not just reinventing the wheel.
In a service pattern, you're specifically only providing endpoints for the things you need, so it's a perfect candidate for things like GetSimilarCars, as you simply just add another method to the service to encapsulate the logic for that.
I would assume that your Business Layer (BL) would be communicating with your Data Access Layer (DAL). That way from your BL you could reach out to different repositories in DAL. That would solve your problem of repositories not being able to share data (that data would be shared through BL).
See here: N-tier architecture w/ EF and MVC
I did not quite get you question but this is how you assign the values. And add it into a collection
public class Repository<T>
{
List<car> _lstCar=new List<car>();
//Add
car cobj=new car();
cobj.Id="1234";
cobj.Name="Mercedes";
_lstCar.Add(cobj);
}

Should my User model inherit MembershipUser

I'm looking at creating a custom membership provider in ASP.Net MVC3 and am struggling to see how it all fits together...
I'm really looking for some best practice approaches on how to do this.
I have a User model (represnting a Users table in my database). In order to use this with the MembershipProvider functionality, should this model inherit MembershipUser? There are a number of fields in MembershipUser that I do not care about - do these have to be in the underlying SQL table for this approach to work (obviously this seems redundant, as I'll never use the columns?)
For example - should I make my model inherit MembershipUser like this?
/// <summary>
/// Class representing a registered user based on the Users database table.
/// </summary>
public class User : MembershipUser
{
public int Id { get; set; }
//here I can access some other properties I will use which are already in MembershipUser...
//Addtional properties I need specific to my app.
public bool NotifyOfNewBlog { get; set; }
public bool NotifyOfNewWallPosts { get; set; }
//...plus many more.
}
When it comes to using Membership.GetUser() further down the line, do I then cast that object everytime back to my original User object to be able to access the additional properties?
Is this the approach I should be taking? Or do I a separate User model and then a CustomMembershipUser model which links back to the DB model?
Will EF be able to save/update/insert a User model if it doesn't have all the MembershipUser columns as objects in the table? Is this even anywhere near the correct approach? As you can see, I'm scratching my head a bit here.
Any advice/thoughts/ideas are much appreciated.
As far as inheriting the MembershipUser object goes, you could do that, and in your implementation of MembershipProvider, just cast up to your derived type, but I personally would not do this, simply because you are then at the mercy of future changes to this type breaking your derived type (although this could be said about most of the framework I guess). I would instead put these additional values into a profile, and roll your own ProfileProvider, (don't use the Sql one it is rubbish from my experience).
"There are a number of fields in MembershipUser that I do not care about - do these have to be in the underlying SQL table for this approach to work (obviously this seems redundant, as I'll never use the columns?)"
If you are rolling your own, you can just not save this in the Db. After all, you are implementing the MembershipProvider methods (GetUser etc etc) so what you do with the MembershipUser object passed to you, is up to you. You can just ignore these, and not validate or store them.
I had quite the same problem a while ago, and in the end i decided not to pollute my EF models with Membership logic. I have my data access tier in my application, and my EFMembershipProvider use that when he has to save/update data. If i have to GET user data in my application (other than in the membership itself), i don't use Membership (and i don't have to cast nothing).
I want to make clear that if you implement your own Membership Provider
public class EFMembershipProvider : MembershipProvider
you can abstract the underlying functionality of the membership facility to use your own models/repositories.
You can find an example of an implemented membership provider for EF in the MVC3 boilerplate
https://github.com/crdeutsch/MVC3-Boilerplate
Under Web/Infrastructure (though you probably want to modify large parts of it).

Data access architectures with Raven DB

What data access architectures are available that I can use with Raven DB?
Basically, I want to separate persistence via interfaces, so I don't expose underline storage to the upper layers. I.e. I don't want my domain to see IDocumentStore or IDocumentSession which are from Raven DB.
I have implemented the generic repository pattern and that seems to work. However, I am not sure that is actually the correct approach. Maybe I shall go towards command-query segregation or something else?
What are your thoughts?
Personally, I'm not really experienced with the Command Pattern. I saw that it was used in Rob Ashton's excellent tutorial.
For myself, I'm going to try using the following :-
Repository Pattern (as you've done)
Dependency Injection with StructureMap
Moq for mock testing
Service layer for isolating business logic (not sure of the pattern here .. or even if this is a pattern.
So when i wish to get any data from RavenDB (the persistence source), i'll use Services, which will then call the appropriate repository. This way, i'm not exposing the repository to the Application nor is the repository very heavy or complex -> it's basically a FindAll / Save / Delete.
eg.
public SomeController(IUserService userService, ILoggingService loggingService)
{
UserService = userService;
LoggingService = loggingService;
}
public ActionMethod Index()
{
// Find all active users, page 1 and 15 records.
var users = UserService.FindWithIsActive(1, 15);
return View(new IndexViewModel(users));
}
public class UserService : IUserService
{
public UserService(IGenericReposistory<User> userRepository,
ILoggingService loggingService)
{
Repository = userRepository;
LoggingService = loggingService;
}
public IEnumberable<User> FindWithIsActive(int page, int count)
{
// Note: Repository.Find() returns an IQueryable<User> in this case.
// Think of it as a SELECT * FROM User table, if it was an RDMBS.
return Repository.Find()
.WithIsActive()
.Skip(page)
.Take(count)
.ToList();
}
}
So that's a very simple and contrived example with no error/validation checking, try/catch, etc... .. and it's pseudo code .. but you can see how the services are rich while the repository is (suppose to be, for me at least) simple or lighter. And then I only expose any data via services.
That's what I do right now with .NET and Entity Framework and I'm literally hours away from giving this a go with RavenDb (WOOT!)
What are you trying to achieve by that?
You can't build an application which makes use of both an RDBMS and DocDB, not efficiently at least. You have to decide for yourself which database you are going to use, and then go all the way with it. If you decide to go with an RDMBS, you can use NHibernate for example, and then again - no need for any other abstraction layer.

Categories