ASP.NET custom MembershipProvider and shared DbContexts - asp.net

I have created a custom MembershipProvider in an MVC web appliocation. My GetUser function returns an instance of my own custom Employee class which inherits from the standard MembershipUser. This allows me to supply additional details for the each user such as various employee details.
public override MembershipUser GetUser(string username, bool userIsOnline)
{
return new ModelRepository().GetModels<Employee>().Where(e => e.UserName == username).FirstOrDefault();
}
The problem I'm having, the membership provider spawns a new instance of my repository class (which creates a new DbContext) to retrieve the Employee object. This Employee object is then passed to whatever request/controller action called the Membership api.
Employee currentUser = (Employee)Membership.GetUser();
That calling request will often want to create a new object in memory, lets say a new SicknessRecord and assign the user retrieved earlier to that record and then save it to the DB with its own model repository. You can probably see where this is going, the framework complains that I'm trying to save an object (the user) with a context that it wasn't initially retrieved with.
My current, rather hackish solution is to just use the ID of the user retrieved from the Membership.GetUser and go and re-retrieve the Employee object from my current model repository.
newSickness.Employee = this.modelRepository.GetModelById<Employee>(this.me.Id.Value);
I've tried detaching the Employee object but then it loses its lazy loaded properties and I have to remember to try and attach it again to my current repository/context.
I've also read it is good to have your custom membership provider share the same context that the current request would be using. Any ideas how to achieve this, how do I ensure the membership provider uses the same context as the one spawned when a user executes a controller action?

You can have one separate DbContext instance for each controller.
public class SomeController : Controller
{
private DbContext context = new DbContext();
private CustomMembershipProvider membershipProvider = new CutomMembershipProvider(this.context);
... Actions ....
}
As far as I know, one context per controller is good practice.
By the way, if you have several repositories try to use UnitOfWork with Repository pattern.

Related

Making my identity 2.0 custom extension method thread safe

So I created a class to hold user settings and i'm saving it as a JSON string so that I can modify it whenever I please without doing migrations every time I add one setting.
Anyways everything is working wonderful, well until, exception, I look further into it, and I've found things about it being thread safe but I don't really understand what they mean, how is my simple function that accesses entity identity dbcontext, not thread safe?
public static AppUserSettings GetUserSettings(this IIdentity identity)
{
var user = IdentityDbContext.Users.Find(identity.GetUserId());
return user.SettingsClass != null ? JsonConvert.DeserializeObject<AppUserSettings>(user.SettingsClass) : new AppUserSettings();
}
and the sister function:
public static void SetUserSettings(this IIdentity identity, AppUserSettings toSaveUserSettings)
{
var user = IdentityDbContext.Users.Find(identity.GetUserId());
user.SettingsClass = JsonConvert.SerializeObject(toSaveUserSettings);
DatabaseUtil.SaveChanges(IdentityDbContext);
}
Any help is appreciated, if need be I can attach other classes and/or snippets, but I feel like it is largely a Identity/Entity issue.

ASP.NET MVC How does AuthorizeAttribute support checking Roles?

In my controllers, I have code like [Authorize(Roles = "Administrators")] annotated above some actions, and I want to know how AuthorizeAttribute uses the Roles parameter (the implementation of the checking mechanism). My goal is to create an extension of this class, called PrivilegeAttribute for example, so that I can annotate actions like [Privilege(Privileges = "read")]. In this class, I would check if the Role of the user has at least one of the privileges in this custom filter (read in this example). I have already created the association between roles and privileges in the code and in the database, and what I want help with is checking whether the role is associated to the privilege.
I tried seeing if that information is there in HttpContextBase.User.Identity but I couldn't find it.
Thank you.
If you don't need your own custom attribute and could live with using someone else attribute, than I would suggest to use the package Thinktecture.IdentityModel.Owin.ResourceAuthorization.Mvc as described here
Blog Post by Dominick Baier
and here
Git Hub Sample Code for the Package
so it basically works like this:
you put an attribute over your action like this:
[ResourceAuthorize("View", "Customer")]
The first argument is the name of the Action to check, the second one is the name of the attribute.
Then you derive from ResourceAuthorizationManager in your code and override the CheckAccessAssync Method
public class MyAuthorization : ResourceAuthorizationManager
{
public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context)
{
var resource = context.Resource.First().Value;
var action = context.Action.First().Value;
// getting the roles that are connected to that resource and action
// from the db. Context could of course be injected into the
// constructor of the class. In my code I assume that the table
// thank links roles, resources and actions is called Roles ToActions
using(var db = MyContext())
var roles = db.RolesToActions // Use your table name here
.Where(r => r.Resource == resource && r.Action == action).ToList();
foreach(var role in roles)
{
if(context.Principal.IsInRole(role.Name)
{
return Ok();
}
}
return Nok();
}
}
}
So I hope this helps. If you prefer to implement your own attribute however, than the source code from the ResourceAuthorization GitHub Repository should be a good starting point

ASP.NET MVC Design Question - Where to put DB access code?

I've been playing around with ASP.NET MVC for the past few weeks. I've got a simple web application with a form which contains a number of drop down lists.
The items in the drop down lists are stored in a database, and I'm using LINQ to SQL to retrieve them.
My question is - where's the appropriate place to put this code? From what I've read so far, it seems that it's advisible to keep the Controller 'thin', but that's where I currently have this code as it needs to be executed when the page loads.
Where should I be putting DB access code etc.? I've included an excerpt from my controller below.
Thanks.
public ActionResult Index()
{
TranslationRequestModel trm = new TranslationRequestModel();
// Get the list of supported languages from the DB
var db = new TransDBDataContext();
IEnumerable<SelectListItem> languages = db.trans_SupportedLanguages
.Select(c => new SelectListItem
{
Value = Convert.ToString(c.ID),
Text = c.Name.ToString()
});
ViewData["SourceLanguages"] = languages;
ViewData["TargetLanguages"] = languages;
return View();
Your database access code should be in a repository. Example:
public interface ITranslationRepository
{
Translation GetTransaltion();
}
and the controller would use this repository:
public class TransaltionController : Controller
{
private readonly ITranslationRepository _repository;
public TransaltionController(ITranslationRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
// query the repository to fetch a model
Translation translation = _repository.GetTransaltion();
// use AutoMapper to map between the model and the view model
TranslationViewModel viewModel = Mapper.Map<Translation, TranslationViewModel>(model);
// pass the view model to the view
return View(viewModel);
}
}
So the basic idea is the following:
The controller queries a repository to fetch a model
The controller maps this model to a view model (AutoMapper is great for this job)
The controller passes the view model to the view
The view is strongly typed to the view model and uses it to edit/display
As far as the implementation of this repository is concerned feel free to use any data access technology you like (EF, NHibernate, Linq to XML, WCF calls to remote resources over the internet, ...)
There are the following advantages:
The controller logic is completely decoupled from the data access logic
Your controllers can be unit tested in isolation
Your models are not littered with properties that should belong to the UI layer (such as SelectListItem) and thus are reusable across other types of application than ASP.NET MVC.
The view model is a class which is specifically tailored to the needs of the view meaning that it will contain specific formatted properties and the view code will be extremely readable.
Your views are strongly typed => no more ViewData and ugly magic strings
Suggest that your data-access code should be contained in its own project/assembly. That is referenced by the UI tier (ASP.NET MVC application). That'll help achieve the goal of keeping your Controllers thin, and keep all the data access code out of your MVC UI project.
That typically leads to another question/discussion about domain entities: when mapping to the data store. Some architects like to have the entities in their own separate assembly. This encourages reuse in other applications. Some like to keep the entity model and data access code in the same project/assembly. This is totally up to you and your environment.
For an example, let's say it's a billing application; holding customers, invoices, etc.
Your implementation will be different, depending on your data access strategy (an ORM like LINQ To SQL, EF, nHibernate, SubSonic, or plain old ADO.NET, or reading from a flat file).
// Assembly: InvoicingDL
public class CustomerRepo
{
public IQueryable<Customer> ListCustomers()
{
return MyDatabase.Customers(); //however you'd get all your customers
}
//etc
}
// Assembly: InvoicingDL
public class InvoicingRepo
{
public IQueryable<Invoice> GetCustomerInvoices(int custID)
{
return MyDatabase.Invoices.Where(i=>i.CustomerID==custID);
}
//etc
}
Check out the Repository pattern
https://web.archive.org/web/20110503184234/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx
http://www.mindscapehq.com/blog/index.php/2008/05/12/using-the-unit-of-work-per-request-pattern-in-aspnet-mvc/
The idea is you abstract your data access in something called a repository that returns domain objects. Your controller can then use this repository to get the appropriate objects from the database and assign them to the model.

ASP.NET SQL Profile Provider - Does the ProfileBase.Create() method hit DB?

I am working with the SQLMemebershipProvider and using Profiles. I have a custom class called UserProfile that inherits from the ProfileBase class and I use this to set custom properties like "FullName". I am wanting to loop through all the users in the database and get access to their profile properties. On each iteration I am calling ProfileBase.Create() to get a new profile and then access the properties.
It looks to me like every time ProfileBase.Create() is called it hits my SQL database. But I am just looking for confirmation of this. So, does anyone know if this does in fact hit the DB each time?
And better yet, does anyone have a better solution of how I could make one call to the DB to get all users with their custom profile attributes?
I know I could write my own stored proc, but I am wondering if there is a way built in to the Membership Provider.
Mike, I believe what you observed is true. I am working with a ProfileProvider that uses Azure TableStorage as data store. I wanted to get a list of user profiles from database and merge them with information from membership provider.
It took some time until I realized that calling ProfileBase.Create() with a username as argument performs a lookup against TableStorage and actually retrieves the data associated with that username. As far as I'm concerned, calling this method Create() is misleading, I would expect Load() or Get().
Currently my code looks like this:
public IEnumerable<AggregatedUser> GetAllAggregatedUsers()
{
ProfileInfoCollection allProfiles = this.GetAllUsersCore(
ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)
);
//AggregatedUser is simply a custom Class that holds all the properties (Email, FirstName) that are being used
var allUsers = new List<AggregatedUser>();
AggregatedUser currentUser = null;
MembershipUser currentMember = null;
foreach (ProfileInfo profile in allProfiles)
{
currentUser = null;
// Fetch profile information from profile store
ProfileBase webProfile = ProfileBase.Create(profile.UserName);
// Fetch core information from membership store
currentMember = Membership.FindUsersByName(profile.UserName)[profile.UserName];
if (currentMember == null)
continue;
currentUser = new AggregatedUser();
currentUser.Email = currentMember.Email;
currentUser.FirstName = GetStringValue(webProfile, "FirstName");
currentUser.LastName = GetStringValue(webProfile, "LastName");
currentUser.Roles = Roles.GetRolesForUser(profile.UserName);
currentUser.Username = profile.UserName;
allUsers.Add(currentUser);
}
return allUsers;
}
private String GetStringValue(ProfileBase profile, String valueName)
{
if (profile == null)
return String.Empty;
var propValue = profile.PropertyValues[valueName];
if (propValue == null)
return String.Empty;
return propValue.PropertyValue as String;
}
Is there a better (more straightforward, more performant) way to
retrieve all the custom profile information from profile provider and
merge them with membership provider info to show them e.g. in an administrator page?
I have had a look at Web Profile Builder but IMO this only provides design-time intellisense for custom profile properties by generating a proxy class.
You don't persist to the database until you call Save:
The Save method writes modified
profile property values to the data
source. The profile provider can
reduce the amount of activity at the
data source by performing updates only
when the IsDirty property is set to
true. This is the case for the default
SqlProfileProvider.

IRepository confusion on objects returned

I have some e-commerce code that I use often that uses Linq To SQL for saving orders to the database. I want to remove the tightly coupled Linq to SQL bit and pass in an IRepository instead but I am still a little confused on things.
Say I have a GetCustomer() method on my ICustomerRepository that returns a Customer object.
Do I need it to really return an ICustomer object that gets passed back from that method so if I switch from Linq To SQL to say SubSonic it's not a problem?
I believe I do, if that is the case is there a way in Linq To SQL to easily convert my Linq To SQL Customer object to my ICustomer object like SubSonics ExecuteSingle(Of ) method?
If you want your Customer class to be a plain object with no attachment to LINQ, then you will most likely need to write a mapper method to convert your LINQ-based Customer object to your plain Customer domain object. LINQ to SQL does not have such functionality built-in.
I have begun to wrap my mapping methods in an extension method for readability, and it really helps to keep the Repository code simple. For instance, an example CustomerRepository method my look like:
public Customer GetById(int id)
{
return dataContext.LINQCustomers.Where(c => c.Id == id)
.Single()
.ToDomainObject();
}
and the ToDomainObject() method is defined in an extension method like:
public static class ObjectMapper
{
public static Customer ToDomainObject(this Customer linqObject)
{
var domainObject = null
if (linqObject != null)
{
domainObject = new Customer
{
Id = linqObject.Id,
FirstName = linqObject.FirstName,
LastName = linqObject.LastName
}
}
return domainObject;
}
}
or something similar. You can do the same to convert your domain object back to a LINQ object to pass back into your repository for persistence.
You can have it return a Customer as long as Customer is a plain old .NET object, and not some db-generated entity. Your Customer domain object should have no knowledge about how (or if) it might be persisted to a database, and this is what should be returned from your repository. In your repository you might have some mapping code - this is quite common - that maps from [however you get the data back from its storage location] to your domain object. If you're using Linq-to-sql then this mapping would be from the Linq-To-Sql generated Customer table (and perhaps other tables - your Customer domain object likely won't map 1:1 to a particular table in the database) to your Customer domain object, which would live in a different namespace (and most likely, assembly).
There is no need to make it an ICustomer at all. A repository acts in a way as to make it look as though your persistent instances are in memory.
public interface ICustomerRepository
{
Customer GetByID(int id);
IEnumerable<Customer> GetByName(string name);
Customer GetByVatCode(string vatCode);
}
Some people would additionally include methods such as
void Add(Customer newCustomer);
void Delete(Customer deleted);
void Update(Customer modified);
The latter method implementations would most likely just update a unit of work.
The concept though is that these are just common ways of asking for Customer instances, the repository acts as a way of asking for them without defining how to ask for them.

Resources