How to force an IIS hosted WCF or ASMX [webservice] to use session object readonly? - wcf

While making my first ajax attempts, I decided also, to go to use IIS hosted WCF now. The strange thing is, that the WCF cannot process several requests parallel for the same user/session, if sessionmode is enabled! If sessionmode is disabled on asp.net, the requests are processed parallel. The broser/client may execute several different requests, where some of them are long running. This blocks all further requets and make my ajax app unusable.
This applies to asmx [webservices] also. I had a big hope, to compile the webservice methods using "IReadOnlySessionState" interface, but this has - in oppsite to webpages - no influence. But I need access [most times readonly] to the asp.net session!
Does someone knows any solution to this problems.
Anyway, thanks a lot!
br--mabra

In .NET 4, you can do this in Application_BeginRequest
if (Context.Request.Path.EndsWith("xxx.svc"))
Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);

I found this:
http://blogs.msdn.com/silverlightws/archive/2009/09/30/having-a-pollingduplex-service-and-any-other-wcf-service-in-the-same-website-causes-silverlight-calls-to-be-slow.aspx
Which states,
"All WCF services require read/write session state access if you enable ASP.Net sessions, which causes the replies to be queued sequentially. Ideally user should be able configure the WCF handler to be read only, which would allow polling duplex services to work with sessions. Unfortunately this is unsupported at this point."
...the only thing I can think of is if there's some way to manually force early release of the lock. I'm looking into that now.

You can provide a custom session state provider
See: http://koolsand.blogspot.com/2010/02/why-iis-hosted-wcf-services-does-not.html
whenever a request contains svc in the
path it intimates default session
state provider to use readonly lock
and not read-write lock. So using
readonly lock will allow the next wcf
call to be executed concurrently.

Related

Service fabric and WCF

We are planning to redesign our services to micro services using service fabric, I have some questions that I hope you can help me with, here we go:
Communication Stack
All our services are on WCF using net.tcp so in theory we can reuse the WCF Communication stack but I'm not sure that's the best way, what are the differences between the default communication stack and the WCF one?
Extensibility
We have a lot of implementation using the extensibility points of WCF, if we choose the WCF communication stack can we still use this? We are basically using IServiceBehavior,IOperationInvoker, OperationContext and ServiceSecurityContext for this:
1. Security ServiceSecurityContext/OperationContext to get the IP and if the call is in the intranet the domain account who is making the call, I checked in StatelessServiceContext but could not find any property where i could get this info.
2. Parameters and time IOperationInvoker to log the parameters of the method and how much it took to finish the operation, reading this it appears that if implement the Start/Stop methods the time duration is done automatically, what I'm not sure is if this will work in the context of an attribute and with IErrorHandler when an error happens.
3. Notifications IErrorHandler to log the exception and then send an email to the developer team, we are currently doing this using an SMTP server, is there a better way to send notifications in azure?.
Thanks for your time
Answering this:
Communication Stack
Never did a comparison in performance between the default listener and WcfCommunicationListener but we opted for WCF to reuse all our components and as a first version to understand how service fabric works.
Extensibility
Security All the code worked the same, we needed to make some changes to the way the context works, but all the info needed was there (plus some data on the node it was running)
Parameters and time We used Azure Service Profiler with our own implementation of Microsoft.Diagnostics.Tracing.EventSource capturing the data using IOperationInvoker, awesome
Notifications IErrorHandler continued to work but we used sendgrid for the emails.

Session variable equivalent in OWIN self-host

I have a sample web API hosted in an OWIN process (self hosted, not in IIS). I get a JWT token in my controller and I want to be able to retreive it in another part of the application, a class that implements NserviceBus IMutateOutgoingTransportMessages. In my other web application POC (hosted in IIS), I used a simple session variable and it works just fine. But I'd like to know what would be the best way to do it in my new OWIN self hosted environment ? Static property in static class ?
This question is really broad and difficult to answer without detailed knowledge of your specific needs. Here's my interpretation of your issue:
You're already signing each request, perhaps storing the token in the browser sessionStorage (or even localStorage), but this does not suffice
You need to retrieve the token outside of or not in relation to any request cycle (if not, this is probably where you should be looking for answers)
Your application does not need to be stateless
Just one static property for one token in a static class would of course start breaking as soon as more than one request hits the application at the same time. Implementing a class that maintains a list of tokens may be a solution, although I can't tell what key you should use to identify each token. Interface details would vary depending on things like if you need to retrieve the token more than once.
Thread safety issues would apply to all handling and implementation of such a class. Using Immutable Collections and functional programming practices as an inspiration may help.
If lingering tokens poses a problem (and they probably would from a security perspective, if nothing else), you need to figure out how to make sure that tokens do not outstay their welcome, even if the cycle is for some reason not completed.
Seeing how you used Session as a solution in your POC, I'm assuming you want some similar behavior, and that one user should not be allowed to carry two tokens at the same time. You could store the tokens i a database, or even in the local file system, making maintenance and validity a separate issue all together.
There are implementations of cache-like functionality already available for OWIN self-hosted applications, and maybe one of those would serve as a shortcut to implementing everything yourself.
If this token business in fact is the only reason for introducing state in your application, then the best solution IMHO would be to rethink your architecture so that the application can remain stateless.
I'm facing a similar dilemma on a server i'm currently developing for a customer. My problem is that the server must make calls (and retain a live connection) with a legacy, multithreaded DLL, (aka the SDK).
I struggled to get this working on IIS with a regular Web API project. Failed badly since IIS recycles threads when it determines that a thread is going rogue... witch is what the SDK thread looks like in that perspective. Also, the SDK must be able to callback on the caller (client - single page app) and for this I'm using SignalR.
I then tried a multi-part system (single page + web api on IIS + WCF service for the SDK integration). But it is a real nightmare to manage because of the 2 way async communication that must occur between all apps. Again: failure.
So I reverted to a single self hosted OWIN + WebAPI service in a console app (for now). My problem is that some of the calls are lengthy and are processed in a worker thread. I managed to pass the SignalR client id in each ajax calls via headers. I can extract the id when in web api controller. But when the task goes async, I need to get the id (via an Unity injected service) from the class that manages the async task. This is where my problem is similar to yours. In IIS hosted apps, we have HttpContext. It is contextualized on each client calls, and follows any thread changes in the pipeline... But not in self hosted OWIN WCF apps...
I'm looking into Thread Local Storage, CallContext... and other means of keeping track of the original caller info during the lifecycle of the async call. I have read about OWIN pipeline, I can capture the info in a OWIN middleware... but how to safely keep that info for use in injected services? I'm still searching for an answer...
I was wondering if you have found a solution to this rather interesting problem ?
I prefer adding to your thread rather than start another parallel thread / SO question.

Using session in wcf

If I set my servis instance as Per Session or Single can I send some data between services instance in session? It should be done in Asp.net session - HttpContext.Current.Session
or wcf have own session ?
As I said - WCF is not ASP.NET and its session handling is vastly different. While ASP.NET sessions and WCF sessions are called the same - they are vastly different in their purpose and usefulness.
Read the MSDN page Using Sessions in WCF for more details.
One sentence reads: There is no general data store associated with a WCF session. - so the answer is no - sessions in WCF are not meant for data storage.
WCF sessions are merely to "tie together" several messages into a conversation. By default, with the "per-call" model, each WCF service request would get its own, freshly instantiated service class instance to handle the request, and that service class instance will be freed after returning the answer. Using sessions avoids this - the service class instance handling the first call of a session will stay alive on the server side (and thus also taking up memory on the server) and will handle all subsequent requests within the same session.
WCF and web services in general should however preferably be stateless, so sessions are a bit of an oddball architecture in a proper SOA environment - and that's most likely why sessions in WCF are also not nearly as useful as ASP.NET sessions are for web apps.
To remain stateless and support the per-call method (the preferred best practice), if you need to store data between calls, store it in a persistent store (e.g. a database) and fetch it back from there when needed later on.
If you're hosting services in IIS, you can enable ASP.Net Compatability mode. This will allow you to use ASP.Net session state, just like you would in a web application.

WCF service to proxy an email service. Stateful?

I have to create a WCF web service that proxies an IMAP service (so that it can be consumed by a SL application).
The IMAP service requires that first the Login(credentials) method is called, to authenticate with the IMAP server. After the Login method is called the connection is kept open and other operations can be performed.
Does anybody know how can achieve this with a WCF service?
One solution I want to avoid is the proxy to login for every operation it has to perform (as the login operation usually takes 1-2 seconds). And I would have to pass the credentials every time: GetMail(credentials), GetFolders(credentials), etc.
I know it is highly recommended that WCF services not to be stateful, but it seems I need to keep the state of IMAP connection for every client. How can I do this?
Thanks!
This is one of those rather rare cases where I think using WCF sessions makes sense:
your first call that calls the IMAP Login method starts a WCF session
any subsequent call will be using the same session
some final call (e.g. something like a Done or Logout) will terminate that session
With a session in WCF, your service class on the server stays in memory for the duration of the entire session, i.e. it's not constantly re-created, and thus you can keep the IMAP connection "live" inside your service class.
Resources:
Sessions, Instancing, and Concurrency (MSDN)
Using Sessions (MSDN)
WCF Sessions - a brief introduction
WCF Sessions
Per-Session Instance Management in WCF
Be aware: WCF sessions are NOT ASP.NET sessions - those are two totally different things! Just to be clear from the get-go.
Also: only a handful of WCF bindings support sessions - netTcpBinding, wsHttpBinding and netNamedPipeBinding (as far as I know)

Logging EntLib LogEntry objects via WCF Service in multi-system solution

We have a multi-system solution: several web sites and a separate App-Tier implemented / exposed as WCF services. The web sites all use EntLibs to log stuff - but they need to log to a central DB which is only accessible by the App-Tier.
To get around this we're looking at implementing a WCF service that can have LogEntires sent to it (via a Custom Trace Listener that sends the Log Entries to it).
The decision to use a WCF service is that it's in keeping with the rest of the architecture - and we don't have a lot of time to go doing much else.
I also looked at this and started wondering if we're on the wrong track altogether (from a performance perspective).
So, my question is:
Is this such a bad idea that I should just stop?
If it's viable, what are the traps I need to look out for?
The answer in the question you linked to covers it quite well, if you read between the lines:
Call the WCF logging service with "Is One way" = true, so that your client program does not wait for the logging to complete.
Set the WCF settings such that the client does not throttle the number of requests