viernes, 13 de septiembre de 2013

CRM 4.0 - Todo sobre entidades dynamicas en crm

Actualizar a nulo un campo de datetime

CrmDateTime NullTime = new CrmDateTime();
NullTime.IsNull = true;
NullTime.IsNullSpecified = true;
           
proyectoDinamico.Properties.Add(new CrmDateTimeProperty("new_fechaestimadacierredinamica", NullTime));


Recuperar un string de el contexto de un plugin (Entidad dinámica)

Microsoft.Crm.Sdk.DynamicEntity target = (Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["Target"];
string domainname= target.Properties["domainname"].ToString();

Recuperar otro tipo de dato de una entidad dinámica

CrmNumber workItemHours = entity.Properties["new_budgetedhours"] as CrmNumber;
o otro modo:
Guid projectid = ((CrmSdk.Lookup)entity.Properties["new_projectid"]).Value;

Comprobar una propiedad del tipo string en un if

if (((string)postOportunidad.Properties["statecode"]) == "Open") {
...
}


Modifica el valor del atributo de una entidad dinámica

tarea.Properties["new_horastotales"] = new CrmDecimal(horasTarea);


Crear, borrar y modificar entidades dinámicas

  * Crear
  // Create the target.
                TargetCreateDynamic targetCreateSinonimoNuno = new TargetCreateDynamic();
                targetCreateSinonimoNuno.Entity = sinonimoNuno;
                // Create the request object.
                CreateRequest createSinonimoNuno = new CreateRequest();
                // Set the properties of the request object.
                createSinonimoNuno.Target = targetCreateSinonimoNuno;
                // Execute the request.
                CreateResponse created = (CreateResponse)crmService.Execute(createSinonimoNuno);

  * Recuperar
  // Retrieve the target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
                targetRetrieve.EntityId = PrePrograma.Value;
                targetRetrieve.EntityName = EntityName.product.ToString();
                // Retrieve the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
  retrieve.ReturnDynamicEntities = true;
  columnasProspect.Attributes.Add("new_lineadenegocioid");
                retrieve.ColumnSet = columnasProspect;
                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)crmService.Execute(retrieve);

  * Recuperar multiples
  sinonimoGuid = ((Key)sinonimo.Properties["new_sinonimoid"]).Value;
  //Recupero la unidad estandar del CRM
                        QueryByAttribute querySinonimoNuno = new QueryByAttribute();
                        colsNunoNif.Attributes.Add("new_sinonimoid");
                        colsNunoNif.Attributes.Add("new_nunoid");
                        querySinonimoNuno.ColumnSet = colsNunoNif;
                        querySinonimoNuno.EntityName = "new_sinonimonuno";
                        querySinonimoNuno.Attributes = new string[] { "new_sinonimoid" };
                        querySinonimoNuno.Values = new object[] { sinonimoGuid };
                        RetrieveMultipleRequest requestSinonimoNuno = new RetrieveMultipleRequest();
                        requestSinonimoNuno.ReturnDynamicEntities = true;
                        requestSinonimoNuno.Query = querySinonimoNuno;
                        RetrieveMultipleResponse retrievedSinonimoNuno = (RetrieveMultipleResponse)crmService.Execute(requestSinonimoNuno);
                        if (retrievedSinonimoNuno.BusinessEntityCollection.BusinessEntities.Count > 0) {

  * Actualizar

  // Create the update target.
             TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();
             // Set the properties of the target.
             updateDynamic.Entity = entity;
             //   Create the update request object.
             UpdateRequest update = new UpdateRequest();
             //   Set request properties.
             update.Target = updateDynamic;
             //   Execute the request.
             UpdateResponse updated = (UpdateResponse)crmService.Execute(update);


  * Eliminar

    TargetDeleteDynamic targetDeleteControlCostes = new TargetDeleteDynamic();
                  targetDeleteControlCostes.EntityName = "new_controldecoste";
                  targetDeleteControlCostes.EntityId = controlCostesGuid;
                  DeleteRequest deleteControlCostesReq = new DeleteRequest();
                 
                  deleteControlCostesReq.Target = targetDeleteControlCostes;
                  DeleteResponse deleteControlCostesResp = (DeleteResponse)crmService.Execute(deleteControlCostesReq);

Igualmente con Update, Delete, etc.


Añadir un atributo a una entidad dinámica

Siendo Cliente una entidad dinamica

      Key KeyContact = new Key();
                    KeyContact.Value = new Guid(context.OutputParameters.Properties["id"].ToString());
                   
                    Cliente.Properties.Add(new KeyProperty("accountid", KeyContact));

      //Si usas el Web Service el metodo Add no existe y has de usarlo de este modo
             //Creas por un lado las propiedades
      CrmBooleanProperty P_bool = new CrmBooleanProperty();
                    P_bool.Value = new CrmBoolean();
                    P_bool.Name = "new_Reconfirmacion";
                    P_bool.Value.Value = true;
                    KeyProperty P_key = new KeyProperty();
                    P_key.Name = "activityid";
                    P_key.Value = Respuestas.activityid;

//Y las añades a la entidad dinamica asi:
respuestaDinamica.Properties = new Property[] {P_bool, P_key};

             //Otra manera de añadir atributos
      //Creacion del producto de la oportunidad
                productoOportunidad.Properties.Add(new LookupProperty("opportunityid",new Lookup("opportunity",OportunityId)));
                productoOportunidad.Properties.Add(new LookupProperty("productid",new Lookup("product",ProductoId)));
                productoOportunidad.Properties.Add(new LookupProperty("uomid",new Lookup("uom",UnidadMedidaId)));
                productoOportunidad.Properties.Add(new CrmMoneyProperty("priceperunit", precioUnidad));
                productoOportunidad.Properties.Add(new CrmDecimalProperty("quantity",precioTotal));
                productoOportunidad.Properties.Add(new CrmMoneyProperty("baseamount", importe));
                productoOportunidad.Properties.Add(new CrmBooleanProperty("new_lineaprincipal", new CrmBoolean(true)));



Preguntar si una entidad dinamica tiene un determinado atributo

Siendo Cliente una entidad dinamica

     
if ( Cliente.Properties.Contains("originatingleadid") ) {
...
}


//Esta funcion se utiliza para convertir una entidad dinamica en una bussines entity que podremos
//utilizar para actualizar o crear entidades con el webservice


incluir -> using System.Reflection;
/// <summary>
        /// Convert a dynamic entity into a strongly typed business entity.
        /// </summary>
        public static BusinessEntity Convert(DynamicEntity entity) {
            string coreEntityName = entity.Name;
     //ATENCION !!!!!! cambiar new email() por la entidad que corresponda !!!!!
            Type entType = (new email()).GetType();
            ConstructorInfo init = entType.GetConstructor(new Type[] { });
            object ent = init.Invoke(new object[] { });
            foreach (Property p in entity.Properties) {
                PropertyInfo entProp = entType.GetProperty(p.Name);
                if (null == entProp) {
                    Console.WriteLine("Could not find attribute {0} on entity {1}.", p.Name, coreEntityName);
                }
                else {
                   
                        entProp.SetValue(ent, GetAttribute(entity, p.Name), null);
                   
                }
            }
            return (BusinessEntity)ent;
        }

....

Un ejemplo de su uso seria:


  DynamicEntity Cliente = new DynamicEntity();

  //***Aqui se hace algo con la entidad dinamica***

  Cliente = (DynamicEntity)context.InputParameters.Properties["Target"];

  //***********************************************

  BusinessEntity ClienteFisico = Convert(Cliente);
                account Account = (account)ClienteFisico;
                Account.accountid = new Key();
               
                if (context.OutputParameters.Properties.Contains("id"))
                    Account.accountid.Value = new Guid(context.OutputParameters.Properties["id"].ToString());

  //Finalmente se actualiza
                service.Update(Account);



Crea, Actualiza o Borra una entidad dinamica con el servicio web


      TargetUpdateDynamic Aval = new TargetUpdateDynamic();
                    Aval.Entity = entity;
                    UpdateRequest update = new UpdateRequest();
                    update.Target = Aval;


---------------------------------------------------------------------------------------------
incluir -> using System.Reflection;
 /// <summary>
        /// This method returns the value of a dynamic entity attribute.
        /// </summary>
        public static object GetAttribute(BusinessEntity entity, string attribute) {
            if (entity.GetType() == typeof(DynamicEntity)) {
                DynamicEntity de = (DynamicEntity)entity;
                foreach (Property prop in de.Properties) {
                    if (prop.Name == attribute) {
                        PropertyInfo propInfo = prop.GetType().GetProperty("Value");
                        return propInfo.GetValue(prop, null);
                    }
                }
                return null;
            }
            else {
                PropertyInfo propInfo = entity.GetType().GetProperty(attribute);
                return propInfo.GetValue(entity, null);
            }
        }
---------------------------------------------------------------------------------------------

DynamicEntity emaildinamico = new DynamicEntity();
emaildinamico.Name = EntityName.email.ToString();
...

//((DynamicEntity)context.InputParameters.Properties["Target"]).Properties["
subject"] = "hola";
//emaildinamico = (DynamicEntity)context.InputParameters.Properties["Target"];
//PropertyBagCollection target = context.InputParameters.Properties["Target"];
//target.



Hacer un retrieve en una entidad dinámica


  // Create the request.
                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.ReturnDynamicEntities = true;
                retrieve.Query = qe.Query;
                // Execute the request.
                RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)crmService.Execute(retrieve);
                DynamicEntity entidad_recuperada = new DynamicEntity();
                entidad_recuperada.Name = entity;
                object valor_atributo;
                if (retrieved2.BusinessEntityCollection.BusinessEntities.Length > 0) {
                    for (int i = 0; i < retrieved2.BusinessEntityCollection.BusinessEntities.Length;i++ ) {
                        BusinessEntity be = retrieved2.BusinessEntityCollection.BusinessEntities[i];
                        entidad_recuperada = (DynamicEntity)be;
                        valor_atributo = GetAttribute(entidad_recuperada, atributo);



GetAttribute: Funcion para recuperar el campo de una entidad dinámica

 /// <summary>
        /// This method returns the value of a dynamic entity attribute.
        /// </summary>
        public static object GetAttribute(BusinessEntity entity, string attribute) {
            if (entity.GetType() == typeof(DynamicEntity)) {
                DynamicEntity de = (DynamicEntity)entity;
                foreach (Property prop in de.Properties) {
                    if (prop.Name == attribute) {
                        PropertyInfo propInfo = prop.GetType().GetProperty("Value");
                        return propInfo.GetValue(prop, null);
                    }
                }
                return null;
            }
            else {
                PropertyInfo propInfo = entity.GetType().GetProperty(attribute);
                return propInfo.GetValue(entity.ToString(), null);
            }
        }



Trabajo con entidades Dinamicas SDK



[C#]
using System;
using System.Collections;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;
namespace Microsoft.Crm.Sdk.HowTo
{
   /// <summary>
   /// This sample shows how to create a contact with a DynamicEntity and
   ///  retrieve it as a DynamicEntity.
   /// </summary>
   public class DynamicEntityHowTo
   {
      static void Main(string[] args)
      {
         // TODO: Change the server URL and organization to match your Microsoft
         // Dynamics CRM Server and Microsoft Dynamics CRM organization.
         DynamicEntityHowTo.Run("http://localhost:5555", "CRM_SDK");
      }
      public static bool Run(string crmServerUrl, string orgName)
      {
         bool success = false;
         try
         {
            // Set up the CRM Service.
         CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);


            #region Setup Data Required for this Sample
            // Create the account object.
            account account = new account();
            account.name = "Fourth Coffee";
            // Create the target object for the request.
            TargetCreateAccount target = new TargetCreateAccount();
            target.Account = account;
            // Create the request object.
            CreateRequest createRequest = new CreateRequest();
            createRequest.Target = target;
        
            // Execute the request.
            CreateResponse createResponse = (CreateResponse)service.Execute(createRequest);
            Guid accountID = createResponse.id;
            #endregion


Create Contact Dynamically



            #region Create Contact Dynamically
            // 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};
     
            // Create the target.
            TargetCreateDynamic targetCreate = new TargetCreateDynamic();
            targetCreate.Entity = contactEntity;
            // Create the request object.
            CreateRequest create = new CreateRequest();
            // Set the properties of the request object.
            create.Target = targetCreate;
            // Execute the request.
            CreateResponse created = (CreateResponse) service.Execute(create);
        
            #endregion


Retrieve Contact Dynamically


        
            #region Retrieve Contact Dynamically
            // Create the retrieve target.
            TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
            // Set the properties of the target.
            targetRetrieve.EntityName = EntityName.contact.ToString();
            targetRetrieve.EntityId = created.id;
            // Create the request object.
            RetrieveRequest retrieve = new RetrieveRequest();
            // Set the properties of the request object.
            retrieve.Target = targetRetrieve;
            retrieve.ColumnSet = new AllColumns();
            // Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
            retrieve.ReturnDynamicEntities = true;
            // Execute the request.
            RetrieveResponse retrieved = (RetrieveResponse) service.Execute(retrieve);
            // Extract the DynamicEntity from the request.
            DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
            // Extract the fullname from the dynamic entity
            string fullname;
            for (int i = 0; i < entity.Properties.Length; i++)
            {
               if (entity.Properties[i].Name.ToLower() == "fullname")
               {
                  StringProperty property = (StringProperty) entity.Properties[i];
                  fullname = property.Value;
                  break;
               }
            }
            #endregion


Update the DynamicEntity



            #region  Update the DynamicEntity
            // This part of the example demonstrates how to update properties of a
            // DynamicEntity. 
            // Set the contact properties dynamically.
            // Contact Credit Limit
            CrmMoneyProperty money = new CrmMoneyProperty();
            // Specify the property name of the DynamicEntity.
            money.Name="creditlimit";
            money.Value = new CrmMoney();
            // Specify a $10000 credit limit.
            money.Value.Value=10000M;
            // Contact PreferredContactMethodCode property
            PicklistProperty picklist = new PicklistProperty();
            //   Specify the property name of the DynamicEntity.
            picklist.Name="preferredcontactmethodcode";
            picklist.Value = new Picklist();
            //   Set the property's picklist index to 1.
            picklist.Value.Value = 1;
            // Contact ParentCustomerId property.
            CustomerProperty parentCustomer = new CustomerProperty();
            //   Specify the property name of the DynamicEntity.
            parentCustomer.Name = "parentcustomerid";
            parentCustomer.Value = new Customer();
            //   Set the customer type to account.
            parentCustomer.Value.type = EntityName.account.ToString();
            //   Specify the GUID of an existing CRM account.
            // SDK:parentCustomer.Value.Value = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
            parentCustomer.Value.Value = accountID;
            //   Update the DynamicEntities properties collection to add new properties.
            //   Convert the properties array of DynamicEntity to an ArrayList.
            ArrayList arrProps = new ArrayList(entity.Properties);
           
            //   Add properties to ArrayList.
            arrProps.Add(money);
            arrProps.Add(picklist);
            arrProps.Add(parentCustomer);
            //   Update the properties array on the DynamicEntity.
            entity.Properties = (Property[])arrProps.ToArray(typeof(Property));
            // Create the update target.
            TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();
            // Set the properties of the target.
            updateDynamic.Entity = entity;
            //   Create the update request object.
            UpdateRequest update = new UpdateRequest();
            //   Set request properties.
            update.Target = updateDynamic;
            //   Execute the request.
            UpdateResponse updated = (UpdateResponse)service.Execute(update);
           
            #endregion

            #region check success
            if (retrieved.BusinessEntity is DynamicEntity)
            {
               success =  true;
            }
            #endregion

  
            #region Remove Data Required for this Sample
            service.Delete(EntityName.contact.ToString(), created.id);
            service.Delete(EntityName.account.ToString(), accountID);
            #endregion

         }
         catch (System.Web.Services.Protocols.SoapException ex)
         {
            // Add your error handling code here...
            Console.WriteLine(ex.Message + ex.Detail.InnerXml);
         }
        
         return success;
      }
   }
}

No hay comentarios:

Publicar un comentario