Access Denied Error for a method in web service - wcf

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?.

Related

RavenDB connection issues

We have seen a noticeable uptick in problems related to RavenDB connections. We're using the IIS server connection method.
I've checked the index errors and I don't see anything listed.
This server is replicated with a MySQL server and there is one error related to replication in the log from today. Could the client stack trace errors actually be coming from the replicated server and not Raven?
EDIT
The client in this case is a single job that runs a few hundred times a day...succeeding many of those times but increasing in failures due to these errors.
Sql Replication failure to replication
Here are the partial stack trace errors from the client log:
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context):367
System.Net.HttpWebRequest.GetRequestStream():3
Raven.Abstractions.Connection.HttpRequestHelper.WriteDataToRequest(HttpWebRequest req, String data, Boolean disableCompression):7
Raven.Client.Connection.ServerClient.DirectBatch(IEnumerable`1 commandDatas, String operationUrl):171
Raven.Client.Connection.ReplicationInformer.TryOperation[T](Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result, Boolean& wasTimeout):35
Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication[T](String method, String primaryUrl, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation):169
Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation):33
Raven.Client.Document.DocumentSession.SaveChanges():65
and
[WebException: Unable to connect to the remote server]
System.Net.HttpWebRequest.GetResponse():570
Raven.Client.Connection.HttpJsonRequest.ReadJsonInternal(Func`1 getResponse):45
Raven.Client.Connection.HttpJsonRequest.ReadResponseJson():206
Raven.Client.Connection.ServerClient.DirectGet(String[] ids, String operationUrl, String[] includes, String transformer, Dictionary`2 queryInputs, Boolean metadataOnly):631
Raven.Client.Connection.ServerClient+<>c__DisplayClass77.<Get>b__76(String u):51
Raven.Client.Connection.ReplicationInformer.TryOperation[T](Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result, Boolean& wasTimeout):35
Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication[T](String method, String primaryUrl, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation):169
Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation):33
Raven.Client.Document.HiLoKeyGenerator.GetDocument(IDatabaseCommands databaseCommands):41
Raven.Client.Document.HiLoKeyGenerator.GetNextRange(IDatabaseCommands databaseCommands):109
Raven.Client.Document.HiLoKeyGenerator.NextId(IDatabaseCommands commands):58
Raven.Client.Document.HiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention convention, Object entity):9
Raven.Client.Document.MultiTypeHiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, Object entity):174
Raven.Client.Document.DocumentStore+<>c__DisplayClass4.<Initialize>b__2(String dbName, IDatabaseCommands databaseCommands, Object entity):20
Raven.Client.Document.DocumentConvention.GenerateDocumentKey(String dbName, IDatabaseCommands databaseCommands, Object entity):164
Raven.Client.Document.GenerateEntityIdOnTheClient.GenerateDocumentKeyForStorage(Object entity):46
Raven.Client.Document.InMemoryDocumentSessionOperations.StoreInternal(Object entity, Etag etag, String id, Boolean forceConcurrencyCheck):79
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity):23
The error says the client cannot connect to the the server. Maybe the client is offline. Or the server is. Or a firewall is in the way. Or maybe the server is there but blows up before returning a response to the client. If the issue is intermittent, and users arent complaining, it's probably just a connectivity thing that you can ignore. If users are complaining, you should look in server-side logs.

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

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

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?

Why WCF client not receiving SOAP Fault as FaultException?

I am using a WCF client to consume a non-WCF SOAP 1.2 web service. When receiving a SOAP fault as shown below, I receive a ProtocolException instead of a FaultException. There are no problems with the communication binding and the request is being processed successfully. But I cannot access the fault error in my WCF client. Any ideas?
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:c14n="http://www.w3.org/2001/10/xml-exc-c14n#" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsa5="http://www.w3.org/2005/08/addressing" xmlns:wsr="http://docs.oasis-open.org/wsrf/r-2" xmlns:xmime5="http://www.w3.org/2005/05/xmlmime" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:tt="http://www.onvif.org/ver10/schema" xmlns:wsbf="http://docs.oasis-open.org/wsrf/bf-2" xmlns:wstop="http://docs.oasis-open.org/wsn/t-1" xmlns:ns10="http://www.onvif.org/ver10/events/wsdl/PausableSubscriptionManagerBinding" xmlns:ns3="http://www.onvif.org/ver10/events/wsdl/PullPointSubscriptionBinding" xmlns:ns4="http://www.onvif.org/ver10/events/wsdl/EventBinding" xmlns:tev="http://www.onvif.org/ver10/events/wsdl" xmlns:ns5="http://www.onvif.org/ver10/events/wsdl/SubscriptionManagerBinding" xmlns:ns6="http://www.onvif.org/ver10/events/wsdl/NotificationProducerBinding" xmlns:ns7="http://www.onvif.org/ver10/events/wsdl/NotificationConsumerBinding" xmlns:ns8="http://www.onvif.org/ver10/events/wsdl/PullPointBinding" xmlns:ns9="http://www.onvif.org/ver10/events/wsdl/CreatePullPointBinding" xmlns:wsnt="http://docs.oasis-open.org/wsn/b-2" xmlns:tds="http://www.onvif.org/ver10/device/wsdl" xmlns:ter="http://www.onvif.org/ver10/error" xmlns:timg="http://www.onvif.org/ver20/imaging/wsdl" xmlns:tptz="http://www.onvif.org/ver20/ptz/wsdl" xmlns:trt="http://www.onvif.org/ver10/media/wsdl">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<SOAP-ENV:Code>
<SOAP-ENV:Value>SOAP-ENV:Sender</SOAP-ENV:Value>
<SOAP-ENV:Subcode>
<SOAP-ENV:Value>ter:InvalidArgVal</SOAP-ENV:Value>
<SOAP-ENV:Subcode>
<SOAP-ENV:Value>ter:NoSource</SOAP-ENV:Value>
</SOAP-ENV:Subcode>
</SOAP-ENV:Subcode>
</SOAP-ENV:Code>
<SOAP-ENV:Reason>
<SOAP-ENV:Text xml:lang="en">Not exist</SOAP-ENV:Text>
</SOAP-ENV:Reason>
<SOAP-ENV:Detail>
<SOAP-ENV:Text xml:lang="en">The requested VideoSource does not exist.</SOAP-ENV:Text>
</SOAP-ENV:Detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
System.ServiceModel.ProtocolException
"The remote server returned an unexpected response: (400) Bad Request.
StackTrace
"Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at OnvifProxy.ImagingPort.SetImagingSettings(String VideoSourceToken, ImagingSettings20 ImagingSettings, Boolean ForcePersistence)
at OnvifProxy.ImagingPortClient.SetImagingSettings(String VideoSourceToken, ImagingSettings20 ImagingSettings, Boolean ForcePersistence) in D:\..\Proxies\OvifServices.cs:line 19005
at Integral.Common.IPCameras.ONVIF.Services.ImagingService.SetImageSettings(String pVideoSourceToken, ImagingSettings20 pImageSettings) in D:\..\Services\ImagingService.cs:line 375" string
I would recommend using Fiddler to intercept the raw response. In these situations (interop), it's best to bypass WCF entirely and read the response message as it arrives "on the wire." Trying to debug a non-WCF fault or a deserialization error through WCF can only give you headaches. =)
Most often, looking at the raw response will point the problem out like a sore thumb.
I think the problem you're having is because the server returns a 400 HTTP response code. Apparently the bodies of messages with a response code other than 200 are not accessible to the Silverlight client.
If you had control of the server, you could modify it to send a 200 response code instead of 400, but if you don't have control of the server, you need to modify your client to accept response codes other than 200.
I found some instructions here to change the client to use an alternative HTTP stack. I had the same problem as you (but with HTTP response code 500) and this fixed the problem. All you have to do is add this code at the beginning of your Silverlight application (for example, on the constructor for the MainPage class):
bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
Is the method being called marked with the IsOneWay=true attribute in the generated proxy class?
If it is then there is no back channel for the SOAP fault to be received on but WCF can get it back some other way and this shows up as the ProtocolException. As far as I am aware you need to have IsOneWay=false to get a SOAP fault.