Is the default behaviour for NSManagedObjectContext save() method a blocking method? - core-data

To be very specific: If I get the managed object context from the app delegate and do not set any parameters on it, what happens when running inserts, updates followed by save()?
Does the app block on save() until done?

Yes, the save method blocks. It's not even a default-- that's how it is, always. Does't matter if the context came from the app delegate or somewhere else, save is a synchronous method.

This what it came down to:
Normally, when I create an object, I only set the main key (properties that don't change through the lifecycle of the object) on creation. I then use an update method to complete the creation. In this particular case, I changed one property on the server from 'creational' property to 'updateable' property, but I missed it in the app. So the app was deleting the objects only to have the server create them again a bit later...

Related

ServiceStack.SSE: How do I get an instance o IServerEvents?

I have the SSE plugin running in ServiceStack, and it works to access for example /event-stream etc.
Now, let's assume there are subscribers, but otherwise no action from outside. Suddenly, the server decides "I need to push this information to channel X". How do I do that? I seem to need in instance of IServerEvents, but I don't know where I get that instance.
I see it's injected into different Service implementations, but in this case, there is no service called, so I need to get this IServerEvents elsewhere. Let's assume an event is trigged, that fires a method inside the AppSelfHostBase implementation, so OnObjectChange(...) is triggered.
How do I then push some data out to a channel/subscriber in the OnObjectChanged method? Where do I get the IServerEvents?
It seems that this code works almost anywhere:
IServerEvents test = TryResolve<IServerEvents>();
The IServerEvents instance will be returned and seems to function.

Invoke onExit() manually in SAPUI5

Is there is a way to invoke onExit() Life cycle hook manually?
If you´re talking about the onExit function of your controller you can! However, you should consider the View Lifecycle. According to this Lifecycle the framework will automatically call the onExit hook for you:
onExit(): Called when the view is destroyed; used to free resources and finalize activities
Source: SAPUI5 Documentation
Since it is a function which belongs to your controller you are able to call it manually by this.onExit() (in your controller).
However, this shouldn´t be necessary. To act according to the lifecycle you can call .destroy() of your view which destroys the view, the controller and all associated children.
destroy(): Cleans up the resources associated with this element and all its children.
Source: SAPUI5 Documentation

Using HttpContext.Current in WebApi is dangerous because of async

My question is a bit related to this: WebApi equivalent for HttpContext.Items with Dependency Injection.
We want to inject a class using HttpContext.Current in WebApi area using Ninject.
My concern is, this could be very dangerous, as in WebApi (everything?) is async.
Please correct me if I am wrong in these points, this is what I investigated so far:
HttpContext.Current gets the current context by Thread (I looked into the implementation directly).
Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread.
WebApi uses IHttpController with method Task<HttpResponseMessage> ExecuteAsync => every request is async => you cannot use HttpContext.Current inside of action method. It could even happen, more Request are executed on the same thread by coicidence.
For creating controllers with injected stuff into constructors IHttpControllerActivator is used with sync method IHttpController Create. This is, where ninject creates Controller with all its dependencies.
If I am correct in all of these 4 points, using of HttpContext.Current inside of an action method or any layer below is very dangerous and can have unexpected results. I saw on StackOverflow lot of accepted answers suggesting exactly this. In my opinion this can work for a while, but will fail under load.
But when using DI to create a Controller and its dependencies, it is Ok, because this runs on one separated thread. I could get a value from the HttpContext in the constructor and it would be safe?. I wonder if each Controller is created on single thread for every request, as this could cause problem under heavy loads, where all threads from IIS could be consumed.
Just to explain why I want to inject HttpContext stuff:
one solution would be to get the request in controller action method and pass the needed value all the layers as param until its used somewhere deep in the code.
our wanted solution: all the layers between are not affected by this, and we can use the injected request somewhere deep in code (e.g. in some ConfigurationProvider which is dependent on URL)
Please give me your opinion if I am totally wrong or my suggestions are correct, as this theme seems to be very complicated.
HttpContext.Current gets the current context by Thread (I looked into the implementation directly).
It would be more correct to say that HttpContext is applied to a thread; or a thread "enters" the HttpContext.
Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread.
Not at all; the default behavior of async/await will resume on an arbitrary thread, but that thread will enter the request context before resuming your async method.
The key to this is the SynchronizationContext. I have an MSDN article on the subject if you're not familiar with it. A SynchronizationContext defines a "context" for a platform, with the common ones being UI contexts (WPF, WinPhone, WinForms, etc), the thread pool context, and the ASP.NET request context.
The ASP.NET request context manages HttpContext.Current as well as a few other things such as culture and security. The UI contexts are all tightly associated with a single thread (the UI thread), but the ASP.NET request context is not tied to a specific thread. It will, however, only allow one thread in the request context at a time.
The other part of the solution is how async and await work. I have an async intro on my blog that describes their behavior. In summary, await by default will capture the current context (which is SynchronizationContext.Current unless it is null), and use that context to resume the async method. So, await is automatically capturing the ASP.NET SynchronizationContext and will resume the async method within that request context (thus preserving culture, security, and HttpContext.Current).
If you await ConfigureAwait(false), then you're explicitly telling await to not capture the context.
Note that ASP.NET did have to change its SynchronizationContext to work cleanly with async/await. You have to ensure that the application is compiled against .NET 4.5 and also explicitly targets 4.5 in its web.config; this is the default for new ASP.NET 4.5 projects but must be explicitly set if you upgraded an existing project from ASP.NET 4.0 or earlier.
You can ensure these settings are correct by executing your application against .NET 4.5 and observing SynchronizationContext.Current. If it is AspNetSynchronizationContext, then you're good; if it's LegacyAspNetSynchronizationContext, then the settings are wrong.
As long as the settings are correct (and you are using the ASP.NET 4.5 AspNetSynchronizationContext), then you can safely use HttpContext.Current after an await without worrying about it.
I am using a web api, which is using async/await methodology.
also using
1) HttpContext.Current.Server.MapPath
2) System.Web.HttpContext.Current.Request.ServerVariables
This was working fine for a good amount of time which broke suddenly for no code change.
Spending a lot of time by reverting back to previous old versions, found the missing key causes the issue.
< httpRuntime targetFramework="4.5.2" /> under system.web
I am not an expert technically. But I suggest to add the key to your web config and give it a GO.
I found very good article describing exactly this problem: http://byterot.blogspot.cz/2012/04/aspnet-web-api-series-part-3-async-deep.html?m=1
author investigated deeply, how the ExecuteAsync method is called in the WebApi framework and came to this conclusion:
ASP.NET Web API actions (and all the pipeline methods) will be called asynchronously only if you return a Task or Task<T>. This might sound obvious but none of the pipeline methods with Async suffix will run in their own threads. Using blanket Async could be a misnomer. [UPDATE: ASP.NET team indeed have confirmed that the Async is used to denote methods that return Task and can run asynchronously but do not have to]
What I understood from the article is, that the Action methods are called synchronously, but it is the caller decision.
I created a small test app for this purpose, something like this:
public class ValuesController : ApiController
{
public object Get(string clientId, string specialValue)
{
HttpRequest staticContext = HttpContext.Current.Request;
string staticUrl = staticContext.Url.ToString();
HttpRequestMessage dynamicContext = Request;
string dynamicUrl = dynamicContext.RequestUri.ToString();
return new {one = staticUrl, two = dynamicUrl};
}
}
and one Async version returning async Task<object>
I tried to do a little DOS attack on it with jquery and could not determine any issue until I used await Task.Delay(1).ConfigureAwait(false);, which is obvious it would fail.
What I took from the article is, that the problem is very complicated and Thread switch can happen when using async action method, so it is definetly NOT a good idea to use HttpContext.Current anywhere in the code called from the action methods. But as the controller is created synchronously, using HttpContext.Current in the constructor and as well in dependency injection is OK.
When somebody has another explanation to this problem please correct me as this problem is very complicated an I am still not 100% convinced.
diclaimer:
I ignore for now the problem of self-hosted Web-Api withoud IIS, where HttpContext.Current would not work probably anyway. We now rely on IIS.

Global request/response interceptor

What would be the easiest way to setup a request/response interceptor in ServiceStack that would execute for a particular service?
A request filter (IHasRequestFilter) works fine but a response filter (IHasResponseFilter) is not triggered if the service returns non 2xx status code. I need to retrieve the status code returned by the method as well as the response DTO (if any).
A custom ServiceRunner and overriding the OnBeforeExecute and OnAfterExecute methods seems to work fine but I find it pretty intrusive as the service runner need to be replaced for the entire application and I couldn't find a way clean way to isolate per functionality the tasks that need to be executed in those methods.
Is there some extension point in ServiceStack that I am missing that would allow me to execute some code before each service method and after each service method? A plugin would be ideal but how can I subscribe to some fictitious BeforeExecute and AfterExecute methods that would allow me to run some custom code?
UPDATE:
Just after posting the question I found out that global response filters are executed no matter what status code is returned by the service which is exactly what I needed. So one last question: Is it possible to retrieve the service type that will handle the request in a request filter? I need to check whether this service is decorated by some custom marker attribute.
I have found out a solution to my question about how to retrieve the service type in a custom request/response filter:
appHost.RequestFilters.Add((req, res, requestDto) =>
{
var metadata = EndpointHost.Metadata;
Type serviceType = metadata.GetServiceTypeByRequest(requestDto.GetType());
...
}
A custom ServiceRunner and overriding the OnBeforeExecute and OnAfterExecute methods seems to work fine but I find it pretty intrusive as the service runner need to be replaced for the entire application
Quick note, you can opt-in and choose only what requests should use a custom service runner, e.g:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(
ActionContext actionContext)
{
return useCustomRunner(actionContext.RequestType)
? new MyServiceRunner<TRequest>(this, actionContext)
: base.CreateServiceRunner<TRequest>(actionContext);
}
IHttpRequest has OperationName. I think thats what you are after.

How would you inject and handle a database object from an object pool into a resource?

i've been thinking about implementing a object pool for jcouchdb objects for jersey. Now i am asking myself what would be the best way to deliver a jcouchdb instance to the resource endpoints.
I expect the pool to have a method for requesting an jcouchdb object and for releasing it so that it can be reused.
My first idea was to implement a InjectableProvider as a singleton an use a annotation in the resource endpoint to "grab" it. The InjectableProvider then returns an jcouchdb object from the object pool and marks it as busy. How can i release the jcouchdb object after I've used it? And i would request a jcouchdb object for every resource endpoint instance even if i never need it?! (don't know when the annotated objects get instantiated)
Another idea i was thinking about was to attach the object pool to the servlet context (with set attribute).
Any other ideas?
I am basically a bit confused when i comes to shared resources and jersey. Hopefully someone can clear things up for me.
Thanks
If you do exactly as you just said, your code would look like this:
public class MyResource{
#GET
#RequestMapping("/bleh")
public Response getValue(#Context JCouchDBObject object){
//manipulate object
}
}
#Provider
public class MyProvider extends InjectableProvider<Context, Parameter>{
public Injectable<JCouchDBObject> getInjectable(ComponentContext context, Context hp, Parameter param) {
//GetObject and return
}
}
I've never worked with JCouchDB, but unless each object is linked to the DB connection pool - there is nothing to manually release - all of this will be handled for you.
But: This is not what the InjectableProvider was designed for. Typically, the InjectableProvider will be used to create and resolve some sort of request object (such as the JCouchDBObject's ID, etc). Then you should use a service to collect the JCouchDBObject and handling any manually release there.

Resources