System.SecurityException when using Principal permissions with WCF and InstanceContextMode.Single - wcf

Im trying to add ASP .NET membership security to my Silverlight + WCF application but i keep getting the following exception intermittently:
at System.Security.Permissions.PrincipalPermission.ThrowSecurityException()
at System.Security.Permissions.PrincipalPermission.Demand()
at System.Security.PermissionSet.DemandNonCAS()
at Hp.Esf.Service.EsfService.GetAllUsers() in C:\HP\Trunk with failing Authentication\trunk\Hp.Esf.Service\EsfService.cs:line 227
at SyncInvokeGetAllUsers(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
If I use [InstanceContextMode = InstanceContextMode.PerCall)] everything works as expected but if I change it to InstanceContextMode = InstanceContextMode.Single)] that exception keeps appearing intermittently (Or at least I havent found a pattern of why this is happening)
Does anybody has any idea of why this could be happening?

Related

Getting UnauthorizedAccessException when deploying asp.net core app using Kudu build service

I have set up Continuous Deployment of my aspnet core 2.2 app using Kudu build service (directly connected through GitHub). It was fine until the day before yesterday but started getting UnauthorizedAccessException when I try to deploy anything since yesterday. Nothing changed in my application though. Any idea what could be wrong here??
Here is the detail exception:
Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
at Internal.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
at Internal.Win32.RegistryKey.SetValue(String name, String value)
at System.Environment.SetEnvironmentVariableFromRegistry(String variable, String value, Boolean fromMachine)
Failed exitCode=1, command=dotnet restore "D:\home\site\repository\myproject.sln"
at System.Environment.SetEnvironmentVariable(String variable, String value, EnvironmentVariableTarget target)
An error has occurred during web site deployment.
at Microsoft.DotNet.Cli.Utils.EnvironmentProvider.SetEnvironmentVariable(String variable, String value, EnvironmentVariableTarget target)
at Microsoft.DotNet.ShellShim.WindowsEnvironmentPath.AddPackageExecutablePathToUserPath()
at Microsoft.DotNet.Configurer.DotnetFirstTimeUseConfigurer.Configure()
at Microsoft.DotNet.Cli.Program.ConfigureDotNetForFirstTimeUse(IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel, IAspNetCertificateSentinel aspNetCertificateSentinel, IFileSentinel toolPathSentinel, Boolean hasSuperUserAccess, DotnetFirstRunConfiguration dotnetFirstRunConfiguration, IEnvironmentProvider environmentProvider)
at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient)
at Microsoft.DotNet.Cli.Program.Main(String[] args)
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.\r\n at Internal.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)\r\n at Internal.Win32.RegistryKey.SetValue(String name, String value)\r\n at System.Environment.SetEnvironmentVariableFromRegistry(String variable, String value, Boolean fromMachine)\r\n at System.Environment.SetEnvironmentVariable(String variable, String value, EnvironmentVariableTarget target)\r\n at Microsoft.DotNet.Cli.Utils.EnvironmentProvider.SetEnvironmentVariable(String variable, String value, EnvironmentVariableTarget target)\r\n at Microsoft.DotNet.ShellShim.WindowsEnvironmentPath.AddPackageExecutablePathToUserPath()\r\n at Microsoft.DotNet.Configurer.DotnetFirstTimeUseConfigurer.Configure()\r\n at Microsoft.DotNet.Cli.Program.ConfigureDotNetForFirstTimeUse(IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel, IAspNetCertificateSentinel aspNetCertificateSentinel, IFileSentinel toolPathSentinel, Boolean hasSuperUserAccess, DotnetFirstRunConfiguration dotnetFirstRunConfiguration, IEnvironmentProvider environmentProvider)\r\n at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient)\r\n at Microsoft.DotNet.Cli.Program.Main(String[] args)\r\nD:\Program Files (x86)\SiteExtensions\Kudu\86.20224.4450\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"
After trying "dotnet restore --help" inside kudu and getting the same error I realized that the error was connected to doing "dotnet restore" inside kudu and not with my application.
After looking at the code related to the error message
https://github.com/dotnet/sdk/blob/5d747e7b4f1450a00eff5844bd76b73588531b2c/src/Cli/dotnet/Program.cs#L152
I realized that I could solve the issue by adding a new application setting with the name DOTNET_ADD_GLOBAL_TOOLS_TO_PATH and the value false
Application setting
After that I could deploy my application using kudu as I did before.

Tests that use Fakes/Shims fail on server, but succeed in local

Tests that use Fakes/Shims fail on build server, but succeed in local.
This following error is gone when I remove the test that uses shims. Do I need to do any specific configuration on build server?
On a side note, I'm using shims in my specflow test cases.
Run has the following issue(s):
One of the background threads threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method(Closure , IContextManager )
at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.FireEvents(HookType bindingEvent)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnTestRunEnd()
at TechTalk.SpecFlow.TestRunner.OnTestRunEnd()
at TechTalk.SpecFlow.TestRunnerManager.OnTestRunnerEnd()
at TechTalk.SpecFlow.TestRunnerManager.
Further debugging gives the following error,
Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitT‌​estIsolationExceptio‌​n: Failed to resolve profiler path from COR_PROFILER_PATH and COR_PROFILER environment variables.

How do I configure distributed transactions for NServiceBus

I have the following scenario.
First write something to a db
Send message on bus
I want to execute those like an atomic action, that is, running them in a transaction but can't get it to work when it is really distributed. Everything was working fint on local machine, but as soon as the service was on another machine it stopped working.
My code looks something like this:
using(var ts = new TransactionScope())
{
// Write something to db
_bus.Send(SomeMessage);
ts.Complete();
}
I have done everything I could think of and find information about, like enabling DTC on client, server and db with inbound and outbound enabled, set the port DCOM protocols to 5000-6000. The error I get is:
FailedToSendMessageException: "Failed to send message to address: myserver"
and the stacktrace is:
at NServiceBus.Transports.Msmq.MsmqMessageSender.ThrowFailedToSendException(Address address, Exception ex) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 89
at NServiceBus.Transports.Msmq.MsmqMessageSender.Send(TransportMessage message, Address address) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Transports\Msmq\MsmqMessageSender.cs:line 80
at NServiceBus.Unicast.UnicastBus.SendMessage(List`1 addresses, String correlationId, MessageIntentEnum messageIntent, Object[] messages) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\UnicastBus.cs:line 658
at NServiceBus.Unicast.UnicastBus.SendMessage(Address address, String correlationId, MessageIntentEnum messageIntent, Object[] messages) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\UnicastBus.cs:line 583
at NServiceBus.Unicast.UnicastBus.NServiceBus.IBus.Send(Object[] messages) in c:\BuildAgent\work\d4de8921a0aabf04\src\NServiceBus.Core\Unicast\UnicastBus.cs:line 480
at Rapporteringsregisteret.Web.Controllers.RapporteringController.Post(OpprettRapportering opprettRapportering) in c:\dev\git\Rapporteringsregisteret\src\Rapporteringsregisteret.Web\Controllers\RapporteringController.cs:line 37
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
Why isn't this working?
When running in a distributed scenario your endpoint mapping needs to explicitely define the machine name where the queue of the receiver is located. When running on the same box this is not necessary. Therefore your mapping should not contain "myserver" but "myserver#machinename". This error is not related to DTC. For future questions always include Nservicebus version number and transport layer

WCF : An item with the same key has already been added

While testing WCF services with 150 Users, i got this exception.
Note : I am using MS Test Project for loadtesting of WCF Service. When load test is run for 100users, there is no exception.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Linq.Dynamic.ClassFactory.GetDynamicClass(IEnumerable1 properties) at System.Linq.Dynamic.DynamicExpression.CreateClass(IEnumerable`1 properties) at System.Linq.Dynamic.ExpressionParser.ParseNew() at System.Linq.Dynamic.ExpressionParser.ParseIdentifier() at System.Linq.Dynamic.ExpressionParser.ParsePrimaryStart() at System.Linq.Dynamic.ExpressionParser.ParsePrimary() at System.Linq.Dynamic.ExpressionParser.ParseUnary() at System.Linq.Dynamic.ExpressionParser.ParseMultiplicative() at System.Linq.Dynamic.ExpressionParser.ParseAdditive() at System.Linq.Dynamic.ExpressionParser.ParseComparison() at System.Linq.Dynamic.ExpressionParser.ParseLogicalAnd() at System.Linq.Dynamic.ExpressionParser.ParseLogicalOr() at System.Linq.Dynamic.ExpressionParser.ParseExpression() at System.Linq.Dynamic.ExpressionParser.Parse(Type resultType) at System.Linq.Dynamic.DynamicExpression.ParseLambda(ParameterExpression[] parameters, Type resultType, String expression, Object[] values) at System.Linq.Dynamic.DynamicExpression.ParseLambda(Type itType, Type resultType, String expression, Object[] values) at System.Linq.Dynamic.DynamicQueryable.Select(IQueryable source, String selector, Object[] values) at CustomEntities.Data.Repository.CustomEntitiesDataRepository.GetCustomEntityData(CriteriaDto criteriaDto) in d:\Projects\SRM\Services\Data\CustomEntities\CustomEntities.Data.Repository\CustomEntitiesDataRepository.cs:line 131 at CustomEntities.Data.Manager.CustomEntitiesDataManager.GetCustomEntityData(CriteriaDto criteriaDto) in d:\Projects\SRM\Services\Data\CustomEntities\CustomEntities.Data.Manager\CustomEntitiesDataManager.cs:line 69
If you look at your code, in CustomEntitiesDataRepository.cs at line 131, this line is triggering the issue. The custom entity you are returning is, at some level, trying to insert a value into a Dictionary<T,U>, but the key its using already exists.
Actually it looks like there's a concurrency issue in .Select(). See http://www.webr2.com/system-linq-dynamic-select-new-does-not-appear-to-be-thread-safe/
Easiest fix is to put some locking in your code around calls to Select

Access Denied Error for a method in web service

I have a webservice that works perfectly from localhost but when I hosted it on the testing server I get an error on one of the methods. I am using wsHttp Binding. everything else works fine on the client side except for this method. This is the error that I am getting
client error:
System.ServiceModel.Security.SecurityAccessDeniedException: Access is denied.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Server error:
namespace.Service Error: 10001 : Error occurred in methodname().
System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.
at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly)
at System.Diagnostics.EventLog.SourceExists(String source, String machineName)
at System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, String currentMachineName)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
at System.Diagnostics.EventLogTraceListener.TraceEvent(TraceEventCache eventCache, String source, TraceEventType severity, Int32 id, String format, Object[] args)
at System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String format, Object[] args)
at AutoWatch.Entity.WcfService.TrackingService.UpdateIncidentStatusHistory(Int64 incidentId, String status, String username, String comment, Boolean SuspectFaultyUnit) in C:\..servicename.cs:line 566
at AutoWatch.Entity.WcfService.TrackingService.GetNewIncidentMessage(String username) in C:\..servicename.cs:line 444
The Zone of the assembly that failed was:
MyComputer
I added in the error I am getting on the server.
Is it possible I am getting this error because the service cannot write to the event log?
Please help.
Ensure that account running your process where the service is hosted has access rights to the database. For example in case of IIS the account running the application pool where the service is hosted must have login to database server and it must have permissions to do all necessary operations in your database.
Edit:
The server stack trace looks quite straightforward. You have a problem with writing to Windows Event Log! It cannot find source you requested and it doesn't have permission to create it.
I got the same error when I tried to use the following statement in a Web Method of a WCF Service:
string myTypeName = typeof(ErrorHandlerBehavior).AssemblyQualifiedName;
where ErrorHandlerBehavior derives from BehaviorExtensionElement.
The line works well when I test the service on my localhost. On the web, the call of the containing method raises the Exception "Access is denied".
In this case, I guess that the cause was that my IP does not allow the creation of a BehaviourExtensionElement in a Partially Trusted environment (my service is in a shared hosting environment).
Finally, I succeded following the first mechanism described at https://learn.microsoft.com/en-us/dotnet/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors about Service Behaviors:
"Using an attribute on the service class. When a ServiceHost is constructed, the ServiceHost implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of IServiceBehavior, they are added to the behaviors collection on ServiceDescription. This allows those behaviors to participate in the construction of the service run time."
I just modified the derivation (no other modification required):
public class ErrorServiceBehavior : Attribute, IServiceBehavior
{ ... }
and use the class as Attribute of my service:
[ErrorServiceBehavior()]
public partial class MyService : IMyService
{...}
No other modification required. Check the original sample at How do I create a global exception handler for a WCF Services?.