How do I update a custom entity in crm 2011 online plugin code? - dynamics-crm

Can anyone tell me why this code doesn't work in an 2011 online plugin? What I'm trying to do is update a collection of custom entities. It throws the following error on the service.Execute(...). Another way to achieve this much appreciated...
Unexpected exception from plug-in (Execute): : System.InvalidCastException: Specified cast is not valid.
EntityCollection CustomEntitiesNeedingSync = service.RetrieveMultiple(RelevantCustomEntitiesQuery);
foreach (Entity currentCustomRecord in CustomEntitiesNeedingSync.Entities)
{
UpdateRequest theUpdateRequest = new UpdateRequest();
theUpdateRequest.Target = currentCustomRecord;
service.Execute(currentCustomRecord);
}

You have to execute the request - not the record.
foreach (Entity currentCustomRecord in CustomEntitiesNeedingSync.Entities)
{
UpdateRequest theUpdateRequest = new UpdateRequest();
theUpdateRequest.Target = currentCustomRecord;
service.Execute(theUpdateRequest);
}

Related

FaultException when using ExecuteTransactionRequest (CRM 2015)

I'm doing a bit of a technical investigation into the ExecuteTransactionRequest. It's not something I've ever used before so I knocked up a very quick experiment just to see how it works. However, when sending off the request the OrganizationService is throwing back a FaultException (below). What I believe is happening is that my version of CRM doesn't support that OrganizationRequest. Although I'm pretty sure I have the right assemblies and version.
Can anyone please shed some light on what I'm missing?
CRM Deployment Version: 7.0.1.129
Organization Version: 7.0.2.53
Microsoft.Xrm Assembly Version: 7.0.0.0 (Also happened with 8.0.0.0)
An unhandled exception of type 'System.ServiceModel.FaultException'
occurred in Microsoft.Xrm.Sdk.dll
Additional information: The formatter threw an exception while trying
to deserialize the message: There was an error while trying to
deserialize parameter
http://schemas.microsoft.com/xrm/2011/Contracts/Services:request. The
InnerException message was 'Error in line 1 position 451. Element
'http://schemas.microsoft.com/xrm/2011/Contracts/Services:request'
contains data from a type that maps to the name
'http://schemas.microsoft.com/xrm/2011/Contracts:ExecuteTransactionRequest'.
The deserializer has no knowledge of any type that maps to this name.
Consider changing the implementation of the ResolveName method on your
DataContractResolver to return a non-null value for name
'ExecuteTransactionRequest' and namespace
'http://schemas.microsoft.com/xrm/2011/Contracts'.'. Please see
InnerException for more details.
CrmConnection connection = CrmConnection.Parse(GetCrmConnectionString("unmanaged"));
IOrganizationService orgService = new OrganizationService(connection);
ExecuteTransactionRequest transactionRequest = new ExecuteTransactionRequest()
{
ReturnResponses = true,
Requests = new OrganizationRequestCollection()
};
Entity newContact = new Entity("contact");
newContact["firstname"] = "Stack";
newContact["lastname"] = "Overflow";
CreateRequest createRequest = new CreateRequest()
{
Target = newContact
};
transactionRequest.Requests.Add(createRequest);
ExecuteTransactionResponse transactionResponse = (ExecuteTransactionResponse)orgService.Execute(transactionRequest);
Update
Quick look at your code, looked like it was because of the CreateRequest not being added to the collection. After your comments and double checking the crm organization version, you are on CRM 2015 (not on update 1). ExecuteTransactionRequest is only supported by CRM 2015 update 1 (version 7.1.XXX) and up (version 8.0.XXX) organizations. So unfortunately, your query won't work until at least the 2015 update is applied to the organization.
You did not add your create request to the ExecuteTransactionRequest - Requests collection. An empty request collection is causing the exceptions most likely.
ExecuteTransactionRequest transactionRequest = new ExecuteTransactionRequest()
{
ReturnResponses = true,
Requests = new OrganizationRequestCollection()
};
Entity newContact = new Entity("contact");
newContact["firstname"] = "Stack";
newContact["lastname"] = "Overflow";
CreateRequest createRequest = new CreateRequest()
{
Target = newContact
};
transactionRequest.Requests.Add(createRequest); //missing
ExecuteTransactionResponse transactionResponse = (ExecuteTransactionResponse)orgService.Execute(transactionRequest);

Breeze filtering not working

I am using breeze and the filter does not work.
var EntityQuery = breeze.EntityQuery;
var manager = configureBreezeManager("xxx");
function configureBreezeManager(param) {
breeze.NamingConvention.camelCase.setAsDefault();
var mgr = new breeze.EntityManager(param);
model.configureMetadataStore(mgr.metadataStore);
return mgr;
}
And my query query
var query = EntityQuery.from('GetStudents').where("Id", "==", "xxx");
return manager.executeQuery(query)
The filter is ignore and all results are returned. my get student returns an IQueryable of all students.
public IQueryable<Students> GetStudents(){
return context.Students;
}
Is there something up there I am doing wrong or should I look elsewhere?
EDIT
I realize that my controller is missing the property [BreezeController]. But when I include that, me metadata path is not found giving me an error (error 500 below) when trying to load it. The matadata loads fine without this property on the controller, but filtering does not work. Is this related?
"Could not load file or assembly 'System.Web.Http.OData, ... or one of its dependencies. The system cannot find the file specified."
Your issue might be that you have specified a 'camelCase' namingConvention, but your query is for 'Id' instead of 'id'. i.e. try:
var query = EntityQuery.from('GetStudents').where("id", "==", "xxx");
return manager.executeQuery(query)
I was missing the [BreezeController] and after adding it, I received the error Could not load file or assembly System.Web.Http.OData, Version=4.0.0.0 and was able to solve it by runing Install-Package Microsoft.AspNet.WebApi.OData in the package manager

Dynamics AX 2009 : can't save new Customer via webservice using AxdCustomer Class

CustomerService CustService = new CustomerService();
try
{
CustService.Credentials = new NetworkCredential("xxx", "xxx", "xxx");
AxdCustomer customer = new AxdCustomer();
AxdEntity_CustTable[] table = new AxdEntity_CustTable[1];
AxdEntity_CustTable test = new AxdEntity_CustTable();
test.AccountNum = TextBox1.Text;
test.Name = TextBox1.Text;
test.CustGroup = DropDownList1.SelectedItem.Value;
table[0] = test;
customer.CustTable = table;
CustService.create(customer);
}
catch (Exception ex)
{
err.Visible = true;
lblerr.Text = ex.Message;
}
I am new to Dynamics AX. I'm trying to create a customer which is actually created by consuming a webservice from the web . the above code snippet is the code for that, but it's giving an exception as :
Request Failed. See the Exception Log for details.
I'm not even getting the actual reason why it's not getting created. How to create a customer in dynamics AX 2009 sp1?
Note: CustService is the CustomerService object for the class in CustomerSvc namespace (it is the webservice reference to the CustomerService webservice in Dynamics).
Have a look at the event log in the server where there webservice and the AOS is hosted on.
You may get half a clue from there.
Also have a look at the exception log in AX which you can get from
Basic -> Periodic -> Application Integration framework -> Exceptions
Once you get the error details then you may figure out the problem otherwise post them here and I an have a further look at what the problem might be.

LINQ CRM 2011 Update - Create

I notice the the CRM moderator David Jennaway on the technet forum states that you can't use LINQ to update/Create records in CRM 2011 see here http://social.microsoft.com/Forums/en-IE/crmdevelopment/thread/682a7be2-1c07-497e-8f58-cea55c298062
But I have seen a few threads that make it seem as if it should work. Here is my attempt which doesn't work. Any ideas why not?
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
EntityState state = new EntityState();
state = EntityState.Changed;
var counter = from c in orgContext.CreateQuery<pcx_entitycounter>()
where c.pcx_name.Contains("pcx_candidate")
select new pcx_entitycounter
{Id = c.Id,
pcx_name = c.pcx_name, pcx_Sequence = c.pcx_Sequence, pcx_Prefix = c.pcx_Prefix
};
foreach (var c in counter)
{
string prefix = c.pcx_Prefix.ToString(); ;
string sequence = c.pcx_Sequence.ToString();
c.pcx_Sequence = c.pcx_Sequence + 1;
c.EntityState = state;
**service.Update(c);** //FAILS HERE
}
In my experience, it's been difficult-to-impossible to retrieve an entity from the Context, update it, then use the Service to save the changes. It has caused me headaches figuring it out!
Since your retrieval code uses a query from the Context, all of those entities should be attached to the Context and their states are being tracked. Thus you need to use the Context's method for updating:
foreach (var c in counter) {
string prefix = c.pcx_Prefix.ToString(); ;
string sequence = c.pcx_Sequence.ToString();
c.pcx_Sequence = c.pcx_Sequence + 1;
// Use the Context to save changes
orgContext.UpdateObject(c);
orgContext.SaveChanges();
}
Since a lot of my code will retrieve entities in different ways (i.e. Service or Context) depending on the situation, I have developed a simple method that knows how to update the entity correctly. To expand on your example, you might have an update method that looks like:
public void UpdatePcxEntityCounter(pcx_entitycounter c) {
if (!orgContext.IsAttached(c)) {
service.Update(c);
}
else {
orgContext.UpdateObject(c);
orgContext.SaveChanges();
}
}
This assumes both orgContext and service are available at a scope above that of the method. Otherwise, they'd have to be passed as additional parameters.
Without seeing the difficult its difficult to discern what the issue is but have you tried using orgContext.UpdateObject(c); before doing the update step? Also, not sure why you are assigning the prefix and sequence to local variables within your loop since they don't appear to be being used. Its possible that you are getting a SOAP Exception or something for assigning values that don't work. Do you have any plugins registered on the entity?
See the following links for possible resolutions -
How to update a CRM 2011 Entity using LINQ in a Plugin?
http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/7ae89b3b-6eca-4876-9513-042739fa432a

Creation of Dynamic Entities in MS CRM 4.0

I am trying to create a new contact using Dynamic Entity. The sample i found in CRM SDK had this code.
// Set the properties of the contact using property objects.
StringProperty firstname = new StringProperty();
firstname.Name = "firstname";
firstname.Value = "Jesper";
StringProperty lastname = new StringProperty();
lastname.Name = "lastname";
lastname.Value = "Aaberg";
// Create the DynamicEntity object.
DynamicEntity contactEntity = new DynamicEntity();
// Set the name of the entity type.
contactEntity.Name = EntityName.contact.ToString();
// Set the properties of the contact.
contactEntity.Properties = new Property[] {firstname, lastname};
In my code i have the following implementation.
StringProperty sp_Field1 = new StringProperty("Field1","Value1");
StringProperty sp_Field2 = new StringProperty("Field2","Value1");
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Create the DynamicEntity object.
DynamicEntity contactEntity = new DynamicEntity();
// Set the name of the entity type.
contactEntity.Name = EntityName.contact.ToString();
// Set the properties of the contact.
contactEntity.Properties = new Property[] {sp_Field1,sp_Field2};
I don't see much differences in the code. In the examples i found in the internet i have the same implementation as i found in SDK. But if i run the same i get the following error
CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.StringProperty' to 'Microsoft.Crm.Sdk.PropertyCollection'
I tried created a new variable of type PropertyCollection(one that belongs in mscrm namespace) and added the stringpropertys into that and passed it to the entity.
Microsoft.Crm.Sdk.PropertyCollection propTest = new Microsoft.Crm.Sdk.PropertyCollection();
propTest.Add(sp_SSNNo);
propTest.Add(sp_FirstName);
contactEntity.Properties = new Property[] {propTest};
This gave me the following error
CS0029: Cannot implicitly convert type 'Microsoft.Crm.Sdk.PropertyCollection' to 'Microsoft.Crm.Sdk.Property'
I am sure its a minor typecasting error but i am not able to figure out where the error is. And moreover, even if it was a typecasting error why is it working for all the samples given in the internet and not for me. I tried getting the code sample to run but i am encountering the same conversion error. Please let me know if you need more info on this, any help on this would be appreciated.
Here is an article from Microsoft that makes an attempt to discuss this topic:
http://community.dynamics.com/blogs/cscrmblog/archive/2008/06/23/web-services-amp-dlls-or-what-s-up-with-all-the-duplicate-classes.aspx
This is not a bug that you are running into but more of a difference in design between the way the two assemblies work and what they are designed to do.
If you want to continue to use the Microsoft.Crm.Sdk.dll you should be able to accomplish your goal with the following...
StringProperty sp_Field1 = new StringProperty("Field1","Value1");
StringProperty sp_Field2 = new StringProperty("Field2","Value1");
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Create the DynamicEntity object.
DynamicEntity contactEntity = new DynamicEntity();
// Set the name of the entity type.
contactEntity.Name = EntityName.contact.ToString();
// Set the properties of the contact.
PropertyCollection properties = new PropertyCollection();
properties.Add(sp_Field1);
contactEntity.Properties = properties;
Thanks SaaS Developer, that code is working fine now. One more way of doing it would be to directly add the StringProperty to the entity property collection.
contactEntity.Properties.Add(sp_SSNNo);
Thanks again for replying :)
I believe the issue is that you are referencing the dynamic entity class in the Microsoft.Crm.Sdk assembly. The sample in the SDK is using a reference to the CRM web service. This can get confusing as both assemblies contain many of the same types, however they are different.

Resources