Change VirtualPathProvider in MVC 5 - asp.net-mvc-5

I ported my MVC 4 project to MVC 5 and after that my views with is embedded as resources cannot be loaded. Problem is that when mvc search for view it uses view engine witch inherit from BuildManagerViewEngine. This class use FileExistenceCache with use VirtualpathProvider with is set through constructor. By default its MapPathBased provider when I change provider to my custom in HostingEnviroment no change is made in existing FileExistenceCache instances than my view is not founded.
I change VirtualpathProvider in Route config class but its to late. What is better place for this?
Thanks

Rather subclass existing 'IViewEngine' to use custom VirtualPathProvider. Then register your custom engine in Global.asax file.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Add(new MyViewEngine());
}
private class MyVirtualPathProvider: VirtualPathProvider {}
private class MyViewEngine : RazorViewEngine
{
public MyViewEngine()
{
this.VirtualPathProvider = new MyVirtualPathProvider();
}
}
}
This way you can also control which engine has priority by adding, inserting your engine at proper place in Engines collection.
As an alternative, you can use PreApplicationStartMethodAttribute to replace VirtualPathProvider, but this will change provider globally, for all standard IViewEngines.
[assembly: PreApplicationStartMethod(
typeof(MyNamespace.MyInitializer), "Initialize")]
Then you swap provider in public static method in your class:
public static class MyInitializer
{
public static void Initialize() {
HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());
}
}
There is good post by Phil Haack about it: Three Hidden Extensibility Gems in ASP.NET 4

Related

Using StructureMap[4.7.0] Setter Injection in my MVC5 Controller

I am trying to inject the IApplicationConfigurationSection implementation into this MVC5 Controller, so that I can have access to some of the information (various strings) from my web.config custom section in all of my views:
public class BaseController : Controller
{
public IApplicationConfigurationSection AppConfig { get; set; }
public BaseController()
{
ViewBag.AppConfig = AppConfig; // AppConfig is always null
}
}
I want to use setter injection so I don't have to clutter up my derived Controller constructors with parameters that they don't really care about.
Note: If there is a better way to inject base class dependencies, please let me know. I admit I may not be on the right track here.
In my Global.asax I load my StructureMap configurations:
private static IContainer _container;
protected void Application_Start()
{
_container = new Container();
StructureMapConfig.Configure(_container, () => Container ?? _container);
// redacted other registrations
}
My StructureMapConfig class loads my registries:
public class StructureMapConfig
{
public static void Configure(IContainer container, Func<IContainer> func)
{
DependencyResolver.SetResolver(new StructureMapDependencyResolver(func));
container.Configure(cfg =>
{
cfg.AddRegistries(new Registry[]
{
new MvcRegistry(),
// other registries redacted
});
});
}
}
My MvcRegistry provides the mapping for StructureMap:
public class MvcRegistry : Registry
{
public MvcRegistry()
{
For<BundleCollection>().Use(BundleTable.Bundles);
For<RouteCollection>().Use(RouteTable.Routes);
For<IPrincipal>().Use(() => HttpContext.Current.User);
For<IIdentity>().Use(() => HttpContext.Current.User.Identity);
For<ICurrentUser>().Use<CurrentUser>();
For<HttpSessionStateBase>()
.Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session));
For<HttpContextBase>()
.Use(() => new HttpContextWrapper(HttpContext.Current));
For<HttpServerUtilityBase>()
.Use(() => new HttpServerUtilityWrapper(HttpContext.Current.Server));
For<IApplicationConfigurationSection>()
.Use(GetConfig());
Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());
}
private IApplicationConfigurationSection GetConfig()
{
var config = ConfigurationManager.GetSection("application") as ApplicationConfigurationSection;
return config; // this always returns a valid instance
}
}
I have also "thrown my hands up" and tried using the [SetterProperty] attribute on the BaseController - that technique failed as well.
Despite my best efforts to find a solution, the AppConfig property in my controller's constructor is always null. I thought that
`Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());`
would do the trick, but it didn't.
I have found that if I discard setter injection and go with constructor injection, it works as advertised. I'd still like to know where I'm going wrong, but I'd like to stress that I'm not a StructureMap guru - there may be a better way to avoid having to constructor-inject my base class dependencies. If you know how I should be doing this but am not, please share.
While constructor injection in this scenario appears to be the better solution to the stated problem as it follows The Explicit Dependencies Principle
Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.
The mention of only needing to access the AppConfig in your views leads me to think that this is more of an XY problem and a cross cutting concern.
It appears that the controllers themselves have no need to use the dependency so stands to reason that there is no need to be injecting them into the controller explicitly just so that the dependency is available to the View.
Consider using an action filter that can resolve the dependency and make it available to the View via the same ViewBag as the request goes through the pipeline.
public class AccessesAppConfigAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var resolver = DependencyResolver.Current;
var appConfig = (IApplicationConfigurationSection)resolver.GetService(typeof(IApplicationConfigurationSection));
filterContext.Controller.ViewBag.AppConfig = appConfig;
}
}
This now makes the required information available to the views with out tight coupling of the controllers that may have a use for it. Removing the need to inject the dependency into derived classes.
Either via adorning Controller/Action with the filter attribute
[AccessesAppConfig] //available to all its actions
public class HomeController : Controller {
//[AccessesAppConfig] //Use directly if want to isolate to single action/view
public ActionResult Index() {
//...
return View();
}
}
or globally for all requests.
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new AccessesAppConfigAttribute());
}
}
At this point it really does not matter which IoC container is used. Once the dependency resolver has been configured, Views should have access to the required information in the ViewBag

Regular Expression to validate ApplicationUser email address in ASP.net MVC5

I am creating a webapp in asp.net MVC5 which will only allow people with a certain domain to sign up.
From what I understand the easiest way is to use a regular expression. Is there any way to use Data Annotations to change the model, or do I have to play around with the view to achieve this?
Probably a bit too late now but I would suggest as follows:
I've have an app in which I need to modify some of ApplicationUser properties, I am trying something which haven't tested on real life yet, but my Unit Tests are passing so far, it could be useful for you.
Override Email property in ApplicationUser, and add a custom validation annotation:
[ValidateEmailDomain(ErrorMessage = "Not a valid email domain.")]
public override string Email { get; set; }
ValidateEmailDomain code:
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace WATHEVER
{
public class ValidateEmailDomain: RequiredAttribute
{
public override bool IsValid(object value)
{
//code
}
}
}
Note that as ValidateEmailDomain inherits from RequiredAttribute it will become obviously obligatory, if you don't want it that way, you could validate it also when it's null.
Sorry for my English :/
with MVC 5 you're using ASPNET Identiy, and the basic properties are encapsulate inside IdentityUser, so for your case, you cannot have access direct to the field email, but yuo can use EF Fluent API to add some rules, the but part is that regularexpression attribute is not part of the EF Fluent API.
If you need to see how can you use EF Fluent API with ASPNET Identity:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//Define rules
modelBuilder.Entity<IdentityUser>()
.Property(u => u.Email).IsRequired();
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Regards,

Implement Unity MVC 5 dependency injection in ActionFilter

I'm trying to inject this user service via Unity (mvc5) in an actionfilter but it is null. How can I implement this?
public class TestFilter : ActionFilterAttribute
{
// this is always null
[Dependency]
public IUserService UserService { get; set; }
// other members
}
You must register UnityFilterAttributeFilterProvider as a FilterProvider first.
Modify the App_Start > UnityMvcActivator's Start method like this:
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
If you could not find the method. You probably installed wrong or out of date package. consider installing Install-Package Unity.Mvc on the package manager console.

AutoMapper in a class library

I create a class library to put my repositories, domain model and my DTO.
When a user call ClienteRepository.GetById(1) for exemple, it should get the Client domain model and transform into a ClientDTO to return this, example:
public class ClientRepository{
public ClientDTO GetById(int id){
var clientDto = Mapper.Map<Client, ClientDTO>(_db.Client.Find(id));
return clientDto;
}
}
the problem is that Mapper.Map doesn't work because I did not create the map (Mapper.CreateMap<Client, ClientDTO>()).
My question: How can I do this in a class library if I dont have global.asax to create it?
You don't need a Global.asax for Automapper.
It's just the better way to do mapping init for a web project.
Just put your init code in a static constructor
static MyStaticCtor()
{
//samples
//Mapper.CreateMap<AccountViewModel, Account>();
//Mapper.CreateMap<AccountSettingViewModel, AccountSetting>()
Mapper.AssertConfigurationIsValid();
}
or even, you can simply do this in the constructor of your Repository.
I solved my problem using https://github.com/davidebbo/WebActivator. Just create a new class and put this code:
[assembly: WebActivator.PostApplicationStartMethod(typeof (MapsInit), "Activate")]
namespace Database
{
public static class MapsInit
{
public static void Activate()
{
Mapper.CreateMap<ClienteDto, Cliente>();
Mapper.CreateMap<Cliente, ClienteDto>();
}
}
}

Ninject MVC 2 - problems with EF 4 ObjectContext

I've been dealing with this issue for a while, and still can't seem to find a solution. I have several repositories which wrap an EF 4 ObjectContext. An example is below:
public class HGGameRepository : IGameRepository, IDisposable
{
private readonly HGEntities _context;
public HGGameRepository(HGEntities context)
{
this._context = context;
}
// methods
public void SaveGame(Game game)
{
if (game.GameID > 0)
{
_context.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);
}
else
{
_context.Games.AddObject(game);
}
_context.SaveChanges();
}
public void Dispose()
{
if (this._context != null)
{
this._context.Dispose();
}
}
}
And I have the following NinjectModule:
public class DIModule : NinjectModule
{
public override void Load()
{
this.Bind<HGEntities>().ToSelf();
this.Bind<IArticleRepository>().To<HGArticleRepository>();
this.Bind<IGameRepository>().To<HGGameRepository>();
this.Bind<INewsRepository>().To<HGNewsRepository>();
this.Bind<ErrorController>().ToSelf();
}
}
Since I'm using the MVC 2 extension, these bindings default to InRequestScope().
My problem is that the ObjectContext isn't being handled properly. I get what's described here: https://stackoverflow.com/a/5275849/399584 Specifically, I get an InvalidOperationException that states:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
This happens every time I try to update an Entity.
If I set my repos to bind InSingletonScope() it works, but seems like a bad idea.
What am I doing wrong?
EDIT: For clarity, I have just one ObjectContext that I want to share with all my repos per request.
You have to specify InRequestScope() in your module. Based on this article the default to transient, which is why you are getting more than one context.
public class DIModule : NinjectModule
{
public override void Load()
{
this.Bind<HGEntities>().ToSelf().InRequestScope();
this.Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
this.Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
this.Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
this.Bind<ErrorController>().ToSelf().InRequestScope();
}
}
Also did you add ninject to your project via nuget package manager or the old fashion way?

Resources