Updating an entity record in CRM using Entity Framework - dynamics-crm

I been trying lately to update records in CRM 2015 Entity using the auto generated code from the SDK tool of CRM CrmSvcUtil.exe
using the code
CrmConnection con = new CrmConnection("CRM");
XrmServiceContext ctx = new XrmServiceContext(con);
var nn = ctx.TestEntity.Where(x => x.Name== "12132").FirstOrDefault();
nn.Name="test";
ctx.SaveChanges();
but all the changes done are ignored after save Changes, I noticed that the entity state of the changed record still unchanged.
When using the ctx.UpdateObject(nn); and ctx.Update(mm); the application throws the following errors:
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 13371. Element 'http://schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/7.1/Contracts:ConcurrencyBehavior'. 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 'ConcurrencyBehavior' and namespace 'http://schemas.microsoft.com/xrm/7.1/Contracts'.'. Please see InnerException for more details.
or this
EntityState must be set to null, Created (for Create message) or Changed (for Update message)
and when trying to set the entity state manually to changed I get this error
The entity is read-only and the 'EntityState' property cannot be modified. Use the context to update the entity instead.
Knowing that I can create new records using the same auto generated code by using ctx.AddObject()

You should use ctx.UpdateObject before calling ctx.SaveChanges().
UpdateRequest.ConcurrencyBehavior was introduced in CRM 2015 Update 1. It appears to me that you have a mismatch between the version of CRM and the version of CrmSvcUtil you are using. You must be using a newer version of the SDK Tools.
Since you are using the RTM version of CRM you can download and use the corresponding RTM version of the CRM 2015 SDK core tools (version 7.0.1). After re-generating your context with CrmSvcUtil from that version you should no longer see any errors related to UpdateRequest.ConcurrencyBehavior.

Related

Bridge RESO OData API

Im trying to use the OData Connected Service in Visual Studio to connect to a OData Feed in Bridge (RESO Feed).
However, If I try and pull the metadata directly from a URL, it has errors Adding OData Connected Service to the project failed: Could not get CLR type name for EDM type 'memberMediaEnums.ResourceName'
So I went ahead and downloaded the XML file and tweaked it to get rid of the errors and warnings. This includes Removing Entity references with no parents and removing attributes that were not supported like Precision.
Once its all loaded and the reference file is created I tried pulling data. The endpoint works and data is retrieved, but it is not thrown into the object as i would expect.
IEnumerable<Property> properties= await context.Property.ExecuteAsync();
foreach (var property in properties) //Errors trying to make a property
{
Console.WriteLine("{0} {1}", property.YearBuilt, property.ListPrice);
}
When I try and loop over the object I get this error:
The context URI 'https://api.bridgedataoutput.com/api/v2/OData/imls2/$metadata#Property' is not valid for the expected payload kind 'Resource'.
Where I am confused, is in the name Resource There is no object or entity in the Reference file or in the XML scheme that references that word. I'm not sure if its coming from OData services or the reference file it created. The call stack does not contain anything but the exact line of the loop.
Any insights would be helpful but i know its a long shot. Let me know if I need to provide more details.
Thanks

EWS - Can't load FirstDayOfWeek property of Appointment.Recurrence

I can successfully load the Recurrence property for an Appointment using EWS (connecting to an Office 365 server), but when I try to access the FirstDayOfWeek property of a WeeklyPattern I always get the following exception:
FirstDayOfWeek threw an exception of type 'Microsoft.Exchange.WebServices.Data.ServiceValidationException
All other properties of the WeeklyPattern seem to load happily (see below) except this.
Is it possibly down to the requested server version I'm using when creating the ExchangeService object?
thisConnection = New ExchangeService(ExchangeVersion.Exchange2010)
I've checked the AppointmentSchema properties available when loading the Appointment, and other than AppointmentSchema.Recurrence (which I am obviously using) there doesn't seem to be anything else I'm missing there.
The FirstDayOfWeek property is not available in the exchange version you have referenced.
The property was introduced in Exchange Server 2010 Service Pack 1
(SP1).
See reference in the Remarks section of this article
You would need to install that service pack and change your code to the below:
thisConnection = New ExchangeService(ExchangeVersion.Exchange2010_SP1)

Server Error with the griffin.mvccontrib package in asp.net

In order to be able to translate my data annotations in my model with a resource file, I saw that many people recommend the solution offered by jgauffin.
However, when I follow the localization tutorial my project cannot launch.
The problematic code is this one, which is supposed to go in the Global.asax.cs file:
ModelValidatorProviders.Providers.Add(
new LocalizedModelValidatorProvider(stringProvider)
);
It says that the LocalizedModelValidatorProvider constructor does not take any arguments, which is also shown by other tutorials.
But when I change the line like this:
ModelValidatorProviders.Providers.Add(
new LocalizedModelValidatorProvider()
);
I get the following error in the browser:
Attempted to access an element as a type incompatible with the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.
The griffin.mvccontrib packages were installed with NuGet under Visual Studio 2012. Any idea what I am doing wrong ?
You might find this link helpful
Here is how I did the registration in the above link:
ResourceStringProvider myResouceFile = new ResourceStringProvider(ModelsResources.ResourceManager);
//ModelsResources is my resource file generated class
GriffinStringsProvider griffinStringsProvider = new GriffinStringsProvider(myResouceFile);
ValidationMessageProviders.Clear();
ValidationMessageProviders.Add(griffinStringsProvider);
ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(myResouceFile);
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
Make sure you are including the right assemblies
using System.Resources;
using Griffin.MvcContrib.Localization;
using Griffin.MvcContrib.Localization.ValidationMessages;
Also the assembly for your Resource file.

EntityKey properties of type “Geography” not supported. Entity Framework 5, VS 2012 – Database First

Created a SQL Server 2008 database and table with a property called “Coordinates” of type “geography”. In VS 2012 created a project, added references to Microsoft.SqlServer.Types and EF V5. Then, using the ADO.NET Entity Data Model wizard generated the edmx. When I compile in VS 2012 I get the following error:
Error 4 Error 129: The property 'Coordinates' in EntityType 'DBModel.GeoDestination' is not valid. EntityKey properties that are of type 'Geography' are currently not supported.
Many of the samples on the web are “code first” examples that use the type “DbGeography” as a type in their c# code and generate the database from the code resulting in a table with a property of type “geography”.
How do I do this database first and fix up the type? It does not appear that “DBGeography” is in the drop down list of types when using the “Table Mapping” view.
Using EF 5, NET 4.5, VS 2012 SP 1, SQL Server Types
I figured this out. Looks like a bug in the wizard. If the table in SQL does not have a primary key, the wizard automatically generates a key(s) in the resulting EF model. It appears random, sometimes one key is generated and sometimes it makes several properties keys. A Geography data type cannot be a key. It was not a key in the table, but the wizard made it a key.
Hope this response helps others.

Web Api and Odata without Entity Framework

I am having trouble getting OData to work with Asp.Net Web Api when the underlying data is NOT coming from Entity Framework.
I am using the latest OData Nuget package (Microsoft ASP.NET Web API OData 0.2.0-alpha release) but when I attempt to pass an OData query (say $top=10) I receive the error:
The given key was not present in the dictionary
If I don't send an OData query I can call the method just fine. The other methods in the same Web Api project that use Entity Framework work fine with OData queries. The one's that don't work are using Subsonic ORM to query an underlying AS400 data source. It returns an IQueryable. This worked just fine before the VS 2012 and .NET 4.5 RTM was released and OData was moved into a separate package. (i.e. worked with beta and RC versions of VS2012 and .NET 4.5)
Any ideas would be appreciated.
I guess this issue is caused by stable ordering, which doesn't work well with the underlying query provider. Could you put the call stack of the error to confirm it?
One big change with OData query composition in this release is that it ensures stable ordering before taking top items. The reason to do that is user may have random data source which makes return data keep changing.
The way web api odata package does is to add OrderyBy [Keys] query before executing top. Or if there is no key defined in the model (Keys are ID, EntityID, or [Key] attributed property), it will use all the primitive properties in the model to order.
If you can make sure that the data source will always return data with stable ordering, you can turn off this feature by code:
[Queryable(EnsureStableOrdering = false)]

Resources