Custom ASP.Net Membership Provider and Certain Properties - asp.net-membership

Implementing a custom membership provider, there are certain properties such as MinRequiredPasswordLength that only provide a getter.
The documentation I find online illustrates that these properties are configured in web.config.
However, it's not clear to me if System.Web.Security.MembershipProvider (from which my custom provider is derived) will read the web.config settings and set appropriate values, or if my concrete subclass is responsible for that task.
Does the base class read and set the values, or am I responsible for doing that in my subclass?

I would have thought the base class would certainly have handled that, given it's meant to be read from web.config. However, checking here -- http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.minrequiredpasswordlength.aspx -- this is how MembershipProvider declares the property:
public abstract int MinRequiredPasswordLength { get; }
So ... I guess you're responsible for that, eh?

Related

Why must database name be specified in AbstractMongoClientConfiguration?

In https://github.com/spring-projects/spring-data-mongodb it specifies that AbstractMongoClientConfiguration implement String getDatabaseName(). Furthermore, this implementation is mandatory. I found this inconvenient to have to manage the database name property in the implementation when all I want to do is override something else (e.g. configureConverters()). Is there a reason getDatabaseName() could not have a default implementation in AbstractMongoClientConfiguration where the MongoProperties could be injected and used to derive the database name? I considered raising an issue on github, but noticed there's no "Issues" tab, so asking here.

MVC Autofac ExtensibleActionInvoker stops me using interface parameters

I have a problem with the Autofac ExtensibleActionInvoker interacting with the MVC ModelBinder when using interfaces for parameters. The background is as follows:
I am building a MVC application and I am using Autofac MVC3's ExtensibleActionInvoker to inject my services as parameters to my actions, e.g.
public ActionResult Test( IMyService service)
{
//A new instance of service is created by Autofac ExtensibleActionInvoker
return View();
}
This works really well and makes for a really clean design (see Alex Meyer-Gleaves post for more information on this approach). I want to use this method as I am producing a code generator to create actions, views, services and DTOs and a per-action service approach makes this easier.
However I also want to use interfaces for the parameters in action classed which receive input from an HttpPost action. This is because I use DI to create classes outside each layer. If I change the DefaultModelBinder to use DI to create the class (see page 595 of Steve Sanderson's book on MVC3 on how to do this) this this works fine, e.g.
[HttpPost]
public ActionResult Test(ITestClass dataComingFromView)
{
//model binder creates the class via DI and then binds it to the data from the post
return View();
}
However in the above simple example above I get a conflict with the ExtensibleActionInvoker enabled, i.e.
Without ExtensibleActionInvoker enabled the method above works fine, i.e. the extended
DefaultModelBinder uses DI to create the TestClass class and modelbinder binds
input from the view to the fields in the class.
With ExtensibleActionInvoker enabled it does not work, i.e. I get an empty TestClass class with no binding. I assume the ExtensibleActionInvoker takes precedence over the model binder and just creates an empty TestClass class.
(Just for completeness I should say that if I just use MVC "out of the box", i.e. no new DefaultModelBinder and no ExtensibleActionInvoker enabled, then it says you cannot use an interface as an Action method parameter.)
My question for anyone with better Autofac knowledge than me is: can I change the Autofac ExtensibleActionInvoker to select what it binds to? All my injected service classed start with IService so I could filter on that. I know you can do that in Autofac elsewhere but couldn't see anything to do that with ExtensibleActionInvoker, but maybe I missed it.
Any help would be appreciated.
Jon Smith - Selective Analytics
You are correct that the problem is caused by the ExtensibleActionInvoker class. If you look at the source for it, there is a method called GetParameterValue(). See below:
protected override object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
{
if (_injectActionMethodParameters)
return _context.ResolveOptional(parameterDescriptor.ParameterType) ?? base.GetParameterValue(controllerContext, parameterDescriptor);
return base.GetParameterValue(controllerContext, parameterDescriptor);
}
This method overrides the method that eventually uses the MVC framework's model binder infrastructure. What this means, is that the ActionInvoker tries to resolve the parameter using AutoFac first, and if it fails, falls back to the default functionality. Based on the results you are getting, it seems that your AutoFac configuration must be setup to provide a default resolution of ITestClass.
In order to register a custom ModelBinder with AutoFac you have a couple options. You can decorate the view model with a ModelBinderTypeAttribute or you can do it in your configuration with the custom extension methods found in RegistrationExtensions.
One article I found looks like it provides an easy solution to a similar issue (see the end), but I have not tested this personally.
Having now worked on this problem I found a simple answer. My problem was due to me not really understanding how the MVC Model Binding worked.
If you look at my orginal problem I had created a DefaultModelBinder to allow me to use interfaces as my model parameters (see original question at the top). This was added after me including the Autofac's ExtensibleActionInvoker to bind my IService types. The problem was that the two DI approaches clashed.
The answer was that the DefaultModelBinder was sufficient to bind both my data classes and the Service definitions, so I do not need Autofac's ExtensibleActionInvoker. For completeness I have included the DefaultModelBinder code in case it is useful to anyone else.
public class DiModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
return modelType.IsInterface
? DependencyResolver.Current.GetService(modelType)
: base.CreateModel(controllerContext, bindingContext, modelType);
}
}
Note that I only call the DependencyResolver if the modeltype is an interface as I don't pass abstract classes between layers. Any alternative is to always call the DependencyResolver and then call the base.CreateModel if the DI does not resolve the type. I didn't do this because calling the DependencyResolver is slightly expensive so I only call it when I know I need it.

Defining data annotation using DbContext versus Objectcontext in the database first approach

I am using the database first approach with entity framework, when i used to work on the default template the database tables were mapped using the ObjectContext, so i used to create #partial classes & [MetadataType(typeof ) to apply the data annotation ,, but when i start using the Dbcontext code generation template to map the database tables i found that it will create .tt folder in my Model area were i find that i can apply the data annotation directly to the .cs classes themselves without the need to create partial classes as in objectcontext case.
Currently the data annotations are working fine,, but would my approach cause me problems i am not aware of and i should create partial classes as i used to do with the Objectcontext ?
BR
In general, you shouldn't edit generated code because changes you make will be overwritten on re-generation. This is why most generators emit partial classes.
The best practice for your situation would be to create a new file in your solution with another partial class declaration. In that file, add the MetadataType attribute to the class, and add your property-level validation attributes to the "buddy" class (the one referenced in the attribute). This allows you to use validation attributes on the generated properties and, should your model/database change, you can still re-generate your model classes without losing them.
For example, your new file might look something like:
[MetadataType(typeof(PersonMetadata))]
partial class Person
{
// Add logic to the generated class in here.
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
class PersonMetadata
{
// Add attributes to the generated properties in here.
[Required]
public string FirstName { get; set; }
}
Create the same partial classes to define your metadata OR you can simply reverse engineer your existing database using the Entity Framework Power Tools so you have POCO classes. Then you can use the fluent API (you'll see the validations it adds for you) instead of data annotations to give you server side validation.
If you want client side, then you can still apply them to your models, as they wont be regenerated every time you compile .
however - I would recommend you create ViewModels and use AutoMapper to map between your EF objects and viewmodels. Then you can apply your annotations directly to your ViewModels.
My understanding of your situation is that you reverse-engineered your Database-First style to a Code-First style. If your context class inherits from DbContext, you are in Code-First style now (unless there is some strange hybrid possible, which I don't know about!).
In code-first, there is really no point of creating partial classes for data annotations, IMO.

ASP.Net MVC3, DataAnnotations and Dynamic Validation

I'm creating an MVC 3 application that needs to establish data validation rules at runtime based on external data (e.g. Required, MinimumLength, MaximumLength). It seems natural to use Data Annotations in MVC 3, however the property attributes that provide validation metadata are set at compile-time.
Is there a pattern to use Data Annotations with metadata provided at runtime?
Example:
public string Text { get; set; }
public void SetIsRequired(string propertyName, bool required)
{
// Somehow find the property 'propertyName' and create/remove a RequiredAttribute
// on that property
}
...
SetIsRequired("Text", true);
I'm aware of TypeDescriptor, but don't see an option to modify attributes of a property of an instance (only class level attributes on an instance, or property level attributes for a type).
It seems natural to use Data Annotations in MVC 3
Not for me. I never really liked data annotations due to their declarative nature. And doing validation in a declarative way limits capabilities. I have always liked and use FluentValidation.NET.
You could probably use the IDataErrorInfo interface (which MVC can consume) to write your custom, dynamic, validation rules.

Extend linq-to-sql partial class to avoid writing a property?

I have a linq-to-sql class. I have a property "Password" for which I want to call the underlying ASP.NET Membership provider. Thus, I do not want this property written out directly but via my own code. I basically want to create a facade/proxy for this property such that I may use the underlying membership provider or a custom stored procedure.
I want to accomplish without modifying the LINQ-TO-SQL designer generated code, if at all possible.
It is possible. You can add your properties and methods to linq generated class using partial class mechanism. Linq generated classes are marked partial so you can add class members with:
public partial class YourLinqClass
{
// your methods and properties. refer linq properites and methods with "this."
// example:
public string Password
{
get
{
int id = this.UserId;
string password = // ... get password
return password;
}
set
{
// ...
}
}
}
You have to place the partial class in the same namespace as the rest of dbml.
The best option is to remove the property from the designer and write it in code, in the partial class, as described by PanJanek.
However, if you do it this way, you are pursuing a bad design. You're introducing a dependency into your entity class that breaks layer encapsulation. Entity classes shouldn't know about providers any more than they know about the DataContext that loads them. They aren't really meant to be anything more than containers for data going in and out of the database.
You should consider making a separate class that wraps the entity, the context, the username provider, and whatever other services you require, and in that class retrieve the username and do the required operations to your entity.
It looks like it might be possible to create a custom DataContext to handle this situation.
http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
There are partial methods for the individual properties as, well and an OnValidate method.
In my case, I think the best solution is to throw an exception in the property changing method and add a public method for setting this individual property. This solution while not perfect will avoid touching the SQL generated code, where the property could be set to readonly or the setter removed.
Other suggestions welcome.

Resources