Registering dependencies within TinyIOC for use in NancyFX - nancy

I have another newbie question regarding registering additional dependencies within TinyIoc for use within NancyFX.
I am continuing to get the following exceptions when running the application...
Unable to resolve type: AdvancedSearchService.Interfaces.IResponseFactory
Exception Details: TinyIoC.TinyIoCResolutionException: Unable to resolve type: AdvancedSearchService.Interfaces.IResponseFactory
Source Error:
Line 25: var container = TinyIoCContainer.Current;
Line 26:
Line 27: _responseFactory = container.Resolve<IResponseFactory>();
Line 28:
Line 29:
I am currently registering my dependencies incorrectly, but I cannot seem to figure out the correct way. Below is my code within my custom bootstrapper. Also note that I am not currently calling the base.ConfigureRequestContainer method because I cannot seem to figure out how to get the current context to pass into it.
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<IRavenSessionManager>(new RavenSessionManager());
base.ConfigureApplicationContainer(container);
ConfigureRequestContainer(container);
}
protected void ConfigureRequestContainer(TinyIoCContainer applicationContainer)
{
var requestContainer = applicationContainer.GetChildContainer();
requestContainer.Register<ISearchRepository>(new SearchRepository(requestContainer.Resolve<IRavenSessionManager>().GetSession()));
requestContainer.Register<IResponseFactory>(new ResponseFactory(requestContainer.Resolve<ISearchRepository>()));
//base.ConfigureRequestContainer(requestContainer,[I NEED THE CONTEXT])
}
Any help would really be appreciated...apparently my ignorance has no limits :)

Ok, not 100% sure where to start.. you don't need the context because you're doing it wrong :-)
Firstly, why are you calling "configure request container" at all, and why are you creating a child container? You don't do that :-) There are two scopes, application scope, configured by overriding ConfigureApplicationContainer, and request scope, configured by overriding ConfigureRequestContainer, you don't call them yourself, you just override them depending on how you want to scope your objects.
Secondly, the default Nancy bootstrapper will "autoregister" everything it can in its default implementation of ConfigureApplicationContainer. By calling "base" after you've made a manual registration you are effectively copying over your original registration by autoregister. Either don't call base, or call it before you do your manual registrations. And, again, don't call ConfigureRequestContainer from your ConfigureApplicationContainer :-)
If you don't care about everything being application scoped (so singetons get the same instance for each request) then you don't need any of this, you can just rely on autoregister.
You're currently constructing your objects manually and putting them into the container, that seems a rather odd way to do it. Normally you'd just register the types and let the container handle instantiating as and when it needs to.
You're not overriding ConfigureRequestContainer, you are just creating a new method (with a different signature).
So, what you probably want is something like:
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
// Autoregister will actually do this for us, so we don't need this line,
// but I'll keep it here to demonstrate. By Default anything registered
// against an interface will be a singleton instance.
container.Register<IRavenSessionManager, RavenSessionManager>();
}
// Need to override this, not just make a new method
protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
// Get our session manager - this will "bubble up" to the parent container
// and get our application scope singleton
var session = container.Resolve<IRavenSessionManager>().GetSession();
// We can put this in context.items and it will be disposed when the request ends
// assuming it implements IDisposable.
context.Items["RavenSession"] = session;
// Just guessing what this type is called
container.Register<IRavenSession>(session);
container.Register<ISearchRepository, SearchRepository>();
container.Register<IResponseFactory, ResponseFactory>();
}

Related

Turn off Hystrix functionality

I am integrating Hystrix in an application. That application is already in production and we will be testing out hystrix integration work in sandbox before we will push it to production.
My question is that is there any way to turn on/off hystrix functionality using some configuration setting?
There is no single setting for this. You'll need to set multiple parameters to disable Hystrix.
See https://github.com/Netflix/Hystrix/wiki/Configuration for the configuration options:
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests=100000 # basically 'unlimited'
hystrix.command.default.execution.timeout.enabled=false
hystrix.command.default.circuitBreaker.enabled=false
hystrix.command.default.fallback.enabled=false
Please double check your version of Hystrix for the available parameters.
This is all what you need:
# Disable Circuit Breaker (Hystrix)
spring:
cloud:
circuit:
breaker:
enabled: false
hystrix:
command:
default:
circuitBreaker:
enabled: false
As ahus1 said, there is no single way to disable Hystrix entirely. To disable it in our application, we decided it was cleanest and safest to put a HystrixCommand in a wrapper class, and that wrapper class only exposed the parts of the HystrixCommand that we used (in our case, the execute() method). When constructing the wrapper class, we pass it a Callable that contains the code we want executed, and if Hystrix is disabled (according to our own config value), we simply call that Callable without ever creating a HystrixCommand. This avoids executing any Hystrix code whatsoever and makes it easier to say that Hystrix isn't affecting our application at all when it's disabled.
There are a couple of ways to achieve this-
Doing this for your every group including default. Although this will not disable hystrix(it will only keep the circuit closed all the time) but you will achieve the same result-
hystrix.command.{group-key}.circuitBreaker.forceClosed=false
If you are using java, you can create an around advice over #HystrixCommand annotation and bypass hystrix execution based upon a flag.
Java Code for #2-
#Pointcut("#annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
#Around("hystrixCommandAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
Method method = AopUtils.getMethodFromTarget(joinPoint);
if ((System.getProperty(enable.hystrix).equals("true")) {
result = joinPoint.proceed();
} else {
result = method.invoke(joinPoint.getTarget(), joinPoint.getArgs());
}
return result;
}
If your Project is spring Managed you can comment the bean definition of hystrixAspect in applicationContext.xml
Comment the following line
bean id="hystrixAspect"class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
This will remove Hystrix from your project.
I ran into this situation where I wanted to completely turnoff Hystrix using a single property (We use IBM uDeploy to manage dynamic properties). We are using javanica library built on top of Hystrix
Create a Configuration class which creates the HystrixCommandAspect
#Configuration
public class HystrixConfiguration{
#Bean(name = "hystrixCommandAspect")
#Conditional(HystrixEnableCondition.class)
public HystrixCommandAspect hystrixCommandAspect(){
return new HystrixCommandAspect()}
}
2. And the conditional class would be enabled based on a system property.
public class HystrixEnableCondition implements Condition{
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
return
"YES".equalsIgnoreCase(
context.getEnvironment().getProperty("circuitBreaker.enabled")) ||
"YES".equalsIgnoreCase(
System.getProperty("circuitBreaker.enabled"));
}
}
setting
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
is enough.
Additionally you may or should disable also the timeout threads
with hystrix.command.default.execution.timeout.enabled=false

How to use connectionDidFinishDownloading:destinationURL: and connectionDidFinishLoading:

I have implemented both the NSURLConnectionDownloadDelegate, NSURLConnectionDataDelegate delegate methods as given below.
The problem is that after connection:didReceiveResponse: , connectionDidFinishDownloading:destinationURL: is called but not connectionDidFinishLoading: Even connection:didReceiveData: is not called.
When I comment the NSURLConnectionDownloadDelegate methods, the other three are called without any issues.
I have a NSURLConnections which gets JSON from server. The NSURLConnectionDataDownloading delegate methods are used by newsstand to download issues.
How do i manage this?
Here are all the delegate methods than I am implementing
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes {
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL {
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
}
Here is my .h file
#interface FirstTopViewController : UIViewController <NSURLConnectionDownloadDelegate, NSURLConnectionDataDelegate, NSURLConnectionDelegate, UITableViewDataSource, UITableViewDelegate>
This is how I am connecting to server to get JSON
[[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
This is the code for downloading an issue if needed
NSURLRequest *urlReq = [NSURLRequest requestWithURL:myURL];
NKAssetDownload *asset = [currentIssue addAssetWithRequest:urlReq];
[asset downloadWithDelegate:self];
The problem is with the call to get JSON from server. Issue downloading works fine.
NSURLConnectionDataDelegate define delegate methods used for loading data to memory.
NSURLConnectionDownloadDelegate: delegate methods used to perform resource downloads directly to a disk file.
Then if you implemented connectionDidFinishDownloading:destinationURL: in your delegate. That will inform NSURLConnection you want to download the data to a disk file other than to memory as NSData. The
NSURLConnectionDataDelegate method won't get called. If you eliminate connectionDidFinishDownloading:destinationURL: from your delegate class implementation, connection:DidReceiveData: will get called instead.
For your case, implement two helper delegates for different usage.
When you want to get your JSON data in -connection:didReceiveData:, you need to set the delegate to an object which implements NSURLConnectionDataDelegate; when you want to download an issue to a file, the delegate needs to be an object that implements NSURLConnectionDownloadDelegate. A single class can't do both at once.
This is not explained very well in the NSURLConnection docs, but the comments in NSURLConnection.h make it a little more explicit:
An NSURLConnection may be used for loading of resource data
directly to memory, in which case an
NSURLConnectionDataDelegate should be supplied, or for
downloading of resource data directly to a file, in which case
an NSURLConnectionDownloadDelegate is used. The delegate is
retained by the NSURLConnection until a terminal condition is
encountered. These two delegates are logically subclasses of
the base protocol, NSURLConnectionDelegate.

Partial Trust JavaScript Object Access in XBAP via HostScript: SecurityException in Callbacks

I've encountered a problem with the XBAP Script Interop feature that was added in WPF 4. It involves a combination of the following:
Accessing members of a script object from .NET
Running .NET code in a callback invoked from JavaScript
Running in Partial trust
This seems to be a "pick any two" scenario... If I try and do all three of those things, I get a SecurityException.
For example, combining 1 and 3 is easy. I can put this into my hosting web page's script:
function ReturnSomething()
{
return { Foo: "Hello", Bar: 42 };
}
And then in, say, a button click handler in my WPF code behind, I can do this:
dynamic script = BrowserInteropHelper.HostScript;
if (script != null)
{
dynamic result = script.ReturnSomething();
string foo = result.Foo;
int bar = result.Bar;
// go on to do something useful with foo and bar...
}
That works fine, even in a partial trust deployment. (I'm using the default ClickOnce security settings offered by the WPF Browser Application template in Visual Studio 2010, which debugs the XBAP as though it were running in the Internet zone.) So far, so good.
I can also combine 2 and 3. To make my .NET method callable from JavaScript, sadly we can't just pass a delegate, we have to do this:
[ComVisible(true)]
public class CallbackClass
{
public string MyMethod(int arg)
{
return "Value: " + arg;
}
}
and then I can declare a JavaScript method that looks like this:
function CallMethod(obj)
{
var result = obj.MyMethod(42);
var myElement = document.getElementById("myElement");
myElement.innerText = "Result: " + result;
}
and now in, say, a WPF button click handler, I can do this:
script.CallMethod(new CallbackClass());
So my WPF code calls (via BrowserInteropHelper.HostScript) my JavaScript CallMethod function, which in turn calls my .NET code back - specifically, it calls the MyMethod method exposed by my CallbackClass. (Or I could mark the callback method as a default method with a [DispId(0)] attribute, which would let me simplify the JavaScript code - the script could treat the argument itself as a method. Either approach yields the same results.)
The MyMethod callback is successfully called. I can see in the debugger that the argument passed from JavaScript (42) is getting through correctly (having been properly coerced to an int). And when my method returns, the string that it returns ends up in my HTML UI thanks to the rest of the CallMethod function.
Great - so we can do 2 and 3.
But what about combining all three? I want to modify my callback class so that it can work with script objects just like the one returned by my first snippet, the ReturnSomething function. We know that it's perfectly possible to work with such objects because that first example succeded. So you'd think I could do this:
[ComVisible(true)]
public class CallbackClass
{
public string MyMethod(dynamic arg)
{
return "Foo: " + arg.Foo + ", Bar: " + arg.Bar;
}
}
and then modify my JavaScript to look like this:
function CallMethod(obj)
{
var result = obj.MyMethod({ Foo: "Hello", Bar: 42 });
var myElement = document.getElementById("myElement");
myElement.innerText = "Result: " + result;
}
and then call the method from my WPF button click handler as before:
script.CallMethod(new CallbackClass());
this successfully calls the JavaScript CallMethod function, which successfully calls back the MyMethod C# method, but when that method attempts to retrieve the arg.Foo property, I get a SecurityException with a message of RequestFailed. Here's the call stack:
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(PermissionSet permSet, StackCrawlMark& stackMark)
at System.Security.PermissionSet.Demand()
at System.Dynamic.ComBinder.TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject& result, Boolean delayInvocation)
at Microsoft.CSharp.RuntimeBinder.CSharpGetMemberBinder.FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
at System.Dynamic.DynamicMetaObject.BindGetMember(GetMemberBinder binder)
at System.Dynamic.GetMemberBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at XBapDemo.CallbackClass.MyMethod(Object arg)
That's the whole trace as reported by the exception. And above CallbackClass.MyMethod, Visual Studio is showing two lots of [Native to Managed Transition] and an [AppDomain Transition] - so that's the whole of the stack. (Apparently we're on a different thread now. This callback is happening on what the Threads panel describes as a Worker Thread - I can see that the Main Thread is still sat inside my WPF button click handler, waiting for the call to the JavaScript CallMethod function to return.)
Apparently the problem is that the DLR has ended up wrapping the JavaScript object in the ComBinder which demands full trust. But in the earlier case where I called a JavaScript method via HostScript and it returned me an object, the HostScript wrapped it in a System.Windows.Interop.DynamicScriptObject for me.
The DynamicScriptObject class is specific to WPFs XBAP script interop - it's not part of the usual DLR types, and it's defined in PresentationFramework.dll. As far as I can tell, one of the jobs it does is to make it possible to use C#'s dynamic keyword to access JavaScript properties without needing full trust, even though those properties are being accessed through COM interop (which usually requires full trust) under the covers.
As far as I can tell, the problem is that you only get these DynamicScriptObject wrappers for objects that are returned from other DynamicScriptObject instances (such as HostScript). With callbacks, that wrapping doesn't seem to occur. In my callback, I'm getting the sort of dynamic wrapper C# would normally give me in plain old COM interop scenarios, at which point, it demands that I have full trust.
Running it with full trust works fine - that would be the "1 and 2" combination from the list above. But I don't want to have full trust. (I want 1, 2, and 3.) And outside of callback situations, I can access JavaScript object members just fine. It seems inconsistent that I can access a JavaScript object just fine most of the time, but accessing an identical object in a callback is forbidden.
Is there a way around this? Or am I doomed to run my code in full trust if I want to do anything interesting in a callback?
I haven't done XBAP in a while, but I am curious if it is the dynamic type that could be causing the issue. Try changing the dynamic parameter to type object and see if it will work.
[ComVisible(true)]
public class CallbackClass
{
public string MyMethod(object arg)
{
return "Arg is: " + arg.ToString();
}
}

AppDomain.GetData method not accessible?

I am developing a Silverlight 3 application and I would like to delegate all unexpected error handling in a single instance of a class I have named ErrorHandler. This class has one method named HandleApplicationException, plus a couple of other methods to handle more specialized errors.
In my application I am using Unity for dependency injection, but since I want the error handling object to be available even when the Unity container is not yet set up, I register the object as AppDomain global data in the App class constructor, this way:
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());
InitializeComponent();
}
And in case of unhandled exception, I retrieve the error handler object and use it this way:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
e.Handled = true;
var errorHandler = AppDomain.CurrentDomain.GetData("ErrorHandler") as ErrorHandler;
Debug.Assert(errorHandler != null, "No ErrorHandler registered.");
errorHandler.HandleApplicationException(e.ExceptionObject);
}
The problem is that the AppDomain.GetData method in the Application_UnhandledException method is throwing a MethodAccessException. I don't understand why, as I am just invoking a public method on the AppDomain class. I have used a similar approach in other applications and it worked fine (anyway these were not Silverlight applications).
So, what's going on? Am I doing something wrong?
Ok, I got it. From MSDN documentation:
This member has a
SecurityCriticalAttribute attribute,
which restricts it to internal use by
the .NET Framework for Silverlight
class library. Application code that
uses this member throws a
MethodAccessException.
I have resorted to storing the error handler in a public property in the App class, then I access it using ((App)Application.Current).ErrorHandler. I don't like doing things this way but I suppose it is ok in this special case.
Why can't you just use a static instance of ErrorHandler? I.e. have something like ErrorHandler.Current?
It looks like you're trying to manually construct a poor man's IoC framework to be honest.
Consider doing some research on Unity/Ninject and see for yourself why strongly-typed decoupling is better.

Silverlight serialisation/deserialisation problem

I'm looking for a way to persist Silverlight objects to a user's PC, then re-hydrate them so the user can finish editing them.
Serialising with DataContractSerializer and persisting to IsolatedStorageFile works fine. However, deserialising causes a problem. Here's the code that causes the failure:
private string _FirstNames = string.Empty;
public string FirstNames
{
get { return _FirstNames; }
set
{
new PersonNameValidator().Validate(value); //<-- BOOM 8(
Set(ref _FirstNames, value, () => this.FirstNames);
}
}
The deserialiser calls the property setter, which in turn throws an exception and aborts the deserialisation.
I've tried explicitly applying DataContract/DataMember/IgnoreDataMember attributes, but then it doesn't play nicely with private fields:
System.Security.SecurityException
occurred Message="The data contract
type
'Trident.Model.Journey.JourneyApplication'
cannot be serialized because the
member '_TravellerSavingsAmount' is
not public. Making the member public
will fix this error. Alternatively,
you can make it internal, and use the
InternalsVisibleToAttribute attribute
on your assembly in order to enable
serialization of internal members -
see documentation for more details. Be
aware that doing so has certain
security implications."
How can I bypass the property setters during deserialisation?
I'd like to keep my classes focused on the domain, and not too polluted with infrastructure concerns.
A couple of ideas:
serialize a property that is used only for serialization thereby bypassing any validation
serialize a parent class and use a derived class for validation

Resources