简体   繁体   中英

Calling Dynamics Web API with Entity metadata early binding

I would like to consume my organizations dynamics oData endpoint but with early bound classes. However, there are a lot of early bound tools out there and I wanted to know which one provides the best developer experience/least resistance?

For example, there is this one:

https://github.com/daryllabar/DLaB.Xrm.XrmToolBoxTools https://github.com/yagasoft/DynamicsCrm-CodeGenerator

and so on. Is there a developer preference/method out there?

Early bound classes are for use with the Organization Service which is a SOAP service. The normal way to generate those classes is using CrmSvcUtil .

OData can be used in Organization Data Service or Web API, but those don't have Early Bound classes.

Further reading: Introducing the Microsoft Dynamics 365 web services

It's not impossible to use with standard SOAP Early bound class. We just have to be creative. If we work just with basic attributes (fields, not relationships, ecc) it seems possible. For example. for create and update, OData will not accept the entire early bounded class, just pass the attibutes:

    class Program
{
    static void Main(string[] args)
    {
        string token = System.Threading.Tasks.Task.Run(() => GetToken()).Result;
        CRMWebAPI dynamicsWebAPI = new CRMWebAPI("https:/ORG.api.crm4.dynamics.com/api/data/v9.1/",
                token);


        CRMGetListOptions listOptions = new CRMGetListOptions
        {
            Select = new string[] { "EntitySetName" },
            Filter = "LogicalName eq 'contact'"
        };

        dynamic entityDefinitions = dynamicsWebAPI.GetList<ExpandoObject>("EntityDefinitions", listOptions).Result;

        Contact contact = new Contact
        {
            FirstName = "Felipe",
            LastName = "Test",
            MobilePhone = "38421254"
        };

        dynamic ret = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.Create(entityDefinitions.List[0].EntitySetName, KeyPairValueToObject(contact.Attributes))).Result;



}

    public static async Task<string> GetToken()
    {
        string api = "https://ORG.api.crm4.dynamics.com/";

        ClientCredential credential = new ClientCredential("CLIENT_ID", "CLIENT_SECRET");

        AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/commom/oauth2/authorize");
        return authenticationContext.AcquireTokenAsync(api, credential).Result.AccessToken;

    }

    public static object KeyPairValueToObject(AttributeCollection keyValuePairs)
    {
        dynamic expando = new ExpandoObject();
        var obj = expando as IDictionary<string, object>;
        foreach (var keyValuePair in keyValuePairs)
            obj.Add(keyValuePair.Key,  keyValuePair.Value);
        return obj;

    }
}

It's a simple approach and I didn't went further. Maybe we have to serealize other objects as OptionSets, DateTime (pass just the string) and EntityReferences but this simple test worked fine to me. I'm using Xrm.Tools.WebAPI and Microsoft.IdentityModel.Clients.ActiveDirectory. Maybe it's a way.

[Edit]

And so I decided to go and created a not well tested method to cast the attributes. Problems: We have to follow OData statments to use the API. To update/create an entity reference we can use this to reference https://www.inogic.com/blog/2016/02/set-values-of-all-data-types-using-web-api-in-dynamics-crm/ So

//To EntityReference

entityToUpdateOrCreate["FIELD_SCHEMA_NAME@odata.bind"] = "/ENTITY_SET_NAME(GUID)";

So, it's the Schema name, not field name. If you use CamelCase when set you fields name you'll have a problem where. We can resolve that with a (to that cute) code

        public static object EntityToObject<T>(T entity) where T : Entity
    {
        dynamic expando = new ExpandoObject();
        var obj = expando as IDictionary<string, object>;
        foreach (var keyValuePair in entity.Attributes)
        {
            obj.Add(GetFieldName(entity, keyValuePair), CastEntityAttibutesValueOnDynamicObject(keyValuePair.Value));
        }
        return obj;

    }

    public static object CastEntityAttibutesValueOnDynamicObject(object attributeValue)
    {
        if (attributeValue.GetType().Name == "EntityReference")
         {
            CRMGetListOptions listOptions = new CRMGetListOptions
            {
                Select = new string[] { "EntitySetName" },
                Filter = $"LogicalName eq '{((EntityReference)attributeValue).LogicalName}'"
            };

            dynamic entitySetName = dynamicsWebAPI.GetList<ExpandoObject>("EntityDefinitions", listOptions).Result.List[0];

            return $"/{entitySetName.EntitySetName}({((EntityReference)attributeValue).Id})";
        }
        else if (attributeValue.GetType().Name == "OptionSetValue")
        {
            return ((OptionSetValue)attributeValue).Value;
        }
        else if (attributeValue.GetType().Name == "DateTime")
        {
            return ((DateTime)attributeValue).ToString("yyyy-MM-dd");
        }
        else if (attributeValue.GetType().Name == "Money")
        {
            return ((Money)attributeValue).Value;
        }
        else if (attributeValue.GetType().Name == "AliasedValue")
        {
            return CastEntityAttibutesValueOnDynamicObject(((AliasedValue)attributeValue).Value);
        }
        else
        {
            return attributeValue;
        }
    }

    public static string GetFieldName<T>(T entity, KeyValuePair<string, object> keyValuePair) where T : Entity
    {
        switch (keyValuePair.Value.GetType().Name)
        {
            case "EntityReference":
                var entityNameList = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.GetEntityDisplayNameList()).Result;

                var firstEntity = entityNameList.Where(x => x.LogicalName == entity.LogicalName).FirstOrDefault();

                var attrNameList = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.GetAttributeDisplayNameList(firstEntity.MetadataId)).Result;

                return attrNameList.Where(x => x.LogicalName == keyValuePair.Key).Single().SchemaName + "@odata.bind";
            case "ActivityParty":
                throw new NotImplementedException(); //TODO
            default:
                return keyValuePair.Key;
        }
    }

Please, note that this approach do not seems fast or good in anyway. It's better if you have all this values as static so we can save some fetches

[Edit 2]

I just found on XRMToolBox a plugin called "Early bound generator for Web API" and it seems to be the best option . Maybe you should give it a try if you're still curious about that. I guess its the best approach. The final code is this:

        static void Main(string[] args)
    {
        string token = Task.Run(() => GetToken()).Result;
        dynamicsWebAPI = new CRMWebAPI("https://ORG.api.crm4.dynamics.com/api/data/v9.1/",
                token);

        Contact contact = new Contact
        {
            FirstName = "Felipe",
            LastName = "Test",
            MobilePhone = "38421254",
            new_Salutation = new EntityReference(new_salutation.EntitySetName, new Guid("{BFA27540-7BB9-E611-80EE-FC15B4281C8C}")),
            BirthDate = new DateTime(1993, 04, 14),
        };

        dynamic ret = Task.Run(async () => await dynamicsWebAPI.Create(Contact.EntitySetName, contact.ToExpandoObject())).Result;
        Contact createdContact = dynamicsWebAPI.Get<Contact>(Contact.EntitySetName, ret, new CRMGetListOptions
        {
            Select = new string[] { "*" }
        }).Result;
    }

and you have to change the ToExpandoObject on Entity.cs class (generated by the plugin)

        public ExpandoObject ToExpandoObject()
    {
        dynamic expando = new ExpandoObject();
        var expandoObject = expando as IDictionary<string, object>;
        foreach (var attributes in Attributes)
        {
            if (attributes.Key == GetIdAttribute())
            {
                continue;
            }

            var value = attributes.Value;
            var key = attributes.Key;

            if (value is EntityReference entityReference)
            {
                value = $"/{entityReference.EntitySetName}({entityReference.EntityId})";
            }
            else
            {
                key = key.ToLower();

                if (value is DateTime dateTimeValue)
                {
                    var propertyForAttribute = GetPublicInstanceProperties().FirstOrDefault(x =>
                        x.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase));

                    if (propertyForAttribute != null)
                    {
                        var onlyDateAttr = propertyForAttribute.GetCustomAttribute<OnlyDateAttribute>();

                        if (onlyDateAttr != null)
                        {
                            value = dateTimeValue.ToString(OnlyDateAttribute.Format);
                        }
                    }
                }
            }

            expandoObject.Add(key, value);
        }

        return (ExpandoObject)expandoObject;
    }

Links: https://github.com/davidyack/Xrm.Tools.CRMWebAPI

https://www.xrmtoolbox.com/plugins/crm.webApi.earlyBoundGenerator/

We currently use XrmToolkit which has it's own version of early binding called ProxyClasses but will allow you to generate early binding using the CRM Service Utility (CrmSvcUtil). It does a lot more than just early binding which is why we use it on all of our projects but the early binding features alone would have me sold on it. in order to regenerate an entity definition all you do is right click the cs file in visual studio and select regenerate and it is done in a few seconds.

For my first 3 years of CRM development I used the XrmToolbox "Early Bound Generator" plugin which is really helpful as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM