Castle Windsor does not work under Medium Trust - asp.net-mvc

When attempting to run an ASP.NET MVC application which uses Castle Windsor, the following error occurs.
Server Error in '/' Application.
Inheritance security rules violated while overriding member:
'Castle.MicroKernel.DefaultKernel.InitializeLifetimeService()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Inheritance security
rules violated while overriding member:
'Castle.MicroKernel.DefaultKernel.InitializeLifetimeService()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[TypeLoadException: Inheritance security rules violated while
overriding member:
'Castle.MicroKernel.DefaultKernel.InitializeLifetimeService()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.]
Castle.Windsor.WindsorContainer..ctor() +0
The assemblies Castle.Core.dll and Castle.Windsor.dll have been built off the source code available on github. The source code for the assemblies includes the file SecurityAssemblyInfo.cs which has the following source code:
// Sets up assembly level security settings
#if ! SILVERLIGHT
[assembly: System.Security.AllowPartiallyTrustedCallers]
#if DOTNET40
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level2)]
#endif
#endif
I have verified using ILSpy that the System.Security.AllowPartiallyTrustedCallers attribute is declared at the assembly on both files.
The web application is being run with <trust level="Medium" />.

I have been able to get a successful build + run of my mvc application by making the following changes to Castle.Core:
SecurityAssemblyInfo.cs:
Changed to only the following:
[assembly: System.Security.AllowPartiallyTrustedCallers]
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
ProxyGenerator.cs:
Changed three lines in ProxyGenerator::ProxyGenerator(IProxyBuilder):
if (HasSecurityPermission())
{
Logger = new TraceLogger("Castle.DynamicProxy", LoggerLevel.Warn);
}
becomes:
// if (HasSecurityPermission())
// {
// Logger = new TraceLogger("Castle.DynamicProxy", LoggerLevel.Warn);
// }
I have no idea what sort of consequences these might have. It would be nice if someone familiar with the SecurityRuleSets could chime in on the first part, and #Krzysztof Koźmic could advise me on why I had to comment out the trace logger.

Related

Visual Studio 2017 Error initializing VroomJs.JsEngine

My project uses Reactjs, and I use Visual Studio 2017. Recently I did an software update on VS 2017, but no code/config changes.
However, when I start my project locally in debug mode, I encountered below error:
No JavaScript engines were registered, falling back to a default config! It is recommended that you configure JavaScriptEngineSwitcher in your app. See https://github.com/Taritsyn/JavaScriptEngineSwitcher/wiki/Registration-of-JS-engines for more information.
Error initialising JavaScriptEngineSwitcher.V8.V8JsEngineFactory: JavaScriptEngineSwitcher.Core.JsEngineLoadException: During loading of V8JsEngine error has occurred.
See more details:
Cannot load V8 interface assembly. Load failure information for v8-ia32.dll:
C:\Users\user1\AppData\Local\Temp\Temporary ASP.NET Files\vs\77655ce5\ca0bb6d0\assembly\dl3\300b733a\003cadac_c3f4d201\v8-ia32.dll: The specified module could not be found
C:\Code\project1\branches\apps\src\DotNet\COMP.project1.Web\v8-ia32.dll: The specified module could not be found
C:\Code\project1\branches\apps\src\DotNet\COMP.project1.Web\bin\v8-ia32.dll: The specified module could not be found ---> System.TypeLoadException: Cannot load V8 interface assembly. Load failure information for v8-ia32.dll:
C:\Users\user1\AppData\Local\Temp\Temporary ASP.NET Files\vs\77655ce5\ca0bb6d0\assembly\dl3\300b733a\003cadac_c3f4d201\v8-ia32.dll: The specified module could not be found
C:\Code\project1\branches\apps\src\DotNet\COMP.project1.Web\v8-ia32.dll: The specified module could not be found
C:\Code\project1\branches\apps\src\DotNet\COMP.project1.Web\bin\v8-ia32.dll: The specified module could not be found
at Microsoft.ClearScript.V8.V8Proxy.LoadNativeLibrary()
at Microsoft.ClearScript.V8.V8Proxy.LoadAssembly()
at Microsoft.ClearScript.V8.V8Proxy.GetAssembly()
at Microsoft.ClearScript.V8.V8Proxy.GetImplType(Type type)
at Microsoft.ClearScript.V8.V8Proxy.CreateImpl[T](Object[] args)
at Microsoft.ClearScript.V8.V8IsolateProxy.Create(String name, V8RuntimeConstraints constraints, Boolean enableDebugging, Int32 debugPort)
at Microsoft.ClearScript.V8.V8Runtime..ctor(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(V8Runtime runtime, String name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, Int32 debugPort)
at JavaScriptEngineSwitcher.V8.V8JsEngine..ctor(V8Settings settings)
--- End of inner exception stack trace ---
at JavaScriptEngineSwitcher.V8.V8JsEngine..ctor(V8Settings settings)
at JavaScriptEngineSwitcher.V8.V8JsEngineFactory.CreateEngine()
at React.JavaScriptEngineFactory.GetFactory(JsEngineSwitcher jsEngineSwitcher, Boolean allowMsie)
Error initialising React.VroomJsEngine+Factory: JavaScriptEngineSwitcher.Core.JsEngineLoadException: During loading of VroomJs JavaScript engine error has occurred.
See more details:
The type initializer for 'VroomJs.JsEngine' threw an exception. ---> System.TypeInitializationException: The type initializer for 'VroomJs.JsEngine' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'VroomJsNative': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at VroomJs.JsEngine.js_set_object_marshal_type(JsObjectMarshalType objectMarshalType)
at VroomJs.JsEngine..cctor()
--- End of inner exception stack trace ---
at VroomJs.JsEngine..ctor(Int32 maxYoungSpace, Int32 maxOldSpace)
at React.VroomJsEngine.<>c.<.cctor>b__23_0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at React.VroomJsEngine.get_Engine()
at React.VroomJsEngine..ctor()
--- End of inner exception stack trace ---
at React.VroomJsEngine..ctor()
at React.VroomJsEngine.Factory.CreateEngine()
at React.JavaScriptEngineFactory.GetFactory(JsEngineSwitcher jsEngineSwitcher, Boolean allowMsie)
This error does not block me from running and testing the code.
Like I said, all I did recently was to update the VS 2017 software...I tried to do a wild search in the project for 'v8-ia32' but nothing found.
To fix these errors I did the following:
Make sure you install the JavaScriptEngineSwitcher.V8, JavaScriptEngineSwitcher.V8.Native.win-x86 and JavaScriptEngineSwitcher.V8.Native.win-x64.
(I didn't install JavaScriptEngineSwitcher.V8.Native.win-x86)
According to https://reactjs.net/getting-started/aspnet.html
edit the ReactConfig.cs, basically, I just added this
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
Rebuild the project.

Implementing DI using Unity (design time configuration) in Web API 2

I am working on implementing DI using Unity in Web API Layer. Following is the error message I am getting while calling the Service -
Resolution of the dependency failed, type =
"API.Controllers.LeadController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type,
Business.ILeadManager, is an interface and cannot be constructed. Are
you missing a type mapping?
At the time of the exception, the container was:
Resolving API.Controllers.LeadController,(none)
Resolving parameter "leadManager" of constructor
API.Controllers.LeadController(Business.ILeadManager leadManager)
Resolving Business.ILeadManager,(none)
Any suggestions, what is wrong ?
Your unity configuration is missing a mapping for type Business.ILeadManager, so unity does not know which object instance it should create.
There should be an entry for your type like:
<register type="Business.ILeadManager" mapTo="MyLeadManagerImplementation" />

AngularJS with .NET MVC Bundling Minification Error

I have been developing a large AngularJS application inside of a .NET MVC Website. I've gone way to long without testing if it will sucesfully minifiy using the Bundle Optimiazation Features?
BundleTable.EnableOptimizations = True
And of Course, it fails. I've been playing with the Order I bundle my scripts, and ensuring I am using String Literals for my Controller Names (I wasn't, and that is a lot of re-factoring that I will have to do).
But I can not get my Core Scripts to Minifiy without the angular "Unknown Provider" error.
Here is the exact Error:
Uncaught Error: [$injector:modulerr] [http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=ppAccount&p1=Error…redScripts%3Fv%3DknV3wkCOg32ajaw4GwiRSrTXdo8Ue7MRIn65CPYa1b81%3A1%3A379851)]1
Here is my bundle config that is failing:
bundles.Add(new ScriptBundle("~/bundles/PilotPartnerRequiredScripts")
.Include(
"~/UI/js/jquery/jquery-2.1.3.js",
"~/UI/js/plugins/jquery-ui/jquery-ui.js",
"~/UI/js/bootstrap/bootstrap.js",
"~/UI/js/plugins/pace/pace.min.js",
"~/UI/js/plugins/slimscroll/jquery.slimscroll.js",
"~/UI/js/inspinia.js",
"~/UI/js/angular/angular.js",
"~/UI/js/ui-router/angular-ui-router.js",
"~/UI/js/bootstrap/ui-bootstrap-tpls-0.12.1.js",
"~/UI/js/angular/angular-resource.js",
"~/UI/js/angular/angular-sanitize.js",
"~/UI/js/angular/angular-route.js",
"~/UI/js/plugins/switchery/switchery.js",
"~/UI/js/plugins/angular-ui-switch/angular-ui-switch.js",
"~/UI/js/plugins/angularLocalStorage/angular-local-storage.js",
"~/UI/js/plugins/ngDialog/ngDialog.js",
"~/Scripts/ngTags/ng-tags-input.js",
"~/Scripts/uiSortable/sortable.js",
"~/Scripts/kendo/2014.3.1119/kendo.all.min.js",
"~/Scripts/xeditable/xeditable.js"
For the life of me, I can't figure out which dependency isn't being resolved. I feel that if I can narrow it down to a specific dependency I know I can solve the issue.
Is there any way to track down the specific Module that is causing the issue?
Any suggestions on how to make this work?
Thank you for your help.
You should always follow strict di while injecting dependency (Array notation)
Angualar Doc has mentioned that, Do follow strict DI while doing minification, otherwise it could break you app
Eg.(Code)
angular.module('myModule', [])
.factory('serviceId', ['depService', function(depService) {
// ...
}])
.directive('directiveName', ['depService', function(depService) {
// ...
}])
.filter('filterName', ['depService', function(depService) {
// ...
}]);
In above snippet I followed inline array notation of DI, it has been applied on various angular component just to demonstrate it. You should make sure that you follow it wherever you're injecting dependency.

F# compile code at runtime ends in missing assemblies

I have a question related to the code provided in an answer to this question.
The problem I have is that the three referenced assmeblies (System.dll, FSharp.Core.dll, FSharp.Powerpack.dll) that are passed to CompilerParameters are not found at runtime. The error I get is:
unknown-file(0,0) : error 0: error FS0218: Unable to read assembly
'c:\user s\utente\documents\visual studio
2010\Projects\TrashSolution\TrashSolution\bin\D ebug\FSharp.Core.dll'
How do I tell the compiler to search for these assemblies in the GAC, instead of the project's bin directory? If I open a namespace in the code provided as a string, how do I know which assemblies to add? Where can I get this information?
In the code from the answer you linked, there's a line towards the bottom:
let asm = Reflection.Assembly.LoadFrom(fileinfo.Value.FullName)
If you call Reflection.Load instead and pass it the fully-qualified assembly name, it'll try to load the assembly from the GAC (and a few other places, if the assembly isn't in the GAC).
let asm =
Assembly.Load "SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3"
If you don't know the fully-qualified assembly name you have to create an AssemblyName with the simple name of the assembly, then call the Reflection.Load overload which takes an AssemblyName instead of a string.
let asmName = AssemblyName "Your.Assembly.Name"
let asm = Assembly.Load asmName
As far as knowing which assemblies to load -- I don't think there's a simple way to determine that programmatically. The only two solutions I can think of right now:
If you have some knowledge about the code you're being given (as a string), you could parse it with the FSharpCodeProvider and look at which namespaces/modules are opened and which types are used. If you're looking to see if some particular namespace or type is used (i.e., that you would need to include an assembly reference for when compiling the code), you could create a Map (in your .fsx which is doing the compilation) of namespaces and/or type names to assembly names and use it to reference the appropriate assemblies.
You could "brute-force" search the GAC, by using the semi-documented Fusion API to enumerate all of the assemblies installed in the GAC, then using Reflection to examine each assembly and determine if it's one you require. This is likely to be extremely slow, so I'd avoid it at all costs. If you do decide to go this route, you must also use the Assembly.ReflectionOnlyLoad method to load the assemblies! This allows the assemblies to be unloaded after you finish examining them -- if you use normal Reflection the assemblies can't be unloaded and your program will likely crash with an OutOfMemoryException or similar.
EDIT: Turns out that loading the assembly by its simple name succeeds in fsi and not in normal F# code because fsi automatically installs a handler for the AppDomain.AssemblyResolve event. This event is triggered by the CLR when you try to load an assembly and it can't be resolved; the event provides a way for you to "manually" resolve the assembly and/or generate an assembly dynamically and return it.
If you look at the FileNotFoundException raised when you try to run the code in an F# project, you'll see something like this in the Fusion Log property of the exception:
=== Pre-bind state information ===
LOG: User = Jack-Laptop\Jack
LOG: DisplayName = System
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: System | Domain ID: 1
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/Jack/Documents/Visual Studio 2010/Projects/StackOverflow1/StackOverflow1/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : StackOverflow1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/Jack/Documents/Visual Studio 2010/Projects/StackOverflow1/StackOverflow1/bin/Debug/System.DLL.
LOG: Attempting download of new URL file:///C:/Users/Jack/Documents/Visual Studio 2010/Projects/StackOverflow1/StackOverflow1/bin/Debug/System/System.DLL.
LOG: Attempting download of new URL file:///C:/Users/Jack/Documents/Visual Studio 2010/Projects/StackOverflow1/StackOverflow1/bin/Debug/System.EXE.
LOG: Attempting download of new URL file:///C:/Users/Jack/Documents/Visual Studio 2010/Projects/StackOverflow1/StackOverflow1/bin/Debug/System/System.EXE.
Looking towards the bottom of that log, you'll see where the CLR searched for the assembly before it gave up.
Here's a simple handler to give you an idea of how to use the AppDomain.AssemblyResolve handler to manually resolve the assembly. (NOTE: The handler needs to be added before the code that attempts to load the assembly!)
System.AppDomain.CurrentDomain.add_AssemblyResolve (
System.ResolveEventHandler (fun _ args ->
let resolvedAssembly =
System.AppDomain.CurrentDomain.GetAssemblies ()
|> Array.tryFind (fun loadedAssembly ->
// If this assembly has the same name as the one we're looking for,
// assume it's correct and load it. NOTE : It may not be the _exact_
// assembly we're looking for -- then you'll need to adjust the critera below.
args.Name = loadedAssembly.FullName
|| args.Name = loadedAssembly.GetName().Name)
// Return null if the assembly couldn't be resolved.
defaultArg resolvedAssembly null))
If you add that code to a new F# console project, followed by the code which uses AssemblyName with Assembly.Load, you should be able to load the System assembly because it's referenced by default in an F# project and it'll be loaded when you run the project. If you try to resolve System.Drawing, it'll fail because our custom event handler can't find the assembly. Obviously, if you need some more complicated assembly-resolving logic, you should build that into the event handler in whatever way makes sense for your application.
Finally, here's a link to the MSDN whitepaper mentioned in the exception message: Best Practices for Assembly Loading. It's worth a read if you get stuck and can't figure out how to resolve the assemblies you need.

SignalR Requests Throwing "Hub could not be resolved."

I've been using SignalR since an early version and upgraded along the way however I have deployed my application to my Windows Server 2008 R2 production server and now the app crashes out with the " Hub could not be resolved." exception.
edit: StackTrace Added:
[InvalidOperationException: 'stockitems' Hub could not be resolved.]
Microsoft.AspNet.SignalR.Hubs.HubManagerExtensions.EnsureHub(IHubManager hubManager, String hubName, IPerformanceCounter[] counters) +426
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.Initialize(IDependencyResolver resolver, HostContext context) +716
Microsoft.AspNet.SignalR.Owin.CallHandler.Invoke(IDictionary`2 environment) +1075
Microsoft.AspNet.SignalR.Owin.Handlers.HubDispatcherHandler.Invoke(IDictionary`2 environment) +363
Microsoft.Owin.Host.SystemWeb.OwinCallContext.Execute() +68
Microsoft.Owin.Host.SystemWeb.OwinHttpHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object extraData) +414
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
Microsoft.Owin.Host.SystemWeb.CallContextAsyncResult.End(IAsyncResult result) +146
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
On my dev machine and local test server I am getting no issues.
The hub in question is really simple:
[HubName("StockItems")]
public class StockItemHub : Hub
{
}
Originally I thought it was an issue with the HubName so removed it but it still bombs out.
Originally I thought it was due to dependency injection so I then changed my Global.asax to look as follows:
var signalRResolver = new SignalRDependencyResolver();
GlobalHost.DependencyResolver = signalRResolver;
var configuration = new HubConfiguration { Resolver = signalRResolver };
RouteTable.Routes.MapHubs(configuration);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, config.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
edit: what is SignalRDependencyResolver?
SignalRDependencyResolver didn't exist until I tried to solve this issue. As I believe its a dependency injection issue I wrapped DefaultDependencyResolver overrode GetService and GetServices to first check my Ninject kernel for the type and if not fall back to the DefaultDependencyResolver
Any ideas?
The server is running IIS7, Windows Server 2008 with .Net 4.5
The application is an MVC 4 .Net 4.5
I had this same error due to my Hub class being internal, therefore SignalR couldn't find it within my assembly.
Setting the hub to public solved the issue.
I suffer from this problem just now, and I dig in a little deeper, and have just found out a possible solution.
My hub class are not in assembly of the web project, they are in some referenced assemblies. This is a very common scenario in a multi-layer application.
When starting up, signalR will try to find hub class by an IAssemblyLocator instance. When deployed within an IIS site, this IAssemblyLocator instance find through all referenced assemblies. But at this point of time, the application is just during the startup, which means many (referenced but not loaded yet) assemblies may had NOT been gathered by owin host environment.
So the lookup for hub classes fails.
So, just add your assembly into system.web/compilation/assemblies section of Web.Config:
<system.web>
<compilation targetFramework="4.5">
<assemblies>
<add assembly="HubAssembly, Version=1.0.0.0, Culture=neutral"/>
</assemblies>
</compilation>
</system.web>
Or if you like, you can also solved this problem by implementing a custom IAssemblyLocator class, register it into the dependency resolver as soon as app.MapSignalR is invoked.
using Microsoft.AspNet.SignalR.Hubs;
public class AssemblyLocator : IAssemblyLocator {
public IList<System.Reflection.Assembly> GetAssemblies()
{
// list your hubclass assemblies here
return new List<System.Reflection.Assembly>(new []{typeof(HubAssembly.HubClass).Assembly});
}
}
// add following code to OwinStartup class's Configuration method
app.MapSignalR();
GlobalHost.DependencyResolver.Register(typeof(Microsoft.AspNet.SignalR.Hubs.IAssemblyLocator), () => new AssemblyLocator());
This is now an old question but it reared its ugly head again this weekend. After spending alot of time investigating I have found that SignalR wasn't the only thing broken in the deployment, my WebAPI was also throwing could not find controller exceptions.
Turns out this is caused by the internals of SignalR and WebApi reflecting over all the types in the Sites assembly. A TypeLoadException was being thrown , in my case due to having a class derive RoleEntryPoint which is an Azure type but as the site was being deployed in a non Azure Environment things fell apart. Simply excluding this type from non Azure builds resolved the issue.
It would be nice if these TypeLoadExceptions were more visible but there it is.
Similar to #Jijie Chen, when I hit this issue I found that it was not able to load my assembly containing my hub. The fix for me was more straightforward though. In my case I had three projects. All the logic, including the hub was in a project of its own and I had two projects intended to host using owin. One was a console project that was working fine. I then adapted that to a windows service to host it. Well, somehow I managed to forget to include a reference to the project containing my hub. This still compiled fine because the host code relies on the signalr/owin mapping functions which load the hub(s) at runtime not compile time. So when I would start up the service and try to connect I got the hub no defined error described here because it couldn't find the assembly with my hub.

Resources