Answered by:
Retrieving data from a custom entity

Question
-
We are trying to retrieve data from a custom CRM 4.0 entity named "ugl_teammember" using c#. We follow the same approach as shown in the code below with a standard entity and the code works just fine. we have two different errors occurring, depending on whose machine runs the app, One error is: the entitiy with the name = '' was not found in the metadatacache. the other error we receive is that it cannot find the column we specify. Below is a chuck of our code. Any assistance you can provide would be greatly appreciated!
Craig
CRMWebService.
cols.Attributes =
CRMWebService.
condition2.AttributeName =
condition2.Operator = CRMWebService.
condition2.Values =
condition2.Values[0] = 0;
ConditionExpression condition2 = new CRMWebService.ConditionExpression(); "statecode"; ConditionOperator.Equal; new object[1];//0 = Active, 1 = Inactive
CRMWebService.
filter.Conditions =
CRMWebService.
query.ColumnSet = cols;
query.Criteria = filter;
CRMWebService.
{
teamMembers = service.RetrieveMultiple(query); //Error occurs here
}
// Retrieve the TeamMembers.QueryExpression query = new CRMWebService.QueryExpression(); query.EntityName = "Ugl_teammember"; BusinessEntityCollection teamMembers = null; tryFilterExpression filter = new CRMWebService.FilterExpression(); new CRMWebService.ConditionExpression[] { condition2 }; // Create the QueryExpression object.new string[] { "Ugl_teammemberId" }; // Create the ConditionExpression.ColumnSet cols = new CRMWebService.ColumnSet(); // Set the properties of the ColumnSet.Friday, January 21, 2011 10:35 PM
Answers
-
The cast is failing, but because you used the "as" keyword , instead of "(CrmWebService.ugl_teammember)be", the conversion results in a null pointer, rather than generating the InvalidCastException you would get with the later method. I think your approach is insufficient, because what you're doing with the object, instead of immediately casting from the BusinessEntities collection as a stronger CRMWebService.ugl_teammember type, you've "downgraded" it to BusinessEntity/DynamicEntity both by your query format and your cast ("BusinessEntity be in ..."). At this stage, it cannot be forced upstream, without a great deal of work . I think your remedial options are as follows:
- Use the RetrieveMultiple method to return records as native CRMWebService.ugl_teammember instances, and refrain from using the Execute method in conjunction with RetrieveMultipleRequest (with "ReturnDynamicEntities" flagged as true ). Then cast the elements out of BusinessEntities as native CRMWebService.ugl_teammember types; or
- Cast elements out of BusinessEntities as DynamicEntity and use the Properties collection within each instance to access the "ugl_teammemberid" attribute/value; or
- Cast elements out of BusinessEntities as DynamicEntity and up-convert the DynamicEntity to the stronger CRMWebService.ugl_teammember type forcibly .
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.- Marked as answer by DavidJennawayMVP, Moderator Thursday, February 24, 2011 6:51 PM
Wednesday, January 26, 2011 7:52 PMModerator
All replies
-
You say the code is running on different machines, am I to assume this is a desktop application you have developed? Or is the code deployed to the server, and being run through a web-page, or Plugin?
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.- Proposed as answer by meenakshi Patnala Wednesday, February 27, 2013 10:14 AM
Friday, January 21, 2011 10:50 PMModerator -
No, another developer in the organization - when he runs the code (through the IDE) on his machine he receives the error message that a column is not there. When I run the code on my machine (also through the IDE), I receive the other error. We both are going to the same DB, and we are both hitting the same CRM web service.
Craig
Craig BrowderMonday, January 24, 2011 2:33 PM -
Were the web-references for the .Net project in both places updated after the entity was customized and published? I mention this because you're not using DynamicEntities, which would be necessary if you were using the DLLs instead.
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Monday, January 24, 2011 5:14 PMModerator -
Yes, the web references were updated after the entity was customized and published. I actually updated them again after getting your message to make sure that the references were updated. Any "out of the box" entiry (opportunity, account, etc.), the code is working just fine. The error we are experiencing is only with custom entities.
Craig BrowderMonday, January 24, 2011 5:25 PM -
And is the account being used to connect to CRM's Web Services the same on both systems?
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Monday, January 24, 2011 5:31 PMModerator -
Yes, the account is the same on both systems.
Craig BrowderMonday, January 24, 2011 9:31 PM -
Ok. Then with all the simple possibilities out of the way, it's time for you to turn on tracing at the CRM platform and get some descriptive error messages. Review the forum guidelines for pointers on how to achieve this.
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Monday, January 24, 2011 11:47 PMModerator -
Make sure you were not using both.
For example sdk dll's and web services.
Tuesday, January 25, 2011 12:31 AM -
I have the trace files... is there something in particular i should be looking for?
Craig BrowderTuesday, January 25, 2011 2:29 PM -
Use the Trace Log Viewer to sift out error messages that occurred when you reproduced the problem, and post them here.
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Tuesday, January 25, 2011 5:31 PMModerator -
Heres one of the errors from the log viewer:
at CompositeSoapExtensionExceptionHandler.Handle(Stream to, Stream from, Exception exception)
at CrmAuthenticationSoapExtensionBase.ProcessMessage(SoapMessage message)
at SoapMessage.RunExtensions(SoapExtension[] extensions, Boolean throwOnException)
at SoapServerProtocol.WriteException(Exception e, Stream outputStream)
at WebServiceHandler.WriteException(Exception e)
at WebServiceHandler.Invoke()
at WebServiceHandler.CoreProcessRequest()
at SyncSessionlessHandler.ProcessRequest(HttpContext context)
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at ApplicationStepManager.ResumeSteps(Exception error)
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
>CrmSoapExtension detected CrmException:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Microsoft.Crm.Metadata.EntityMetadataNotFoundException: The entity with a name = 'Ugl_teammember' was not found in the MetadataCache.
at Microsoft.Crm.Metadata.DynamicMetadataCache.GetEntity(String entityName, NameMappingType mapping)
at Microsoft.Crm.Sdk.CrmServiceInternal.VerifyAndRetrieveEntityForCategoryMessage(String messageName, String categoryName, String namespaceName, String entityName)
at Microsoft.Crm.Sdk.CrmServiceInternal.RetrieveMultiple(String namespaceName, QueryBase query, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.Crm2007.CrmService.RetrieveMultiple(QueryBase query)
--- End of inner exception stack trace ---
Craig BrowderTuesday, January 25, 2011 6:50 PM -
I think capitalization matters, so if (as with your first post) the entity's schema name is "ugl_teammember", you may want to match capitalization in your project. However, that may not be the case. Can I ask how the custom entity was created in the CRM deployment? Was it constructed through the customization interface, or did you import it from another deployment/environment?
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Tuesday, January 25, 2011 8:12 PMModerator -
Also, what is the latest Rollup Update you have applied to CRM?
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Tuesday, January 25, 2011 8:18 PMModerator -
We have already matched the capitalization, and that didn't correct the issue.
It was originally created through the customization interface and then the whole environment was imported using the Import function of the Deployment Manager utility to create a better mirror image of production.
Craig BrowderTuesday, January 25, 2011 8:26 PM -
The only mention of errors of this type that I can find, as I'm sure you also experienced, relate to the import of entities--but occurring during the import, and not afterward. That said, I suspect that the Metadata Cache is somehow damaged or incomplete. I would recommend installing the latest Update Rollup and restarting IIS (though you might try the IIS restart first). The cache is assembled during the first execution of CRM's code, which is why the first page load after a restart is the longest. This might help things. Additionally, you could try exporting any records you have made for the entity, deleting it, and either importing it again or creating it from scratch (I would do this if the import doesn't seem to help the situation)--you could then import the exported records into the newly established entity.
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.Tuesday, January 25, 2011 8:42 PMModerator -
Hi,
Try this code, you might have to edit some minor stuff since I edited it to suit your needs in a text editor.
Verify the exact name of the entity by editing it in crm and copying the name from the name field there, this query returns dynamic entities in the response.
/// <summary>
/// Function that handles querying the crm system with the sent in data.
/// </summary>
/// <param name="crmService">CrmService object used to send the query.</param>
/// <returns>Collection of found objects as dynamic entity</returns>
public RetrieveMultipleResponse QueryCrmDynamic(CrmService crmService)
{
//Condition to add to the search that the record must be active.
ConditionExpression _conditionStatus = new ConditionExpression();
_conditionStatus.AttributeName = "statecode";
_conditionStatus.Operator = ConditionOperator.Equal;
_conditionStatus.Values = new object[] { 0 };//Create the query expression
QueryExpression expression = new QueryExpression();
//Set the entity name
expression.EntityName = "ugl_teammemberid"; //Verify the correct name by editing the entity and copy the name direct.
//Add the condition to the query expression
expression.Criteria.Conditions.Add(_conditionStatus);
//Define the columns returned from the search.
expression.ColumnSet = new AllColumns();//Create a retrieve request.
RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
retrieveMultipleRequest.Query = expression;
//Make sure to return dynamic entities.
retrieveMultipleRequest.ReturnDynamicEntities = true;//Execute the request.
RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)crmService.Execute(retrieveMultipleRequest);
//Return the multiple request response.
return retrieveMultipleResponse;
}
Halldór JóhannssonWednesday, January 26, 2011 9:59 AM -
This code seems to work a little bit better. However, I still receive an error when i try to loop through the items in the BusinessEntity Collection... here is the reworked code...
try { //Condition to add to the search that the record must be active. ConditionExpression _conditionStatus = new ConditionExpression(); _conditionStatus.AttributeName = "statecode"; _conditionStatus.Operator = ConditionOperator.Equal; _conditionStatus.Values = new object[] { 0 }; //Create the query expression QueryExpression expression = new QueryExpression(); //Set the entity name expression.EntityName = "ugl_teammember"; //Verify the correct name by editing the entity and copy the name direct. //Add the condition to the query expression CRMWebService.FilterExpression filter = new CRMWebService.FilterExpression(); filter.Conditions = new CRMWebService.ConditionExpression[] { _conditionStatus }; //expression.Criteria.Conditions.Add(_conditionStatus); //Define the columns returned from the search. expression.ColumnSet = new AllColumns(); //Create a retrieve request. RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest(); retrieveMultipleRequest.Query = expression; //Make sure to return dynamic entities. retrieveMultipleRequest.ReturnDynamicEntities = true; //Execute the request. retrieveMultipleResponse = (RetrieveMultipleResponse)service.Execute(retrieveMultipleRequest); foreach (CRMWebService.ugl_teammember teamMember in retrieveMultipleResponse.BusinessEntityCollection.BusinessEntities) { try { } catch (Exception ex) { MessageBox.Show(ex.Message); } } } catch (Exception ex) { MessageBox.Show(ex.Message); }
Now, the exception i get is: Unable to cast object of type 'CRM_Maintenance.CRMWebService.DynamicEntity' to type 'CRM_Maintenance.CRMWebService.ugl_teammember'. When i look at the properties of the BusinessEntityCollection.BusinessEntity, they are all of type "ugl_teammember"... Any idea why the cast is failing?
Craig BrowderWednesday, January 26, 2011 2:19 PM -
Hello,
You can create, update, delete or retrieve multiple entities, using the CRM Web Service, from JavaScript directly too (SOAP based).
Here's on example of how to create a new entity record from JavaScript: http://bizforward.blogspot.com/2011/01/call-crm-service-function.html .
The RetrieveMultiple method is similar, I'll post an article about it as soon as possible.
Thank you,
Cornel Croitoriu
http://bizforward.blogspot.com
- Edited by Cornel Croitoriu Friday, January 28, 2011 9:18 PM
Wednesday, January 26, 2011 5:41 PM -
Cornel,
Thanks for the reply. I am familiar with creating updaing, etc with theCRM web service. What i am not familiar with is working with the DynamicBusinessEntities through the RetrieveMultipleRequest. I tried the above code and the following:
retrieveMultipleResponse = (RetrieveMultipleResponse)service.Execute(retrieveMultipleRequest); foreach (BusinessEntity be in retrieveMultipleResponse.BusinessEntityCollection.BusinessEntities) { try { Key key = new Key(); key = (be as CRMWebService.ugl_teammember).ugl_teammemberid; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
The count of retrieveMultipleResponse.BusinessEntityCollection.BusinessEntities is 614, but when i try to do the cast (key = (be
as CRMWebService.ugl_teammember).ugl_teammemberid;) the error is that be is null, and im not sure why...
Craig BrowderWednesday, January 26, 2011 6:55 PM -
Try debugging the code, to see the object type of the returned object. Maybe you need to do some explicit casting/boxing. But first of all, debug it to find that out. Also, you can check this thread http://social.microsoft.com/Forums/en/crmdevelopment/thread/03d48dc7-e522-4f6e-9de6-978fb613bc9c for a similar problem.
Cornel Croitoriu - Senior Software Developer - http://bizforward.blogspot.com- Edited by Cornel Croitoriu Friday, January 28, 2011 9:18 PM
Wednesday, January 26, 2011 6:58 PM -
There are 614 objects inside the BusinessEntities, the first element is a "DynamicEntity" of type "ugl_teammember". "be" is showing as a DynamicEntity, but the statement "(be as CRMWebService.ugl_teammember)" is returning null, causing the exception... I read through the article that you attached to your last post. It stated that you can cast the items in the BusinessEntities collection as DynamicEntities, but that led to other erros when I tried to cast the object to the custom object type.
Craig BrowderWednesday, January 26, 2011 7:46 PM -
does your exception have an inner exception? if yes, what does it say?
Cornel Croitoriu - Senior Software Developer - http://bizforward.blogspot.com- Edited by Cornel Croitoriu Friday, January 28, 2011 9:18 PM
Wednesday, January 26, 2011 7:49 PM -
The cast is failing, but because you used the "as" keyword , instead of "(CrmWebService.ugl_teammember)be", the conversion results in a null pointer, rather than generating the InvalidCastException you would get with the later method. I think your approach is insufficient, because what you're doing with the object, instead of immediately casting from the BusinessEntities collection as a stronger CRMWebService.ugl_teammember type, you've "downgraded" it to BusinessEntity/DynamicEntity both by your query format and your cast ("BusinessEntity be in ..."). At this stage, it cannot be forced upstream, without a great deal of work . I think your remedial options are as follows:
- Use the RetrieveMultiple method to return records as native CRMWebService.ugl_teammember instances, and refrain from using the Execute method in conjunction with RetrieveMultipleRequest (with "ReturnDynamicEntities" flagged as true ). Then cast the elements out of BusinessEntities as native CRMWebService.ugl_teammember types; or
- Cast elements out of BusinessEntities as DynamicEntity and use the Properties collection within each instance to access the "ugl_teammemberid" attribute/value; or
- Cast elements out of BusinessEntities as DynamicEntity and up-convert the DynamicEntity to the stronger CRMWebService.ugl_teammember type forcibly .
Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.- Marked as answer by DavidJennawayMVP, Moderator Thursday, February 24, 2011 6:51 PM
Wednesday, January 26, 2011 7:52 PMModerator -
No, the innerexecption is null..
Craig BrowderThursday, January 27, 2011 2:41 PM -
Dave,
Thanks for taking the time to put together such a detailed response, with very useful links! I will begin trying out some of the stuff you mention and let you know of the results.
Craig
Craig BrowderThursday, January 27, 2011 2:50 PM