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 - dynamics-crm-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)

Related

Any() method is not working when we connect to MySql

Calling Any() method on a table to check for existence of records throws an exception when we connect to MySql but it is working fine when we connect to SqlServer
I am using the following code:
public IActionResult GetCustomers()
{
DbContext db = new DbContext();
if(db.Customers.Any())//here throws an exception when connect to mysql db
{
//my code
}
return view();
}
My Exception was:
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.'
at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type, MethodInfo method)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Int32 index, TypeMaterializationInfo materializationInfo, Boolean detailedErrorsEnabled, Boolean box)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<>c__DisplayClass13_0.<CreateArrayInitializer>b__0(TypeMaterializationInfo mi, Int32 i)
at System.Linq.Enumerable.<SelectIterator>d__154`2.MoveNext()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey, Boolean detailedErrorsEnabled)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__11_0(CacheKey k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.Create(IReadOnlyList`1 types)
at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.CreateValueBufferFactory(IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.<NotifyReaderCreated>b__14_0(FactoryAndReader s)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
at SampleEfCoreLatest.Controllers.HomeController.GetCustomers() in D:\SampleEfCoreLatest\Controllers\HomeController.cs:line 49
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()

Dynamics CRM 2013 throws SQL Timeout adding a user to a team

I have a simple but tough problem.
I am trying to add an user to a team through user interface, however I'm getting SQL Time Out for some users.
I got no plugins firing on association request. I also did not find any familiarity between the ones I am getting this error.
I have even turned the trace log on which did not give me much more details.
Following the error log generated by tracing tool.
Web Service Plug-in failed in SdkMessageProcessingStepId: {D3DE2F15-53FA-4A12-A286-346CC4BFD310}; EntityName: none; Stage: 30; MessageName: Associate; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
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.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.AssociateEntities(EntityReference entity1, EntityReference entity2, String relationshipName, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.Execute(RelationshipProcessor processor, EntityMetadata entityMetadata, Guid entityId, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.ProcessAssociation(EntityMetadata entityMetadata, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.Associate(EntityReference entityReference, Relationship relationship, EntityReferenceCollection relatedEntities, ExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
Inner Exception: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.Crm.ObjectModel.BusinessManagementUtility.LockSystemUserEntriesForTeamMembershipChange(Guid userId, ExecutionContext context)
at Microsoft.Crm.ObjectModel.TeamMembershipServiceInternal`1.Associate(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.HandleAssociationOperation(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, Boolean createAssociation, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.AssociateEntities(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
Inner Exception: System.ComponentModel.Win32Exception: The wait operation timed out

Internal error when running visual studio project

I'm building a WPF application that currently only has UI elements in place. I'm trying to use some classes I made in another project by importing a dll. When I run the wpf application, Visual Studio pops up this dialog in the Team Explorer:
The application still runs, but I don't know the cause of this error and what its effects are. Has anyone else run into this error and have some insight?
Not sure if it is relevant, but the project I'm importing is using NHibernate and Log4Net. I'm also using Visual Studio 2013 Express if that has anything to do with it.
UPDATE:
Here's the stack trace:
at DatabaseUI.DatabaseViewModel..ctor() in c:\Users\andrew\Documents\Visual Studio 2013\Projects\DatabaseUI\DatabaseUI\ViewModels\DatabaseViewModel.cs:line 36
at DatabaseUI.MainWindow..ctor() in c:\Users\andrew\Documents\Visual Studio 2013\Projects\DatabaseUI\DatabaseUI\MainWindow.xaml.cs:line 30
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at System.Xaml.Schema.SafeReflectionInvoker.CreateInstanceCritical(Type type, Object[] arguments)
at System.Xaml.Schema.SafeReflectionInvoker.CreateInstance(Type type, Object[] arguments)
at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
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 System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(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.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 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, 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.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at DatabaseUI.App.Main() in c:\Users\andrew\Documents\Visual Studio 2013\Projects\DatabaseUI\DatabaseUI\obj\Debug\App.g.cs:line 0
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()
UPDATE 2:
I removed the ViewModel code because this problem existed before I created it. I got this error when I first created a wpf application without any content. I'm looking for answers that describe what this error means or a similar situation that someone had where they were able to resolve this issue.
UPDATE 3:
I started a new console application project and I'm getting the same error. This project does not use any resources from the previously described project, but both of these projects use log4net and nhibernate. I think this is an nhibernate issue.
UPDATE 4:
I started a new console application with absolutely nothing to it, and I'm still getting this error. I've deleted all references and the entire AssemblyInfo.cs, and still no progress.
UPDATE 5:
I create a new C++ console application and I am getting the same error. No nhibernate or anything that I thought was messing it up. There is definitely something wrong with Visual Studio...
Well, I fixed the error by re-installing Visual Studio. I'm still looking into what exactly went wrong, but something deep in the depths of Visual Studio must have been corrupted. Once I know more, I will update this answer to be more complete.
This happens when you have a static resource, in your case is databseviewmodel that is getting initiated and failure is due to that. If your viewmodel is calling database when it is constructed then it will show error due to improper initialization.

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.

Dynamics CRM error: "The object cannot be updated because it is read-only"

I've got an instance of Dynamics CRM 4.0 with some weird errors. If I close a Case and then try to reactivate it I get the error "The object cannot be updated because it is read-only". This is simple, built-in CRM functionality that works fine on other instances. I get the same error if I try to convert a Quote to an Order - I believe it's trying to update the Quote, which has been "closed" by then. What's wrong and how do I fix it?
MSCRM Error Report:
--------------------------------------------------------------------------------------------------------
Error: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Error Number: 0x8004022E
Error Message: The object cannot be updated because it is read-only.
Error Details: The object cannot be updated because it is read-only.
Source File: Not available
Line Number: Not available
Request URL: http://jupiter:5555/EN/cs/cases/edit.aspx?id={C75704E2-3B82-DE11-BFAD-00188B2CB446}
Stack Trace Info: [CrmException: The object cannot be updated because it is read-only.]
at Microsoft.Crm.ObjectModel.IncidentService.Update(IBusinessEntity incident, ExecutionContext context)
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.RequestBase.Process(Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.RequestBase.Process(CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.CrmServiceInternal.Execute(RequestBase request, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.InProcessCrmService.Execute(Object request)
at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.ExecuteInternal()
at Microsoft.Crm.Application.Platform.ServiceCommands.UpdateCommand.Execute()
at Microsoft.Crm.Application.Platform.EntityProxy.Update(Boolean performDuplicateCheck)
at Microsoft.Crm.Application.Platform.EntityProxy.Update()
at Microsoft.Crm.Web.CS.CaseDetailPage.Open(Object sender, DataEventArgs e)
at Microsoft.Crm.Application.Forms.DataEventProcessor.Raise(FormEventId eventId, FormState state, IUser user, String objectId, Entity entity)
at Microsoft.Crm.Application.Forms.AppForm.RaiseDataEvent(FormEventId eventId)
at Microsoft.Crm.Application.Forms.EndUserForm.Initialize(Entity entity)
at Microsoft.Crm.Application.Forms.CustomizableForm.Execute(Entity entity, String formType)
at Microsoft.Crm.Application.Forms.CustomizableForm.Execute(Entity entity)
at Microsoft.Crm.Web.CS.CaseDetailPage.ConfigureForm()
at Microsoft.Crm.Application.Controls.AppUIPage.OnPreRender(EventArgs e)
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
[HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.]
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.en_cs_cases_edit_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Try disabling your onload and onsave code to see if that is causing any problems. To quickly and temporarily disable the events, open the dialog box where you paste in your onload/onsave code and uncheck 'Event is enabled'. Then save the form and publish the entity. Does the error still occur?

Resources