Adding caching support to service step by step - servicestack

I want to use memory caching in my service but not able to configure it. I already registered it in global.asax as per instructions.
Here is how my service looks:
public class CustomerSerivce: Service
{
public CustomerResponse Any(Customer customer)
{
//code to connect to db here - this code is called regardless of cache entry
return customer;
}
}
I know there is this.RequestContext.ToOptimized or something is there but some how it is not working for me.
Thanks in advance.

Do you have declare:
using ServiceStack.ServiceHost;
for extension methods of
base.RequestContext.ToOptimizedResultUsingCache(...)
?

the step by step is here. You can also look at here for the missing link with http 304 Not Modified handling.

Related

MVC5, OWIN, and Ninject - GetOwinContext Issues

I have an MVC5 project that is doing OwinStartup, and I'm using Ninject.MVC5, Ninject.Web.Common.OwinHost, etc.
I have NinjectWebCommon bootstrapping DI and things were working just fine. Until I started playing with the identity code.
I need to issue a password reset token, which requires a DataProtectionProvider. No problem, the ApplicationUserManager wires that up in the Create method, which is bound to the OwinContext during startup in Startup.Auth.cs:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
...
}
In my NinjectWebCommon I have the following registrations:
kernel.Bind<IDataContext>()
.ToMethod(ctx => HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>())
.InRequestScope();
kernel.Bind<IApplicationUserManager>()
.ToMethod(ctx => HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>())
.InRequestScope();
The problem I'm having is that the token isn't being issued. Why isn't that what my question is about? Well, if I get an instance of the ApplicationUserManager using the Create myself and use that, things work flawlessly.
Next on my plate a reported user creation bug. Hyphens aren't working in usernames. In that same ApplicationUserManager.Create method, is the UserValidator code that's overriding the default AllowOnlyAlphanumericUserNames value.
Again, if I use a self created dependency, it works as expected. This seems to indicate Ninject's injected dependency isn't using the ApplicationUserManager.Create'd version.
I'm guessing this has to do with the call to: HttpContext.Current.GetOwinContext??
Is there something I need to do in order to inject something that relies on the owin context or something else I need to do while registering my resolver?
I've seen other questions here showing UseNinjectMiddleware and UseNinjectWebApi. I tried that approach, but didn't have any luck, nothing was being injected in...
Any assistance is greatly appreciated!

Can I proxy a ServiceStack Service?

I'm wondering if it's possible to have ServiceStack use an AOP-proxied service, instead of the main implementation. I would like to avoid having the class that inherits from ServiceStack.ServiceInterface.Service simply be a wrapper, if possible. It looks to me like it will need to be, but I thought it wouldn't hurt to ask, to be sure.
I am looking for a way to achieve this, to proxy the services of a ServiceStack app.
Till now what I have learned is that: The only way we can generate a proxy to a service like
[Route("/reqstars")]
public class AllReqstars : IReturn<List<Reqstar>> { }
public class ReqstarsService : Service
{
public virtual List<Reqstar> Any(AllReqstars request)
{
return Db.Select<Reqstar>();
}
}
Is using a Custom Service Generation Strategy. And generating proxies of IService interface with class target and marking all the method of the service as virtual.
I have not tested this yet and even I do not know (and this is what I am researching for now) if ServiceStack can handle a service generator delegate so I can use Castle's DynamicProxy.
Good luck!

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.

NServiceBus with Azure and XML serializer

I am trying to switch a hosted worker process in Azure to use xml serializer instead of the default json serializer. I have done this by implementing IWantCustomInitialization like this:
public class BusInitialization : IWantCustomInitialization
{
public void Init()
{
Configure.Instance.XmlSerializer();
}
}
However when I start the cloud solution, I get the following error:
Exception when starting endpoint, error has been logged. Reason: Type NServiceBus.Unicast.Transport.CompletionMessage was not registered in the serializer. Check that it appears in the list of configured assemblies/types to scan.
When I use no custom initialization and it goes to JsonSerializer, everything is fine. Does anyone have a suggestion where shall I look to? I use NSB 3.2.8.
thought this was fixed but I just checked, looks like in 3.2.8 the jsonserializer cannot yet be overriden easily. This has already been fixed on the dev branch but didn't get into release yet, it will be in the next one than.
If you can't wait for next release then you can work around this by replacing the AsA_Worker with your own role and role handler similar to this:
3.2.8 version https://github.com/NServiceBus/NServiceBus/blob/master/src/azure/Hosting/NServiceBus.Hosting.Azure/Roles/Handlers/WorkerRoleHandler.cs
develop version https://github.com/NServiceBus/NServiceBus/blob/develop/src/azure/Hosting/NServiceBus.Hosting.Azure/Roles/Handlers/WorkerRoleHandler.cs
Kind regards,
Yves

How to use ASP.NET Session State in an HttpHandler?

I have an HttpHandler that is run on a client page (cross domain, not on our IIS server, etc) and when they click on our embedded link it fires off the Handler on our server. So far everything is working normally.
I am now trying to use the System.Web.HttpContext.Session object but it is null. I am thinking it is null because we don't have a session until our HttpHandler is invoked? And multiple calls to the handler will create a new session per call? If this is the case did MS just disable the Session object when calling into a HttpHandler? Can anyone confirm this?
If this is the case, what do you do to maintain state between calls? Some sort of SQL based data object? A file?
TIA
Have your HttpHandler implement the IRequiresSessionState interface. It will enable session state use.
IRequiresSessionState can be found in the System.Web.SessionState namespace.
I think you have to implement the empty interface IReadOnlySessionState, so the context will be loaded.
edit to add:
According to Michael Morton's answer, you can also implement IRequiresSessionState, which will give you write access also to the Session object
using System;
using System.Web;
using System.Web.SessionState;
public class DownloadHandler : IHttpHandler, IReadOnlySessionState
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
context.Response.Write(context.Session["kmx"]);
}
}
try using the current context...
System.Web.HttpContext.Current.Session

Resources