Connecting to Windows Server Service Bus on AWS - amazon-ec2

I am starting work on a new project using the new Windows Server Service Bus 1.0 Beta. I am trying to set up a test environment on an AWS EC2 virtual machine.
I have installed the Service Bus on a Windows Server 2008 R2 instance running on AWS EC2 and setup a new Farm, Container and Host according to the examples in the MSDN documentatoin. I have all of the proper ports open on the server (4443 and 9354). I also followed the instructions from [this page][1] to export the self generated certificate onto my client machine.
I have a very simple C# program that creates a queue, queues a message, and receives it. This program works fine when I copy the executable up to the VM and run it there, so I believe that I am using the API correctly. However I get security exceptions when I run the program from my local development box pointing to the AWS server.
My code Looks like this:
var servername = "X.X.X.X"; // <-- An IP Address, not FQDN
var sbNamespace = "MyNamespace";
var httpPort = 4446;
var tcpPort = 9354;
//create SB uris
var rootAddressManagement = ServiceBusEnvironment.CreatePathBasedServiceUri("sb", sbNamespace, string.Format("{0}:{1}", servername, httpPort));
var rootAddressRuntime = ServiceBusEnvironment.CreatePathBasedServiceUri("sb", sbNamespace, string.Format("{0}:{1}", servername, tcpPort));
var tokenProvider = TokenProvider.CreateWindowsTokenProvider(new List<Uri>() { rootAddressManagement });
var namespaceManager = new NamespaceManager(rootAddressManagement,
new NamespaceManagerSettings()
{
TokenProvider = tokenProvider
});
var factory = MessagingFactory.Create(rootAddressRuntime,
new MessagingFactorySettings()
{
TokenProvider = tokenProvider,
//OperationTimeout = TimeSpan.FromMinutes(30)
});
if (!namespaceManager.QueueExists("OrderQueue")) <-- EXCEPTION OCCURRS HERE
{
// Code to create a queue that is never reached.
}
My exception trace looks like this:
[Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations+GetAsyncResult`1[[Microsoft.ServiceBus.Messaging.QueueDescription, Microsoft.ServiceBus, Version=1.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]] IteratorAsyncResult failed to move to the next step due to an exception; System.UnauthorizedAccessException: The token provider was unable to provide a security token while accessing 'https://107.23.15.5:4446/APIHealthcare/$STS/Windows/'. Token provider returned message: 'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'. ---> System.IdentityModel.Tokens.SecurityTokenException: The token provider was unable to provide a security token while accessing 'https://107.23.15.5:4446/APIHealthcare/$STS/Windows/'. Token provider returned message: 'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at Microsoft.ServiceBus.TokenProviderHelper.GetWindowsAccessTokenCore(IEnumerator`1 stsUris, Func`2 uriBuilder, String requestToken, TimeSpan timeout, DateTime& expiresIn)
--- End of inner exception stack trace ---
at Microsoft.ServiceBus.TokenProviderHelper.ThrowException(Uri requestUri, WebException exception)
at Microsoft.ServiceBus.TokenProviderHelper.GetWindowsAccessTokenCore(IEnumerator`1 stsUris, Func`2 uriBuilder, String requestToken, TimeSpan timeout, DateTime& expiresIn)
at Microsoft.ServiceBus.WindowsTokenProvider.OnBeginGetWebToken(String appliesTo, String action, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProvider.GetWebTokenAsyncResult..ctor(TokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProvider.BeginGetWebToken(String appliesTo, String action, Boolean bypassCache, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout)
--- End of inner exception stack trace ---
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.HttpWebRequestExtensions.AddAuthorizationHeader(HttpWebRequest request, ITokenProvider tokenProvider, Uri baseAddress, String action)
at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.GetAsyncResult`1.<GetAsyncSteps>d__c.MoveNext()
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.MoveNextStep()
A first chance exception of type 'System.UnauthorizedAccessException' occurred in Microsoft.ServiceBus.dll
System.UnauthorizedAccessException: The token provider was unable to provide a security token while accessing 'https://107.23.15.5:4446/APIHealthcare/$STS/Windows/'. Token provider returned message: 'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'. ---> System.IdentityModel.Tokens.SecurityTokenException: The token provider was unable to provide a security token while accessing 'https://107.23.15.5:4446/APIHealthcare/$STS/Windows/'. Token provider returned message: 'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at Microsoft.ServiceBus.TokenProviderHelper.GetWindowsAccessTokenCore(IEnumerator`1 stsUris, Func`2 uriBuilder, String requestToken, TimeSpan timeout, DateTime& expiresIn)
--- End of inner exception stack trace ---
at Microsoft.ServiceBus.TokenProviderHelper.ThrowException(Uri requestUri, WebException exception)
at Microsoft.ServiceBus.TokenProviderHelper.GetWindowsAccessTokenCore(IEnumerator`1 stsUris, Func`2 uriBuilder, String requestToken, TimeSpan timeout, DateTime& expiresIn)
at Microsoft.ServiceBus.WindowsTokenProvider.OnBeginGetWebToken(String appliesTo, String action, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProvider.GetWebTokenAsyncResult..ctor(TokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProvider.BeginGetWebToken(String appliesTo, String action, Boolean bypassCache, TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider tokenProvider, String appliesTo, String action, Boolean bypassCache, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.HttpWebRequestExtensions.AddAuthorizationHeader(HttpWebRequest request, ITokenProvider tokenProvider, Uri baseAddress, String action)
at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.GetAsyncResult`1.<GetAsyncSteps>d__c.MoveNext()
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.MoveNextStep()
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.EnumerateSteps(CurrentThreadType state)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.Start()
Exception rethrown at [0]:
at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.End(IAsyncResult asyncResult)
at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.EndGet[TEntityDescription](IAsyncResult asyncResult)
at Microsoft.ServiceBus.NamespaceManager.OnEndQueueExists(IAsyncResult result)
at Microsoft.ServiceBus.NamespaceManager.EndQueueExists(IAsyncResult result)
at Microsoft.ServiceBus.NamespaceManager.QueueExists(String path)
at ServiceBusSandbox.ServiceBusSampleApp.CreateAQueue(NamespaceManager namespaceManager) in c:\Users\cent049\Documents\Visual Studio 2012\Projects\ServiceBusSandbox\ServiceBusSandbox\ServiceBusSampleApp.cs:line 15
at ServiceBusSandbox.ServiceBusSampleApp.Main(String[] args) in c:\Users\cent049\DocumentThe thread 'vshost.RunParkingWindow' (0x2608) has exited with code 0 (0x0).
I have a hunch that the problem is that I am connecting using the IP address of the VM and not a FQDN, however I don't know how to confirm that, nor do I know how to get a Domain name for my AWS server. The server has a machine name but is simply on workgroup "WORKGROUP", not on a domain.
Any and all help would be greatly appreciated.

Use the CreateOAuthTokenProvider instead of the CreateWindowsTokenProvider.
First, you need to create an account in the machine at: rootAddressManagement.
Add the newly created account as an Manage user of your namespace. Set-SBNamespace -Name "YourNamespace" -Manage YourUser
Since you are using an ipaddress, add the cert validation code before you do any call to SB. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, cert, chain, ssl) => {return true; });
Third, use TokenProvider.CreateOAuthTokenProvider(new List() { rootAddressManagement }, new NetworkCredential("YouUser", "YouPassword"));
Note: do not specify machine name as part of YourUser

I got bad news and good news.
bad news is could't send the message using microsoft.servicebus.dll method.
For me i am unable to connect windows service bus using microsoft windows.servicebus.dll. When i tryed to send the message i stuck on sendmessage operation and couldnt proceed beyond that point.
I suspect the issue is
Publish to Azure Service Bus over http behind proxy
that is a bug in current release.
Good news is i managed to do all the service bus operation using rest api.
First thing is getting the authentication token using following code sample provide by microsft.
http://msdn.microsoft.com/en-us/library/windowsazure/jj193003%28v=azure.10%29.aspx
Once u get the token rest of operation (create que, send messages, recive messages) are same as windows azure service bus. please see the detail about microsoft documentation about service bus operation.
http://msdn.microsoft.com/en-us/library/windowsazure/hh690927.aspx
hope this helpful.
THanks.

Yes, your hunch is correct. You're running into that issue because the certificate used by the server is issued to the FQDN of the machine, and using the IP will cause a certificate name mismatch.
Short term, you can work around this by using a CertificateValidation callback to ignore the error:
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx
Long term, you might want to check how to get the external facing name of the VM, and use a certificate that matches that.

i am stuck in the same error. i followed the steps as describe in second post. but finally end up with
"This got me one step further. My app did connect and create the queue, but it failed when trying to place a message on the queue. The message I'm getting now is: System.IdentityModel.Tokens.SecurityTokenValidationException: The X.509 certificate CN=MACHINE_NAME is not in the trusted people store. The X.509 certificate CN=MACHINE_NAME chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. The revocation function was unable to check revocation for the certificate."

Related

Elasticsearch NEST SDK throws System.OutOfMemoryException

I am getting this exception from Elasticsearch .net client - NEST v7.10.0.
Exception of type 'System.OutOfMemoryException' was thrown. Elasticsearch.Net.UnexpectedElasticsearchClientException UnexpectedElasticsearchClientException Elasticsearch.Net.UnexpectedElasticsearchClientException: Exception of type 'System.OutOfMemoryException' was thrown.
---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Text.UTF8Encoding.GetString(Byte[] bytes, Int32 index, Int32 count)
at Elasticsearch.Net.ResponseBuilder.SetSpecialTypes[TResponse](String mimeType, Byte[] bytes, IMemoryStreamFactory memoryStreamFactory, TResponse& cs)
at Elasticsearch.Net.ResponseBuilder.SetBodyAsync[TResponse](ApiCallDetails details, RequestData requestData, Stream responseStream, String mimeType, CancellationToken cancellationToken)
at Elasticsearch.Net.ResponseBuilder.ToResponseAsync[TResponse](RequestData requestData, Exception ex, Nullable`1 statusCode, IEnumerable`1 warnings, Stream responseStream, String mimeType, CancellationToken cancellationToken)
at Elasticsearch.Net.HttpConnection.RequestAsync[TResponse](RequestData requestData, CancellationToken cancellationToken)
at Elasticsearch.Net.RequestPipeline.CallElasticsearchAsync[TResponse](RequestData requestData, CancellationToken cancellationToken)
at Elasticsearch.Net.Transport`1.RequestAsync[TResponse](HttpMethod method, String path, CancellationToken cancellationToken, PostData data, IRequestParameters requestParameters)
What should be done to resolve this issue?
I am trying to query AWS elasticsearch cluster to get the results which seems to be very large in size.
Try to upgrade your client version to the latest version and also check Elasticsearch Nest official issue thread:
https://github.com/elastic/elasticsearch-net/issues/4697

Visual Studio Installer fails to run

Visual Studio installer will not run.
First was trying to install additional feature from Visual Studio. Then running the visual studio installer from start menu.
Then deleting the installer directory and trying to run it from a fresh VS online installer.
Here is the error message from the log
Error 0x80131501: Application failed with an uncaught exception: Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at Microsoft.VisualStudio.Setup.Installer.Views.ThemedWindow..ctor(AppInitializerServiceOptions serviceOptions, IApplicationViewModel vm, Nullable`1 parentHandle)
at Microsoft.VisualStudio.Setup.Installer.FocusedUi.Views.FocusedWindow..ctor(AppInitializerServiceOptions serviceOptions, IApplicationViewModel vm, Nullable`1 parentHandle)
at Microsoft.VisualStudio.Setup.Installer.Application.WindowFactory.Create(IInstallerCommandLineOptions commandLineOptions, AppInitializerServiceOptions serviceOptions, IApplicationViewModel viewModel)
at Microsoft.VisualStudio.Setup.Installer.Application.MainApplication.InitializeWindow(AppInitializerServiceOptions serviceOptions, IInstallerCommandLineOptions commandLineOptions, IApplicationViewModel viewModel)
at Microsoft.VisualStudio.Setup.Installer.Application.ApplicationBase.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__1_0(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at Microsoft.VisualStudio.Setup.Installer.Application.MainApplication.Microsoft.VisualStudio.Setup.Installer.IApplication.Run()
at Microsoft.VisualStudio.Setup.Installer.Program.ExecuteInternal(IServiceContainer services, ICommandLineParserResult`1 parserResult, ITelemetry telemetry, ILogger logger)

Unable to login into PluginRegistrationTool - "Plugin Registration Tool stopped working"

I have 2 different accounts with Dynamics 365 online, few hours back I was able to login with 1 account. But then suddenly when I tried to login with another account, it is throwing errors as below:
And when I clicked on DEBUG button and opened it in Visual Studio, it gives error as below:
System.Reflection.TargetInvocationException HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib StackTrace: at
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Delegate.DynamicInvokeImpl(Object[] args) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl() at
MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object
obj) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Windows.Threading.DispatcherOperation.Invoke() at
System.Windows.Threading.Dispatcher.ProcessQueue() at
System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32
msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
IntPtr lParam, Boolean& handled) at
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate method, Object args, Int32
numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam) at
MS.Win32.UnsafeNativeMethods.MessageBox(HandleRef hWnd, String text,
String caption, Int32 type) at
System.Windows.MessageBox.ShowCore(IntPtr owner, String
messageBoxText, String caption, MessageBoxButton button,
MessageBoxImage icon, MessageBoxResult defaultResult,
MessageBoxOptions options) at System.Windows.MessageBox.Show(Window
owner, String messageBoxText, String caption, MessageBoxButton button,
MessageBoxImage icon) at
Microsoft.Crm.Tools.PluginRegistration.CommonControls.ErrorMessageViewModel.ShowErrorMessageBox(Window
owner, String message, String caption, String exceptionMessage,
UserControl usercontrol, Exception ex) at
Microsoft.Crm.Tools.PluginRegistration.CommonControls.ErrorMessageViewModel.ShowErrorMessageBox(Window
owner, String message, String caption, Exception ex, UserControl
usercontrol) at
Microsoft.Crm.Tools.PluginRegistration.MainViewModel.CreateConnections()
at
Microsoft.Crm.Tools.PluginRegistration.MainViewModel.b__1(Object
s) at
MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource
commandSource, Boolean userInitiated) at
System.Windows.Controls.Primitives.ButtonBase.OnClick() at
System.Windows.Controls.Button.OnClick() at
System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs
e) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate
handler, Object target) at
System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,
RoutedEventArgs routedEventArgs) at
System.Windows.EventRoute.InvokeHandlersImpl(Object source,
RoutedEventArgs args, Boolean reRaised) at
System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender,
RoutedEventArgs args, RoutedEvent newEvent) at
System.Windows.UIElement.OnMouseUpThunk(Object sender,
MouseButtonEventArgs e) at
System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object
target) at
System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,
RoutedEventArgs routedEventArgs) at
System.Windows.EventRoute.InvokeHandlersImpl(Object source,
RoutedEventArgs args, Boolean reRaised) at
System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,
RoutedEventArgs args) at
System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at
System.Windows.Input.InputManager.ProcessStagingArea() at
System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport
inputReport) at
System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd,
InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x,
Int32 y, Int32 wheel) at
System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr
hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean&
handled) at
System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
IntPtr lParam, Boolean& handled) at
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate method, Object args, Int32
numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam) at
MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at
System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
frame) at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window) at
Microsoft.Crm.Tools.PluginRegistration.App.Main()
Inner Exception 1: AdalException: multiple_matching_tokens_detected:
The cache contains multiple tokens satisfying the requirements. Call
AcquireToken again providing more requirements (e.g. UserId)
As per my initial go through, it looks like there is some token issue here. So I tried even deleting my account from cache, VS2017 and also restarted my machine. But still this issue persist.
PS: And when I tried to login with my 1st account which was working previously is no more working and throwing the same error.
Help!
I have already checked below link(s):
Regarding Plugin Registration Using xxxx#xxxx.onmicrosoft.com Credentials
After clearing %appdata%\Microsoft\PluginRegistration it started working.
For note: We can use PluginRegistrationTool in XRMToolBox too. (sharing this as I was not aware before of it.)
That Inner Exception makes more sense, looks like multiple tokens generated & stored for those user profiles in cache.
Following the answers in SO thread, either users UPN got reassigned or some mess happened. PRT unable to overcome this.
If you have not tried, try from a different machine.

I got this error "Support user does not have permission on this operation" when I want to give GrantAccess to a record in CRM SDK 2015

I got this exception:
"Support user does not have permission on this operation"
when I try to give access to a record for a user. this is my code:
public void GrantAccess(Guid targetId, Guid principleId)
{
using (var service = new OrganizationService(_con))
{
var request = new GrantAccessRequest()
{
Target = new EntityReference(Account.EntityLogicalName, targetId),
PrincipalAccess = new PrincipalAccess()
{
AccessMask = AccessRights.ReadAccess,
Principal = new EntityReference(principleId.ToString())
}
};
service.Execute(request);
}
}
and my Constr is like:
private static readonly string ConStr = "Url=http://crm.[ourdomain].com:90/Test; Domain=[ourdomain]; Username=[user]; Password=[password];";
I cand read the data, for example I get this method:
RetrieveSharedPrincipalsAndAccessResponse
even more I "RevokeAccess" by RevokeAccessRequest, but I couldn't Grant access or modify it.
Edit1
Full Stack Error:
System.ServiceModel.FaultException`1 was unhandled
Action=http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/ExecuteOrganizationServiceFaultFault
HResult=-2146233087
Message=Support user does not have permission on this operation
Source=mscorlib
StackTrace:
Server stack trace:
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)
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 Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.<Execute>b__18(IOrganizationService s)
at Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func`2 action)
at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request)
at CRMConsole.Queries.GrantAccess(Guid targetId, Guid principleId) in D:\Projects\CRM\CRMPrivileges\CRMConsole\Queries.cs:line 142
at CRMConsole.Program.Main(String[] args) in D:\Projects\CRM\CRMPrivileges\CRMConsole\Program.cs:line 20
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I checked the user access to the Account entity, and he has the read access to it with User depth. Beside that I can share this entity in crm web page UI with current user that is in connection credential.
It's so ridiculous but the problem was in this line of code:
Principal = new EntityReference(principleId.ToString())
we must declare entity name just like this:
Principal = new EntityReference(SystemUser.EntityLogicalName,principleId)

Microsoft Dynamics 2011 N:N LINQ query with where clause containing Guid

I have constructed a simple query to return a Users Team membership (N: N relationship). This works fine for all users, however, when I add a where clause to restrict to a specific user it throws a fault exception (see stack trace below).
Strangely this works fine with "where Users.FullName.StartsWith("Alex")". Does the Dynamics CRM SDK LINQ implementation not support Guides in where clauses?
Any advice?
Example code
using (var service = new OrganizationService("Xrm"))
{
using (var xrm = new XrmServiceContext(service))
{
var AlexUser = xrm.SystemUserSet.Where(p => p.FullName.StartsWith("Alex")).First();
var AlexID = AlexUser.Id;
var Test =
from Users in xrm.SystemUserSet
join TeamMemberships in xrm.TeamMembershipSet on Users.Id equals TeamMemberships.SystemUserId
join Teams in xrm.TeamSet on TeamMemberships.TeamId equals Teams.Id
where Users.Id == AlexID // <-- problematic where clause
orderby Users.FullName
select new
{
FullName = Users.FullName,
UserID = Users.Id,
TeamName = Teams.Name
};
var Test1 = Test.ToList();
}
}
Stacktrace:
Server stack trace: 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.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
Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.b__18(IOrganizationService
s) at
Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func2 action) at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups,
String& pagingCookie, Boolean& moreRecords) at
Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression
qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle,
Projection projection, NavigationSource source, List1 linkLookups) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.Query1.GetEnumerator() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
aspirets.crm.test.Program.Main(String[] args) in
C:\Users\a_marshall\documents\visual studio
2010\Projects\aspirets.crm\aspirets.crm.test\Program.cs:line 37 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
Instead of Users.Id, try Users.SystemUserId. Similarly, instead of Teams.Id, try Teams.TeamId.
As for the reason why this works, I'm not aware of any documentation that states this, but because entities in the generated early-binding file inherit from Entity, they necessarily have an Id property. However, because the early-bound OrganizationServiceContext maps entity attributes directly to the CRM database, the tables of which don't contain an Id column, using the Id attribute with the LINQ provider won't work, so you'd have to use the actual database/schema names.

Resources