Resolving issue: ActionFilterAttribute in Unity - c#

I have found this blogpost: http://blog.bitdiff.com/2012/05/sharing-common-view-model-data-in.html?showComment=1499113088147#c5286707438454380796 about sharing strongly-typed common view model data in asp.net mvc, and it look to me like it would solve of the problems I have with keeping track of some user related data across views.
I’m a complete novice when it comes to DI and Unity as I have never used it before, but I have an understanding of the benefits of using it. The post is from May 2012 but should as far as I can see still be valid, perhaps with some small changes.
I’m using C#, MVC 5, EF, Code First, Migrations, Unity V4.01 and Unity.MVC V4.01 with VS2015 Community Edition.
I have followed the blogpost from start to near finish (lacking the test) and all compiles. I have one problem though, this line causes problems:
GlobalFilters.Filters.Add(container.Resolve<LayoutModelAttribute>(), 1);
As far as I can tell the right place to call place the line is in the FilterConfig.cs file in the App_start folder where I’ve done this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var container = UnityConfig.GetConfiguredContainer();
filters.Add(container.Resolve<LayoutModelAttribute>());
}
The container.Resolve gets a squiggly line beneath it and the project won’t compile. The error description is this:
“The non-generic method 'IUnityContainer.Resolve(Type, string, params
ResolverOverride[])' cannot be used with type arguments”
I’ve tried some other places also, but the result is the same, I now lean towards the notion that Unity itself has changed since 2012, and now must be resolved in a different way.
I’m pretty sure I’m doing something wrong and that it properly is because the blogpost is from 2012 and Unity now works in a different way. Due to my lack of experience with Unity, I’m unable to figure out how to change the line of code that won’t compile or to what extend and how to refactor the blogpost if necessary.
I’m hoping someone out there can point me in the right direction.

It seems you are using container without it having a capability of injecting. Have a look at the following answer
Simple Injector property injection on action filter

Related

How find references for MVC controller methods in Visual Studio

Coming from a long period of WebForms development, I recently began working with MVC. One thing that struck me, is that since controller methods are not called directly from code, Visual Studio won't pick up any references to them.
I understand the reason why there is no reference count, but it can be problematic sometimes. Let's say I rewrite a controller method to accomodate some new requirement, perhaps a certain call to the method needs additional data or a modified result. But perhaps that method, or endpoint if you will, is being called from several places, and the change I made breaks the result handling for those other calls. I would like to be able to easily find all the code in my solution, which is going to invoke the endpoint.
Currently I tend to copy the method name and perform a regular text search in the entire solution, which works rather well as long as the method name isn't too generic. If the method name is "Index", it can be a long day.
Are there any recommendations on how to simplify this, such as coding conventions, plugins or otherwise? I.E. how can I locate from where the endpoint will be invoked?
I currently use Visual Studio 2017 Enterprise, but solutions working in other versions as well are preferred - to make the answer useful for as many as possible.
Thanks in advance / Culme
UPDATE: I learned a lot based on the comments and replies I got. Apart from what is mentioned below, I also decided to try and keep my controller method names unique and identifiable, to simplify finding where they are being used. As an example, instead of just "Index", I'll try to use "Fidgets_IndexController" or something similar. That way, a simple text search will go a long way for locating calling code.
Controller methods are not directly referenced from any part of the code (therefore 0 references), but they are dynamically invoked based on RouteTable which maps controller methods on startup RouteConfig.RegisterRoutes(RouteTable.Routes); in global.asax "implicitly" which would map them as /controller_name/action_name or these can be changed by either editing
RouteConfig.RegisterRoutes(RouteCollection routes) or using attributes:
[Route("myAction")]
public ActionResult MyAction() {
...
}
which would bind it to /myAction (without controller name)
further reading:
MSDN - Understanding MVC Application Execution Process
Lifecycle of an ASP.NET MVC 5 Application
ASP.NET MVC Routing Overview
One of the options is Resharper - it more or less can determine where you use Html.ActionLink() or Html.BeginForm() that points to a controller action. But it won't detect any posts/redirects done from JS.
Also another thing you can do is use T4MVC to make the links from views statically typed, so you can search on references.
Text search through the solution can help, but not always good as you already discovered - how many references to string Index do you have in an average MVC project? So this will help with distinctive controller/action names, but not with common names.
Apart from that you are on your own. If you try doing something clever, like in JS concatenate strings to give you the right endpoint - you are in trouble.
Another option if you know the application fairly well. Put a breakpoint on the controller action and then run some tests of the application.

C# Dependency Injection with Unity, a unit of work, a database and the ability to change database at runtime

So I am wrestling with this for quite some time now, but I can't seem to figure it out.
At first I had a datalayer in my solution. This layer is for the communication between the business and the database. It had a generic repository and context objects so it is easy to retrieve and send data from and to the database with EntityFrameWork 6. This all worked very good... but...
Now I notice that in my application (WebAPI 2) I need to change database at runtime. This is really hard to do. It should follow this path:
An external application does a call to my API. In the header of the request is set which database should be used (an Id, or a logic name or whatever, not important now). Before an action is executed some code should read this header-item and set the new connection to the repositories.
This is how I register the repositories for Unity:
container.RegisterType<IContexts.ILanguageCodes<LanguageCode>, Data.LanguageCodes>();
container.RegisterType<IContexts.ISecurityRoles<SecurityRole>, Data.SecurityRoles>();
To show you everything what the implementations of these interfaces are is very much.
To change the connection to an other database I have to change the DBContext, which I know where to find, but the code doesn't. So I started Googling.
Then I found this article: http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/. I read it and all the stuff that is not good is in my project. I was like: Okay, lets start over on the datalayer.
THen I found this article: https://www.danylkoweb.com/Blog/a-better-entity-framework-unit-of-work-pattern-DD. I followed this and came pretty far. But got stuck on the part where the request comes in.
So basicly I am looking for this:
A way to change the connection to an other database at runtime with dependency injection, so I don't have to change the connection everywhere. In the end; the idea of DI is that you don't know where the implementation is, so in this case you don't know where all the connections are.
Does anybody have an example found on the internet I could use to try? Or maybe a good, small example I can focus on?
Long story, I hoped I could make it smaller. I hope someone can help me with this.
Thanks
When I need to support scenarios like this I have one "provisioning" or "configuration" database which holds the connectionstring for each customer/user/whatever. This is separate from the databases which map to the data my application needs.
Whenever the requests comes in you can configure your IOC container with the correct connectionstring, altough I don't know if unity supports this scenario, I know AutoFac / Ninject and most other containers allow changing the container.

Partial view(s) ‘Enum.cshtml’ implementation works nice while excluded from the project (while included it generates compilation error)

Is there anybody out there how can explain why the ‘enum implementation’ as suggested in article [http://www.codeproject.com/Articles/776908/Dealing-with-Enum-in-MVC] works while both partial views of Enum.cshtml are NOT a part (excluded!) of the project?
Explanation
Currently, I am using MVC 5.2.1 to set up a new project. In this project, as many others, I have to use enumerations, more precisely, fancied ones with Display attributes. In this current version, luckily, we do not have to add enum helpers (as I was doing according K. Scott Allen’s’ tutorial ‘ASP.NET MVC 5 Fundamental’ (chapter Entity Framework 6, clip Scaffolding, free assessable) [https://app.pluralsight.com/player?course=aspdotnet-mvc5-fundamentals&author=scott-allen&name=aspdotnet-mvc5-fundamentals-m6-ef6&clip=4] on PluralSight.
Using fancied enumerations, out-of-the-box pops, with this version of MVC, on several Create views the EditorFor extension has been exchanged with the new EnumDropDownList extension. So far, so good!
On this particular part no extension method such as an EnumHelper has to be set anymore, nice.
However…, due to what several others members already mentioned, having some trouble displaying those fancied enumerations on an Index – or Edit view, I took their tips for granted and followed this post on Code Project [http://www.codeproject.com/Articles/776908/Dealing-with-Enum-in-MVC] right away. Comparing what I have learned in K. Scot Allen’s clip and what has been posted by Shahriar Hossain, it turned out that both directions did NOT work. Following the clip of Scot Allen, his manually configured EnumHelper isn’t touched programmatically, on the other hand following Shahriar post, it gave errors like not able to find the enum.cshtml during compile time.
From a chronologically point of view, my ‘water’ is telling me that the tips of Shahriar must work one way or the other, so … something else apparently is ‘not in sinc’.
Solution (work-around type)
Finally, I figured out (however, what I essentially hate is reaching some goals simply through trial-error, not really knowing what I’m doing) that I had to EXCLUDE both partial views from the project (in both template folder; the DisplayTemplates- as well as the EditorTemplates one) to get it working.
So, the implementation of partial view(s) ‘Enum.cshtml’ works nice while excluded from the project (however included it generates a compilation error). May be this trial-error tip helps others facing comparable trouble.
Is there anybody out there how can explain why the ‘enum implementation’ as suggested works while both partial views of Enum.cshtml are NOT a part (excluded!) of the project.

IOwinContext context is null

I have moved my mvc4 application into mvc5 by creating a new application and copying the code in - to avoid any conflicts while updating the DLL's
When I debug my new solution, no pages can be loaded as the built in IdentityConfig.cs is throwing a nullreferenceexception on the IOwinContext.
the code is breaking at the following line
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
As this is practically OOTB mvc5, and I haven't worked with it before, I am not sure why it is throwing null.
any help?
I get that this is old, but I spent a while figuring it out,and I want to spare others the pain.
Make sure there is a Create() method in your DB context.
Make sure in Startup.Auth there is a line similar to: app.CreatePerOwinContext(ApplicationDbContext.Create);
Make sure (and this is critical) that last line is not commented out.
ok, this is an answer and probably a unique scenario. I actually had a dbcontext with exactly the same name as the one I wanted to use (it was legacy code) and I had actually added a Create statement to that same dbcontext by mistake...so, it was calling the wrong dbcontext and the wrong create method!
All sorted now though :-)

FluentNHibernate Database Deployment

I'm looking into using FluentNHibernate as my ORM but I'm wondering how best to write the database deployment section. I've prior experience with Entity Framework and code first migrations, but I'm curious about FluentNHibernate so I'm playing around. I've looked at FunnelWeb Blog but I haven't got the time, yet, to really get to grips with how they're doing it, so I'm after some help with a very specific part of the project, which I hope someone can summarise.
My Visual Studio solution is separated in the following assemblies (I'm going to look into using an IoC like Autofac, but that will come later):
Solution
Domain Assembly
DatabaseDeployment Namespace
Model Namespace
Web UI
So, in my domain assembly I'd like to have a DBMigrator class who's contract will look something like this:
public interface IDBMigrator
{
bool NeedsUpdating();
void UpdateDatabase();
}
Now, in my WebUI assembly (which is an MVC3 project) I would like to do something like the following (in the global.asax):
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var migrator = new DBMigrator();
if (migrator.NeedsUpdating())
{
migrator.UpdateDatabase();
}
}
This migrator will using .sql scripts (so I can have my database version controlled by Subversion) and likely have a table in the database that tells me what scripts have been executed against the schema, and what scripts haven't yet. So, to summarise I suppose my actual questions are:
Am I on the right track to version controlling (and automating) my database deployment?
At what point should I be checking for (and applying) schema changes to my project, should this really be automated or developer instigated?
I'm looking at some frameworks now such as DbUp and MigratorDotNet but I'd like to get my strategy right in my head first, before I go and adopt a framework for this. How do you handle your database migrations?
Take a look at FluentMigrator
http://nuget.org/packages/FluentMigrator
I couldn't find a specific tool that did what I wanted, so have made my own following the convention in my question. If anyone else comes across this and wants to use it, they can grab it from here:
NuGet Package Manager link
User Guide

Categories