Dynamics CRM 2016 - Set custom Customer lookup using form parameters - dynamics-crm

I have a Customer type field in a form with the schema name: myorg_customer. (Note that this is not an out-of-the-box customer field with schema name customerid that comes with CRM.)
I am opening a new Create form using javascript as follows:
var customer = [
{
id: "571A6CE5-3EBC-4672-A164-D8F9654D4FCF",
name: "TestContact"
}
];
parameters['myorg_customer'] = customer[0].id;
parameters['myorg_customername'] = customer[0].name;
parameters['myorg_customertype'] = "contact" // since my customer is a contact instead of an account.
parent.Xrm.Utility.openEntityForm("myorg_myentity", null, parameters);
But after doing so, the page changes to open the Create form but I get an error message saying "An error has occurred". The log file is as follows:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #89B46272Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> 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.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #89B46272</Message>
<Timestamp>2017-01-03T13:41:22.8457002Z</Timestamp>
<InnerFault>
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d3p1:key>CallStack</d3p1:key>
<d3p1:value xmlns:d5p1="http://www.w3.org/2001/XMLSchema" i:type="d5p1:string"> at Microsoft.Crm.Application.ParameterFilter.ValidateParameter(HttpRequest request, ArrayList parameterCollection, String key, String value, ParameterSources source, EntityType pageEntityType, FormAdditionalAllowedParameters additionalAllowedParameters)
at Microsoft.Crm.Application.ParameterFilter.ValidateParameters(Page page, EntityType pageEntityType, Boolean alwaysEnableParameterChecking, FormAdditionalAllowedParameters formAdditionalAllowedParametersTemp)
at Microsoft.Crm.Application.Controls.AppPage.ValidatePageParameters()
at Microsoft.Crm.Application.Controls.AppPage.OnInit(EventArgs e)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)</d3p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #46259303</Message>
<Timestamp>2017-01-03T13:41:22.8457002Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText i:nil="true" />
</InnerFault>
<TraceText i:nil="true" />
</OrganizationServiceFault>
The same method works when setting an out-of-the-box customer field on a form by setting the customerid, customeridname, and customeridtype parameters.
Any insights?
Thanks,
Anindit

You'll need to add myorg_customer, myorg_customername and myorg_customertype as form parameters. Your error message is Crm's bad way of saying the form parameter isn't allowed...
These are the guidelines from the Documentation:
The following guidelines apply when setting the value of a lookup on a
form using a query string argument:
For simple lookups you must set the value and the text to display in the lookup. Use the suffix “name” with the name of the attribute to set the value for the text.
Don’t use any other arguments.
For customer and owner lookups you must set the value and the name in the same way you set them for simple lookups. In addition you must use the suffix “type” to specify the type of entity. Allowable values are account, contact, systemuser, and team.
You can’t set the values for partylist or regarding lookups.
I'd make sure you are using an actual Customer Field Type, and not just a Contact Reference. I'd also make sure that it isn't a regarding or a partylist. If it is, you will need to define parameter values that don't match what CRM is looking for (add Underscores for example myorg_customer_id, myorg_customer_name and myorg_customer_type) and then write code on the onload to read these parameters and populate the correct field.

Related

Unable to remove Dynamics 365 Appointment's Optional and Required flelds value using Web API

I'm trying to remove Required and Optional Parties from an Appointment using Dynamics 365 Web API. I have tried "activityparties" entity to delete the values but no luck.
Request:
DELETE https://xxxxxx.crm.dynamics.com/api/data/v8.2/appointments(EE4C7268-81B7-E811-8143-3863BB368D98)/activitypointer_activity_parties_required(79ea68eb-4304-e911-8147-3863bb2eb450)
Response: 400 Bad Request
{
"error": {
"code": "",
"message": "Request message has unresolved parameters.",
"innererror": {
"message": "Request message has unresolved parameters.",
"type": "Microsoft.Crm.CrmHttpException",
"stacktrace": " at Microsoft.Crm.Extensibility.OData.CrmODataRoutingConvention.SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup`2 actionMap)\r\n at System.Web.OData.Routing.ODataActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
Probably a wrong Navigation property issue in request. There’s no activitypointer_activity_parties_required for sure.
Try this: (I haven’t tested it, can test in CRM REST Builder)
DELETE https://xxxxxx.crm.dynamics.com/api/data/v8.2/appointments(EE4C7268-81B7-E811-8143-3863BB368D98)/activitypointer_activity_parties(79ea68eb-4304-e911-8147-3863bb2eb450)
activitypointer_activity_parties
Update:
Looks like we cannot achieve what you want. I played around a bit, nothing worked out but found these. We cannot do anything with ActivityParty records after creation, you have to manipulate them in form script or pre-create plugin itself before stored in DB.
Entity Set Path [organization URI]/api/data/v9.0/activityparties
Base Type crmbaseentity
Display Name Activity Party
Primary Key activitypartyid
Primary Key Attribute partyidname
Operations Supported GET (RetrieveMultiple Only)
Read more
Additional Reference

An error occurred while parsing the plugin profile from file

I was connected CRM with Plugin registration tool of CRM SDK 2016 whenever i am uploading the downloaded error log file to debugger it's showing "An error occured while parsing the plugin's profile from file" could any suggest me where i am going wrong. The image is showing below:
ErrorImage
Unhandled Exception: System.ArgumentException: Unable to parse the OrganizationServiceFault.
Parameter name: serializedReport
at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)
at PluginProfiler.Library.ProfilerUtility.DeserializeProfilerReport(String assemblyFilePath, String logFilePath, Boolean isCrmDataStream)
at PluginProfiler.Library.ProfilerExecutionUtility.RetrieveReport(String logFilePath, Boolean isCrmDataStream)
at Microsoft.Crm.Tools.PluginRegistration.CommonControls.Helper.ParseReportOrShowError(Window window, FileBrowserView profilePathControl, Boolean requireReportParse, ProfilerPluginReport& report)
Inner Exception: System.InvalidOperationException: Message does not contain a serialized value.
at PluginProfiler.Library.ProfilerUtility.ExtractReportFromFault(OrganizationServiceFault fault)
at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)
Except this, when log file is downloaded it contains the below error:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected exception from plug-in (Execute): SamplePlugins.PostCreateContact: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.Detail:
<OrganizationServiceFault xmlns="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ActivityId>8998bfd9-9637-430e-8c47-998c63d1f0ee</ActivityId>
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): SamplePlugins.PostCreateContact: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.</Message>
<Timestamp>2017-11-03T11:49:06.9775603Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText>[SamplePlugins: SamplePlugins.PostCreateContact]
[e326c926-0dbe-e711-a94d-000d3af2242b: SamplePlugins.PostCreateContact: Create of contact (Profiled)]</TraceText>
</OrganizationServiceFault>
Below is my .CS file:
using Microsoft.Xrm.Sdk;
using System;
namespace SamplePlugins
{
public class PostCreateContact : IPlugin
{
ITracingService tracingService;
public void Execute(IServiceProvider serviceProvider)
{
tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Tracing Execute");
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data
//passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
try
{
// Create a task activity to follow up with the account customer in 7 days
Entity followup = new Entity("task");
followup["subject"] = "Send e-mail to the new customer.";
followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now;
followup["scheduledend"] = DateTime.Now.AddDays(2);
followup["category"] = context.PrimaryEntityName;
// Refer to the contact in the task activity.
if (context.OutputParameters.Contains("id"))
{
Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
string regardingobjectidType = "contact";
followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
}
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =
serviceFactory.CreateOrganizationService(context.UserId);
// Create the followup activity
service.Create(followup);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
I have tried by replacing the PluginProfiler.Solution.zip but the issue still exists.
Thanks.
I recommend you below steps:
Unregister the Plugin assembly & Profiler
Download latest 365 SDK
Register the assembly freshly using new PRT from latest SDK
Install Profiler & try again
Most important - The error log you shared cannot be used to debug using Profiler. It will be different

Account That Was Just Created No Longer Exists in CRM Plugin

I'm having something that is occurring intermediately (like <1% of the time), that I have no idea how it is possible. I have a plugin registered on the Post Operation of the Qualify Lead event, and have overridden the Qualify Button to execute a Qualify Lead request, setting the CreateAccount, CreateContact, and CreateOpportunity values to false. The plugin then creates the Account, Contact and oppotunity, as well as 4 other potential custom entities.
Below is the relevant code:
protected override void ExecuteInternal(ExtendedPluginContext context)
{
var createdEntities = context.GetOutputParameterValue<EntityReferenceCollection>("CreatedEntities");
var initiatingUser = context.SystemOrganizationService.GetEntity<SystemUser>(context.InitiatingUserId, u => new { u.new_RelatedEmployee, u.FullName });
var initiatingUserEntityRef = initiatingUser.ToEntityReference();
var lead = RetrieveLead(context);
CreateAccount(context, lead, initiatingUserEntityRef, createdEntities);
CreateContact(context, lead, initiatingUserEntityRef, createdEntities);
CreateLocation(context, lead, initiatingUser, createdEntities);
CreateSystemPullJob(context, lead, initiatingUserEntityRef, createdEntities);
CreateInstallJob(context, lead, initiatingUserEntityRef, createdEntities);
CreateOpportunity(context, lead, initiatingUserEntityRef, createdEntities);
CreateOpportunityProducts(context, lead, initiatingUserEntityRef, createdEntities);
UpdateLead(context, lead, initiatingUser, createdEntities);
}
private static void CreateAccount(ExtendedPluginContext context, XrmLead lead, EntityReference initiatingUser, EntityReferenceCollection createdEntities)
{
if (lead.CustomerId != null)
{
context.Trace("Account already exists for Lead. Not creating Account.");
return;
}
context.Trace("Creating Account");
var account = context.SystemOrganizationService.InitializeFrom<Account>(lead.ToEntityReference(), TargetFieldType.ValidForCreate);
account.OwnerId = initiatingUser;
account.ModifiedOnBehalfBy = initiatingUser;
account.CreatedOnBehalfBy = initiatingUser;
account.Id = context.SystemOrganizationService.CreateWithSupressDuplicateDetection(account);
lead.CustomerId = account.ToEntityReference();
createdEntities.Add(account.ToEntityReference());
}
private static void CreateInstallJob(ExtendedPluginContext context,
XrmLead lead,
EntityReference initiatingUser,
EntityReferenceCollection createdEntities)
{
context.Trace("Creating Install Job");
var job = context.SystemOrganizationService.InitializeFrom<new_job>(lead.ToEntityReference(), TargetFieldType.ValidForCreate);
job.new_jobname = "New - Install";
job.new_CustomerId = lead.CustomerId;
job.new_LocationId = GetLocation(lead, createdEntities);
job.new_JobTypeEnum = new_JobType.Installation;
job.OwnerId = initiatingUser;
job.ModifiedOnBehalfBy = initiatingUser;
job.CreatedOnBehalfBy = initiatingUser;
if (lead.new_PreviousLocationId != null)
{
// Set prerequiste job to system pull job
job.new_PrerequisiteJobId = createdEntities.First(e => e.LogicalName == job.LogicalName);
}
job.Id = context.SystemOrganizationService.CreateWithSupressDuplicateDetection(job);
createdEntities.Add(job.ToEntityReference());
}
The account is created, added to the lead.CustomerId, and then used to add the relationship to the location upon creation.
According to the stack trace, the error happens on the Creation of the Install Job, (even though the Contact already was created, and references it as it's ParentCustomerId)
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not ExistDetail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ActivityId>05e171b8-60dd-44d5-ba40-42edb79620d8</ActivityId>
<ErrorCode>-2147220969</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist</Message>
<Timestamp>2017-02-13T13:16:34.5516854Z</Timestamp>
<ExceptionSource>SdkClient</ExceptionSource>
<InnerFault>
<ActivityId>05e171b8-60dd-44d5-ba40-42edb79620d8</ActivityId>
<ErrorCode>-2147220969</ErrorCode>
<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist</Message>
<Timestamp>2017-02-13T13:16:34.5516854Z</Timestamp>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText i:nil="true" />
</InnerFault>
<OriginalException>System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at Microsoft.Crm.Extensibility.InprocessServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Crm.Sandbox.SandboxSdkListener.ExecuteInternal(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest, IExecutionContext context, String& primaryEntityName)
at Microsoft.Crm.Sandbox.SandboxSdkListener.Execute(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest)
Original SdkErrors:
</OriginalException>
<TraceText>Entered Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute()
Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute is Executing for Entity: lead, Message: QualifyLead
Creating Account
Creating Contact
Creating Location
Creating Install Job
Exception: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Account With Id = d14241a1-eef1-e611-810e-e0071b6ac161 Does Not Exist (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
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 Microsoft.Crm.Sandbox.SandboxOrganizationService.Execute(String operation, Byte[] serializedRequest, Object sandboxTraceSettingsObj)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [1]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Crm.Sandbox.ISandboxOrganizationService.Execute(String operation, Byte[] serializedRequest, Object traceSettings)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
at DLaB.Xrm.Extensions.CreateWithSupressDuplicateDetection(IOrganizationService service, Entity entity)
at Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.CreateInstallJob(ExtendedPluginContext context, Lead lead, EntityReference initiatingUser, EntityReferenceCollection createdEntities)
at Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.ExecuteInternal(ExtendedPluginContext context)
at DLaB.Xrm.Plugin.GenericPluginHandlerBase`1.ExecuteRegisteredEvent(T context)
at DLaB.Xrm.Plugin.GenericPluginHandlerBase`1.Execute(IServiceProvider serviceProvider)
**** Context Info ****
Plugin: Contoso.Xrm.Lead.Plugins.QualifyLeadLogic
* Registered Event *
Stage: PostOperation
Message: QualifyLead
Message Name: QualifyLead
Entity Logical Name:
Execute: Null
BusinessUnitId: 425821ca-d73c-e411-936d-a45d36fd8134
CorrelationId: 75366e73-bee1-4154-81a4-354a4c0ffe8f
Depth: 1
InitiatingUserId: 995e0b19-4592-e611-80f3-5065f38a4951
IsInTransaction: True
IsolationMode: 2
MessageName: QualifyLead
Mode: 0
OperationCreatedOn: 2/13/2017 1:16:32 PM
OperationId: 68ea91c1-3727-4cb4-a52d-3a632b4239e0
Organization: org8ea62131(fc3abc92-879c-4a08-8715-4156ce535b92)
OwningExtension: Contoso.Xrm.Lead.Plugins.QualifyLead: QualifyLead of lead (3d85ff0c-8705-e611-80ee-3863bb36bd38)
PrimaryEntityId: 00000000-0000-0000-0000-000000000000
PrimaryEntityName: lead
SecondaryEntityName: none
UserId: 995e0b19-4592-e611-80f3-5065f38a4951
* Input Parameters *
Param[CreateAccount]: False
Param[CreateContact]: False
Param[CreateOpportunity]: False
Param[LeadId]: EntityReference { LogicalName: lead, Name: , Id: 122448c6-edf1-e611-810e-e0071b6ac161}
Param[SourceCampaignId]: EntityReference { LogicalName: campaign, Name: , Id: 330a11ca-4687-e611-80f3-5065f38b21f2}
Param[Status]: 3
Param[OpportunityCurrencyId]:
Param[OpportunityCustomerId]:
Param[ProcessInstanceId]:
* Output Parameters *
Param[CreatedEntities] Entity Reference Collection:
EntityReference { LogicalName: account, Name: , Id: d14241a1-eef1-e611-810e-e0071b6ac161}
EntityReference { LogicalName: contact, Name: , Id: dd4241a1-eef1-e611-810e-e0071b6ac161}
EntityReference { LogicalName: new__location, Name: , Id: e64241a1-eef1-e611-810e-e0071b6ac161}
PostEntityImages: Empty
PreEntityImages: Empty
* Shared Variables *
Param[ChangedEntityTypes]: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]:
[lead, Update]
Param[Contoso.Xrm.Lead.Plugins.QualifyLeadLogic|QualifyLead|PostOperation|00000000-0000-0000-0000-000000000000]: 1
Has Parent Context: False
Stage: 40
Exiting Contoso.Xrm.Lead.Plugins.QualifyLeadLogic.Execute()
</TraceText>
</OrganizationServiceFault>
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.Crm.Sandbox.ISandboxHost.ExecuteAndReturnTraceInfo(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, String assemblyContents, Boolean returnTraceInfo)
at Microsoft.Crm.Sandbox.SandboxPlugin.Execute(SandboxClient client, SandboxCallTracker callTracker, IExecutionContext requestContext, String assemblyContents, Boolean returnTraceInfo)
at Microsoft.Crm.Sandbox.SandboxCodeUnit.Execute(IExecutionContext context)
I only see two possibilities, that the account wasn't created to begin with (seems unlikely since the contact creation was successful) or that the account is deleted after contact creation, but before Install Job Creation (but I'm not aware of anywhere that we perform deletions, and I don't think you can have a deletion of an entity in a transaction, from outside the transaction...)
Ideas?
Can you verify that the "missing account id" is the id of the account that was supposedly created?
If you query the db for this account after the error occurred, I guess it gets no hit?
Did you check "double click bug"? Issuing the QualifyLead twice "simultaneously" could of course lead to interesting effects, if there is possible SystemOrganizationService bleed between the two executions.
(Tried to make this a comment since it's technically not an answer, but it was too long.)
What happens if you comment out creation of the install job? Does everything else work correctly? Account gets created?
Another thing to check would be to query for the account after each of your create methods execute. Would help you narrow down when the account disappears.
Also, in regards to your note about deletions from outside the transaction being prevented, my understanding of how transactions work is as follows. What you suggest would be true if the delete came from something that creates its own transaction (an async plugin, say). But if the delete came from some synchronous plugin on create of contact, for example, then that plugin would also be running in the transaction. If that is true, then it would be allowed to delete the account.
Not an answer either but too long for comments
So if you're saying it a) happens intermittently and b) there is no other logic that could be deleting the account, I think the only conclusion is for some unknown timing reason, the create of installjob gets ahead of the account being visible to it. No clue why this would happen but again, to narrow things down you could catch the exception and not fail the transaction. This would at least tell you if the account actually did get created ok. If that's the case and the root cause of the timing issue can't be found, you could only try the installjob create if you are sure you can retrieve the account. All workarounds until more elimination of variables can be done.
Another thought is could it be security-related? That account does not exist message may really mean account does not exist for you. Seems odd if the plugin context user created it but maybe other security factors involved?

All oData Web APIs are broken after importing solution

using Dynamics CRM 2016 on premises, after importing an unmanaged solution in an organization (via the Web API Action ImportSolution and then PublishAllXml), all the Web APIs have stopped working, and return the following :
(example : https://MyDynamicsServer/MyOrganization/api/data/v8.0/contacts )
{
"Message": "Object reference not set to an instance of an object.",
"ExceptionMessage": "Object reference not set to an instance of an object.",
"ExceptionType": "System.NullReferenceException",
"StackTrace": " at Microsoft.OData.Edm.ExtensionMethods.AddAlternateKeyAnnotation(EdmModel model, IEdmEntityType type, IDictionary`2 alternateKey)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.DeclareAlternateKeys(EdmEntityType entityType, EntityMetadata entityMetadata, EdmModel edmModel)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.AddEntitiesToModel(ICollection`1 edmEntitySets, EdmModel model, EdmEntityContainer container)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.AddEntities(Dictionary`2 edmModels, Dictionary`2 containers, DynamicMetadataCache cache)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.InitializeEdmModels(DynamicMetadataCache cache)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataModelProvider.GetEdmModel(ModelVisibility requestedEdmType)\r\n at Microsoft.Crm.Extensibility.OData.CrmEdmModel.get_InternalEdmModel()\r\n at Microsoft.Crm.Extensibility.OData.CrmEdmModel.get_EntityContainer()\r\n at Microsoft.OData.Edm.ExtensionMethods.FindDeclaredEntitySet(IEdmModel model, String qualifiedName)\r\n at Microsoft.OData.Edm.ExtensionMethods.FindDeclaredNavigationSource(IEdmModel model, String qualifiedName)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.TryCreateSegmentForNavigationSource(String identifier, String parenthesisExpression)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.CreateFirstSegment(String segmentText)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.ParsePath(ICollection`1 segments)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathFactory.BindPath(ICollection`1 segments, ODataUriParserConfiguration configuration)\r\n at Microsoft.OData.Core.UriParser.ODataUriParser.Initialize()\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath, ODataUriResolverSetttings resolverSettings, Boolean enableUriTemplateParsing)\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)\r\n at System.Web.OData.Routing.ODataPathRouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, String parameterName, IDictionary`2 values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage request, Object constraint, String parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\r\n at System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)\r\n at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)",
"ErrorCode": 500
}
This is critical, as it makes our customizations unusable ! (and also prevents us from importing customizations automatically, as this process uses Web API)
Note that the same solution has been imported in another organization the same way without issue ...
The import of the solution through the UI still works, but that completely defeats the point of our automation pipeline ...
Has anyone encountered this issue ? Where should I look ?
(note : I have also posted this question here : https://community.dynamics.com/crm/f/117/t/206996 )
It seems your OData is not enabled or not supported. Please check via
Settings => Customizations => Developer Resources

ServiceStack : How to catch errors before written to response

I develop a Rest Service by using ServiceStack.
My model contains a DateTime property and the problem start with it.If a client post/get wrong formatted date value as string , ServiceStack fires an exception "String was not recognized as a valid DateTime."
Stack Trace:
[FormatException: String was not recognized as a valid DateTime.]
System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) +6364458
ServiceStack.Text.Common.DeserializeBuiltin`1.<GetParseFn>b__b(String value) in C:\src\ServiceStack.Text\src\ServiceStack.Text\Common\DeserializeBuiltin.cs:58
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:79
[SerializationException: KeyValueDataContractDeserializer: Error converting to type: String was not recognized as a valid DateTime.]
ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer.PopulateFromMap(Object instance, IDictionary`2 keyValuePairs) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceModel\Serialization\StringMapTypeDeserializer.cs:95
ServiceStack.ServiceHost.RestPath.CreateRequest(String pathInfo, Dictionary`2 queryStringAndFormData, Object fromInstance) in C:\src\ServiceStack\src\ServiceStack\ServiceHost\RestPath.cs:319
ServiceStack.WebHost.Endpoints.RestHandler.GetRequest(IHttpRequest httpReq, IRestPath restPath) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:104
ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName) in C:\src\ServiceStack\src\ServiceStack\WebHost.Endpoints\RestHandler.cs:80
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +625
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I know its an error and I know it must be catches but I want to implement it with my error codes and error descriptions(human friendly).
Any advice could be very helpful about how to catch an exception before its written to response itself on (DebeugMode=true) or the service fires an exception to client.
Thnx
Add your Custom Request Binder (or more advanced option is to implement IRequiresRequestStream on your DTOs) to by-pass ServiceStack's deserialization with your own.
More information about this is contained in ServiceStack's wiki documentation

Resources