WCF binding -wsHttpBinding uses a session? - iis

In a previous thread one of the respondents said that using wsHttpBinding used a session. Since I'm working in a clustered IIS environment, should I disable this? As far as I know, sessions don't work in a cluster.
If I need to disable this, how do I go about it?

That probably was me :-) By default, your service and the binding used will determine if a session comes into play or not.
If you don't do anything, and use wsHttpBinding, you'll have a session. If you want to avoid that, you should:
switch to another protocol/binding where appropriate
decorate your service contracts with a SessionMode attribute
If you want to stop a service from ever using a session, you can do so like this:
[ServiceContract(Namespace="....", SessionMode=SessionMode.NotAllowed)]
interface IYourSession
{
....
}
and you can decorate your service class with the appropriate instance context mode attributes:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class YourService : IYourService
{
....
}
With this, you should be pretty much on the safe side and not get any sessions whatsoever.
Marc

Related

ASP.NET Core Scoped DbContext (EntityFramework) in Multithreading Environment

I read a lot about a scoped DbContext (EntityFramework) in a ASP.NET Core environment.
It makes sense to setup the DI framework with a scoped DbContext, due to have one DbContext per request.
Unfortunately this DbContext cannot be used in a Parallel.ForEach loop (or any kind of thread). The DbContext itself is not threadsafe! So I have to be careful using any kind of Task/Thread.
But sometimes its necessary (or useful) to implements something in a Parallel.ForEach (or something like this).
But how can I be sure that my called functions in a Parallel.ForEach dont use any kind of DbContext? Or maybe one day I decide to use a DbContext in some class/functions which is called from a Task, but I dont not recognize it?
There must be a solution for this? Right now it seems that I cannot use the TPL at all (just to be safe) ... but this seems to be very strange.
Isn't there any better approach?
You would have to inject a IServiceProvider and create your own scope for each iteration.
A quick example would look like
Parallel.ForEach(values, value =>
{
using (var scope = _serviceProvider.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<DbContext>();
//query context here
} // The context will be disposed off by the scope
});
Serviced acquired through the scope will also be scoped to it (when applicable)

Fixing "PrincipalException: PermissionChecker not initialized" the Liferay 7 way

With Liferay 6, using *LocalServiceUtil static calls was common. Starting from Liferay 7, these calls should be avoided in favor of #Referenceing the OSGi service and using it as a private member of the class, if I understood correctly (feel free to correct me).
Problem: When I replace my old *LocalServiceUtil calls with the OSGi-friendly equivalent, I get this exception:
com.liferay.portal.kernel.security.auth.PrincipalException:
PermissionChecker not initialized
at com.liferay.portal.kernel.service.BaseServiceImpl.getPermissionChecker
at com.liferay.portal.service.impl.UserServiceImpl.getUserById
How to fix it?
I could get a random admin via the OSGi equivalent of UserLocalServiceUtil.getRoleUsers(RoleLocalServiceUtil.getRole(company.getCompanyId(),"Administrator").getRoleId()) and use it in the the OSGi equivalent of PermissionThreadLocal.setPermissionChecker(PermissionCheckerFactoryUtil.create(randomAdmin)) but that sounds very hacky, plus it would put the responsibility of my code's actions on the shoulders of this unlucky admin.
My code:
protected void myMethod() {
userService.getUserById(userId);
}
#Reference(unbind = "-")
protected com.liferay.portal.kernel.service.UserService userService;
I think you actually wanted to inject UserLocalService.
In OSGi you should only strip the *Util suffix to receive equivalent functionality.
What you did is moved from LocalService (UserLocalServiceUtil) to remote service (UserService). The local services do not check permissions so there is no permission checker initialisation.
Apart from the above, you should be sure that no mischief can happen when using Local services. It's not recommended to expose this kind of functionality to end users but it's fine for some background processing.

Best practice for connections to CRM in web application

am sorry if this question will be a bit to broad but if this is question about normal ASP.NET MVC 5 Owin based application with default connection to MSSQL server i would not have such hard time but we use CRM as our database.
Ok as i mention am working on ASP.NET MVC5 application and am having hard time finding what is the best practice to create, keep open and to close connection to Dynamics CRM 365?
I found some many posts and blogs but everyone pulling on his side of the road.
Some say it's better for every request to open new connection in using statement so it could be closed right away (that's sounds good but it's a possible that requests will be slow because on every request it needs to open new connection to CRM).
Some say it' better to make singleton object on application scope, keep it open during application lifetime and reuse it on every request.
Normally i would use OrganizationServiceProxy in some simple console app but in this case am not sure should i use OrganizationServiceProxy or CrmServiceClient or something else?
If anyone have or had some similar problem, any hint would be great.
UPDATE:
#Nicknow
I downloaded SDK from SDK 365 and am using this dll-s.
Microsoft.Xrm.Sdk.dll, Microsoft.Crm.Sdk.Proxy.dll, Microsoft.Xrm.Tooling.Connector.dll and Microsoft.IdentityModel.Clients.ActiveDirectory.dll.
You mention
Microsoft.CrmSdk.XrmTooling.CoreAssembly 8.2.0.5.
if am correct this nuget package use official assembly that i downloaded, or there are some modification to this package?
About that test
proof test
if i got it right, no matter if i use using statement, implement Dispose() method or just use static class on application scope for a lifetime of application i will allways get same instance (If i use default settings RequireNewInstance=false)?
For code simplicity, I usually create a static class (a singleton could be used too, but would usually be overkill) to return a CrmServiceClient object. That way my code is not littered with new CrmServiceClient calls should I want to change anything about how the connection is being made.
So it would be good practice to create static class on application scope that lives for application lifetime? That means that every user that makes request would use same instance ? Wouldn't that be i performance issue for that one connection?
All of your method calls will execute to completion or throw an exception thus even if the GC takes a while there is no open connection sitting out there eating up resources and/or blocking other activity.
This one takes me back to section where i allways get same instance of CrmServiceClient and got the part that xrm.tooling handles cached connection o the other side but what happens on this side (web application).
Isn't the connection to CRM (i.e. CrmServiceClient) unmanaged resources, shouldn't i Dispose() it explicitly?
I found some examples with CrmServiceClient and pretty much in all examples CrmServiceClient is casted in IOrganizationService using CrmServiceClient.OrganizationWebProxyClient or CrmServiceClient.OrganizationServiceProxy.
Why is that and what are the benefits of that?
I got so many questions but this is already allot to ask, is there any online documentation that you could point me to it?
First, I'm assuming you are using the latest SDK DLLs from Nuget: Microsoft.CrmSdk.XrmTooling.CoreAssembly 8.2.0.5.
I never wrap the connection in a using statement and I don't think I've ever seen an example where that is done. There are examples from the "old days", before we had tooling library, where calls to create OrganizationServiceProxy were wrapped in a using statement, which caused a lot of inexperienced developers to release code with connection performance issues.
Luckily most of this has been fixed for us through the Xrm.Tooling library.
Create your connection object using CrmServiceClient:
CrmServiceClient crmSvc = new CrmServiceClient(#"...connection string goes here...");
Now if I create an OrganizationServiceContext (or an early-bound equivalent) object I do wrap that in a using so that it is determinedly disposed when I've completed my unit of work.
using (var ctx = new OrganizationServiceContext(crmSvc))
{
var accounts = from a in ctx.CreateQuery("account")
select a["name"];
Console.WriteLine(accounts.ToList().Count());
}
The Xrm.Tooling library handles everything else for you as far the connection channel and authentication. Unless you specify to create a new channel each time (by adding 'RequireNewInstance=true' to the connection string or setting the useUniqueInstance to true when calling new CrmServiceClient) the library will reuse the existing authenticated channel.
I used the following code to do a quick proof test:
void Main()
{
var sw = new Stopwatch();
sw.Start();
var crmSvc = GetCrmClient();
Console.WriteLine($"Time to get Client # 1: {sw.ElapsedMilliseconds}");
crmSvc.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 1: {sw.ElapsedMilliseconds}");
var crmSvc2 = GetCrmClient();
Console.WriteLine($"Time to get Client # 2: {sw.ElapsedMilliseconds}");
crmSvc2.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 2: {sw.ElapsedMilliseconds}");
}
public CrmServiceClient GetCrmClient()
{
return new CrmServiceClient("...connection string goes here...");
}
When I run this with RequireNewInstance=true I get the following console output:
Time to get Client # 1: 2216
Time to WhoAmI # 1: 2394
Time to get Client # 2: 4603
Time to WhoAmI # 2: 4780
Clearly it was taking about the same amount of time to create each connection.
Now, if I change it to RequireNewInstance=false (which is the default) I get the following:
Time to get Client # 1: 3761
Time to WhoAmI # 1: 3960
Time to get Client # 2: 3961
Time to WhoAmI # 2: 4145
Wow, that's a big difference. What is going on? On the second call the Xrm.Tooling library uses the existing service channel and authentication (which it cached.)
You can take this one step further and wrap your new CrmServiceClient calls in a using and you'll get the same behavior, because disposing of the return instanced does not destroy the cache.
So this will return times similar to above:
using (var crmSvc = GetCrmClient())
{
Console.WriteLine($"Time to get Client # 1: {sw.ElapsedMilliseconds}");
crmSvc.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 1: {sw.ElapsedMilliseconds}");
}
using (var crmSvc2 = GetCrmClient())
{
Console.WriteLine($"Time to get Client # 2: {sw.ElapsedMilliseconds}");
crmSvc2.Execute(new WhoAmIRequest());
Console.WriteLine($"Time to WhoAmI # 2: {sw.ElapsedMilliseconds}");
}
For code simplicity, I usually create a static class (a singleton could be used too, but would usually be overkill) to return a CrmServiceClient object. That way my code is not littered with new CrmServiceClient calls should I want to change anything about how the connection is being made.
To fundamentally answer the question about using, we don't need to use it because there is nothing to be released. All of your method calls will execute to completion or throw an exception thus even if the GC takes a while there is no open connection sitting out there eating up resources and/or blocking other activity.

I wrote a Liferay module. How to make it configurable by administrators?

I have created a Liferay 7 module, and it works well.
Problem: In the Java source code I hard-coded something that administrators need to modify.
Question: What is the Liferay way to externalize settings? I don't mind if the server has to be restarted, but of course the ability to modify settings on a live running server (via Gogo Shell?) could be cool provided that these settings then survive server restarts.
More specifically, I have a module for which I would like to be able to configure an API key that looks like "3g9828hf928rf98" and another module for which I would like to configure a list of allowed structures that looks like "BASIC-WEB-CONTENT","EVENTS","INVENTORY".
Liferay is utilizing the standard OSGi configuration. It's quite a task documenting it here, but it's well laid out in the documentation.
In short:
#Meta.OCD(id = "com.foo.bar.MyAppConfiguration")
public interface MyAppConfiguration {
#Meta.AD(
deflt = "blue",
required = false
)
public String favoriteColor();
#Meta.AD(
deflt = "red|green|blue",
required = false
)
public String[] validLanguages();
#Meta.AD(required = false)
public int itemsPerPage();
}
OCD stands for ObjectClassDefinition. It ties this configuration class/object to the configurable object through the id/pid.
AD is for AttributeDefinition and provides some hints for the configuration interface, which is auto-generated with the help of this meta type.
And when you don't like the appearance of the autogenerated UI, you "only" have to add localization keys for the labels that you see on screen (standard Liferay translation).
You'll find a lot more details on OSGi configuration for example on enroute, though the examples I found are always a bit more complex than just going after the configuration.

Uploading photos using Grails Services

I would like to ask, What would be the most suitable scope for my upload photo service in Grails ? I created this PhotoService in my Grails 2.3.4 web app, all it does is to get the request.getFile("myfile") and perform the necessary steps to save it on the hard drive whenever a user wants to upload an image. To illustrate what it looks like, I give a skeleton of these classes.
PhotoPageController {
def photoService
def upload(){
...
photoService.upload(request.getFile("myfile"))
...
}
}
PhotoService{
static scope="request"
def upload(def myFile){
...
// I do a bunch of task to save the photo
...
}
}
The code above isn't the exact code, I just wanted to show the flow. But my question is:
Question:
I couldn't find the exact definition of these different grails scopes, they have a one liner explanation but I couldn't figure out if request scope means for every request to the controller one bean is injected, or each time a request comes to upload action of the controller ?
Thoughts:
Basically since many users might upload at the same time, It's not a good idea to use singleton scope, so my options would be prototype or request I guess. So which one of them works well and also which one only gets created when the PhotoService is accessed only ?
I'm trying to minimize the number of services being injected into the application context and stays as long as the web app is alive, basically I want the service instance to die or get garbage collect at some point during the web app life time rather than hanging around in the memory while there is no use for it. I was thinking about making it session scope so when the user's session is terminated the service is cleaned up too, but in some cases a user might not want to upload any photo and the service gets created for no reason.
P.S: If I move the "def photoService" within the upload(), does that make it only get injected when the request to upload is invoked ? I assume that might throw exception because there would be a delay until Spring injects the service and then the ref to def photoService would be n
I figured out that Singleton scope would be fine since I'm not maintaining the state for each request/user. Only if the service is supposed to maintain state, then we can go ahead and use prototype or other suitable scopes. Using prototype is safer if you think the singleton might cause unexpected behavior but that is left to testing.

Resources