domingo, 15 de septiembre de 2013

CRM 4.0 - Funcion GetCrmService

private CrmSdk.CrmService GetCrmService(string organizationName) {
            // Setup the Authentication Token
            CrmSdk.CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            CrmSdk.CrmService crmService = new CrmSdk.CrmService();
            crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            crmService.CrmAuthenticationTokenValue = token;
            return crmService;
        }

...

CrmService crmService = GetCrmService("organiacion");
crmService.Credentials = new System.Net.NetworkCredential("usuario", "pass", "domain");

.NET - Encriptación y almacenamiento de claves en web.config y registro windows

Identificación en ASP con password almacenada


1) Usando texto plano

<identity impersonate="true" userName="contoso\Jane" password="pass"/>


2) usando el registro de windows (aspnet_setreg)

userName="registry:HKLM\Software\AspNetIdentity,Name"
password="registry:HKLM\Software\AspNetIdentity,Password"
The credentials must be in REG_BINARY format, containing the output of a call to the Windows API function CryptProtectData. You can create the encrypted credentials and store them in the registry with the ASP.NET Set Registry console application(Aspnet_setreg.exe), which uses CryptProtectData to accomplish the encryption. To download Aspnet_setreg.exe, along with the Visual C++ source code and documentation, visit the Web site www.asp.net and search for "aspnet_setreg".
You should configure access to the key storing the encrypted credentials so that access is provided only to Administrators and SYSTEM. Because the key will be read by the ASP.NET process running as SYSTEM, you should set the following permissions:
Administrators:F
SYSTEM:F
CREATOR OWNER:F
ProcessAccount:R


3) Usando el web.config y encriptando la informacion de usuario y clave

The Aspnet_regiis.exe tool (located in the %SystemRoot%\Microsoft.NET\Framework\versionNumber folder)
includes options for encrypting and decrypting sections of a Web.config file, creating or deleting key containers, exporting and importing key container information, and managing access to a key container.
Once you have specified which provider to use, you can encrypt or decrypt the contents of the Web.config file for your application.

Use the –app option to identify the application for which the Web.config file will be encrypted and the -site option to identify which Web site the application is a part of. The Web site is identified using the site number from the Internet Information Services (IIS) metabase. You can retrieve the site number from the INSTANCE_META_PATH server variable in the ServerVariables collection. For example, when IIS is installed, a Web site named "Default Web Site" is created as site 1. In pages served from that site, the INSTANCE_META_PATH server variable returns "/LM/W3SVC/1". If you do not specify a -site option, site 1 is used.
To see all the possible server variables in IIS, place the following code into an Active Server Page, then browse to it:
<table BORDER="1">
<th COLSPAN="2">ServerVariables</th>
<%
Dim var
For Each var in Request.ServerVariables
    Call Response.Write("<TR>")
    Call Response.Write("<TD><B>" & var & "</B>:</TD>")
    Call Response.Write("<TD>" & Request.ServerVariables(var) _
      & "</TD>")
    Call Response.Write("</TR>")
Next
%>
</table>

Use the –prov option to identify the name of the ProtectedConfigurationProvider that will perform the encryption and decryption. If you do not specify a provider using the -prov option, the provider configured as the defaultProvider is used.

Un ejemplo que encripta el connectionstring del web.config
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov "RsaProtectedConfigurationProvider"

Para desencriptar :
aspnet_regiis -pd "connectionStrings" -app "/SampleApplication"




Para MicrosoftCRM utilizo el siguiente aspx para sacar las serverVariables


<%@ Page language="vb" Inherits="Microsoft.Crm.Web.Loader" %>
<%@ Register TagPrefix="loc" Namespace="Microsoft.Crm.Application.Controls.Localization" Assembly="Microsoft.Crm.Application.Components.Application" %>
<%@ Register TagPrefix="cnt" Namespace="Microsoft.Crm.Application.Controls" Assembly="Microsoft.Crm.Application.Components.Application" %>
<%@ Import Namespace="Microsoft.Crm.Utility" %>
<%@ Import Namespace="Microsoft.Crm.Application.Pages.Common" %>
<html>
<table BORDER="1">
<th COLSPAN="2">ServerVariables</th>
<%
Dim var
For Each var in Request.ServerVariables
    Call Response.Write("<TR>")
    Call Response.Write("<TD><B>" & var & "</B>:</TD>")
    Call Response.Write("<TD>" & Request.ServerVariables(var) _
      & "</TD>")
    Call Response.Write("</TR>")
Next
%>
</table>
</body>

</html>

CRM 4.0 - Acceso y autenticación desde asp a crm con acceso a registro

using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Win32;
namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        public string orgname;
        public string crmurl;
        public string metaurl;
        public bool offline;
        protected void Page_Load(object sender, EventArgs e)
        {
            #region CRM URLs and Organization Name
            //Determine Offline State from Host Name
            Response.Write(Request.Url.Host.ToString());
            if (Request.Url.Host.ToString() == "127.0.0.1")
            {
                offline = true;
                //Retrieve the Port and OrgName from the Registry
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
                orgname = regkey.GetValue("ClientAuthOrganizationName").ToString();
                string portnumber = regkey.GetValue("CassiniPort").ToString();
                //Construct the URLs
                string baseurl = "http://localhost:" + portnumber + "/mscrmservices/2007/";
                crmurl = baseurl + "crmservice.asmx";
                metaurl = baseurl + "metadataservice.asmx";
            }
            else
            {
                offline = false;
                //Retrieve the URLs from the Registry
                RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
                string ServerUrl = regkey.GetValue("ServerUrl").ToString();
                crmurl = ServerUrl + "/2007/crmservice.asmx";
                metaurl = ServerUrl + "/2007/metadataservice.asmx";
                //Retrieve the Query String from the current URL
                if (Request.QueryString["orgname"] == null)
                {
                    orgname = string.Empty;
                }
                else
                {
                    //Query String
                    string orgquerystring = Request.QueryString["orgname"].ToString();
                    if (string.IsNullOrEmpty(orgquerystring))
                    {
                        orgname = string.Empty;
                    }
                    else
                    {
                        orgname = orgquerystring;
                    }
                }
                if (string.IsNullOrEmpty(orgname))
                {
                    //Windows Auth URL
                    if (Request.Url.Segments[2].TrimEnd('/').ToLower() == "isv")
                    {
                        orgname = Request.Url.Segments[1].TrimEnd('/').ToLower();
                    }
                    //IFD URL
                    if (string.IsNullOrEmpty(orgname))
                    {
                        string url = Request.Url.ToString().ToLower();
                        int start = url.IndexOf("://") + 3;
                        orgname = url.Substring(start, url.IndexOf(".") - start);
                    }
                }
            }
            #endregion

            using (new CrmImpersonator())
            {
                CrmAuthenticationToken token;
                if (offline == true)
                {
                    token = new CrmAuthenticationToken();
                }
                else
                {
                    // Notice that the Context parameter value is Page.Context.
                    token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
                }
                token.OrganizationName = orgname;
                token.AuthenticationType = 0;
                //Create the Service
                CrmService service = new CrmService();
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                service.CrmAuthenticationTokenValue = token;
                service.Url = crmurl;
            // This code shows how to create the metadata service.
            // It is not used in this sample.

            // MetadataService meta = new MetadataService();
            // meta.CrmAuthenticationTokenValue = token;
            // meta.Credentials = CredentialCache.DefaultCredentials;
            // meta.Url = "http://localhost/mscrmservices/2007/MetadataService.asmx";

                account account = new account();
                account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
                if (offline == false)
                    // Explicitly set the owner ID for the record if not offline.
                    account.ownerid = new Owner("systemuser", token.CallerId);
                service.Create(account);
            }
            Response.Write("Done");
        }
    }
}

CRM 4.0 - Acceder al crm desde fuera sin usar webservice


Inclusión de la función de conexión


private CrmService GetCrmService(string organizationName) {
            // Setup the Authentication Token
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            CrmService crmService = new CrmService();
            crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            crmService.CrmAuthenticationTokenValue = token;
            return crmService;
        }



En el programa principal se conecta


     #region Proceso de conexión

            crmService = GetCrmService("organizacion");
            crmService.Credentials = new System.Net.NetworkCredential("usuario", "pass", "domain");
            crmService.Url = "http://127.0.0.1/MSCrmServices/2007/CrmService.asmx";

            #endregion

CRM 4.0 - Acceder al CRM desde un aspx con funcion de impersonacion


Conectar desde un aspx con o sin impersonación


1) Añadir al aspx las referencias web



using Microsoft.Crm.Sdk;
using Query = Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Disco;


2) Incluir la siguiente función


- Modificar la URL según intenciones (AD o SPLA en  token.AuthenticationType y en disco.Url),
- Si se accede por IFD en el (service.Credentials) poner DefaultCredentials


public CrmService GetCrmService(HttpContext context, string orgName)
    {
        using (new CrmImpersonator())
        {
            string UserName = "usuario";
            string Password = "password";
            string Domain = "dominio";
            //Get the server url from the registry
            string CRM_REG_DIRECTORY = @"software\Microsoft\mscrm\";
            RegistryKey regkey = Registry.LocalMachine.OpenSubKey(CRM_REG_DIRECTORY);
            string crmServerURL = regkey.GetValue("ServerUrl").ToString();
            CrmService service = null;
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Credentials = new NetworkCredential(UserName, Password, Domain);
           
           
            crmServerURL = @"http://127.0.0.1:5602/mscrmservices";
           
            disco.Url = String.Concat(crmServerURL, "/2007/ad/CrmDiscoveryService.asmx");
            RetrieveOrganizationsRequest OrgRequest = new RetrieveOrganizationsRequest();
            OrgRequest.Password = Password;
            OrgRequest.UserId = Domain + "\\" + UserName;
            RetrieveOrganizationsResponse OrgResponse = (RetrieveOrganizationsResponse)disco.Execute(OrgRequest);
            orgName = orgName.ToLower();
            foreach (OrganizationDetail OrgDetail in OrgResponse.OrganizationDetails)
            {
                if (OrgDetail.OrganizationName.ToLower().Equals(orgName))
                {
                    //Retrieve the ticket.
                    RetrieveCrmTicketRequest ticketRequest = new RetrieveCrmTicketRequest();
                    ticketRequest.OrganizationName = OrgDetail.OrganizationName;
                    ticketRequest.UserId = Domain + "\\" + UserName;
                    ticketRequest.Password = Password;
                    RetrieveCrmTicketResponse ticketResponse = (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);
                    // Setup the Authentication Token
                    CrmAuthenticationToken token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(context, OrgDetail.OrganizationName);
                    token.OrganizationName = OrgDetail.OrganizationName;
                    //token.AuthenticationType = AuthenticationType.Spla; //2
                    token.AuthenticationType = AuthenticationType.AD;
                    token.CrmTicket = ticketResponse.CrmTicket;
                    //Setup Service
                    service = new CrmService();
                    service.Url = OrgDetail.CrmServiceUrl;
                                       
                    service.Credentials = new System.Net.NetworkCredential(UserName, Password, Domain);
                  
                    service.CrmAuthenticationTokenValue = token;
                    break;
                }
            }
            return service;
        }
    }



3) Llamar a la funcion y utilizar el servicio



protected void Page_Load(object sender, EventArgs e)
    {
        string orgname;
       
        try
        {
            //Retrieve the Query String from the current URL
            if (Request.QueryString["orgname"] == null)
            {
                orgname = string.Empty;
            }
            else
            {
                //Query String
                string orgquerystring = Request.QueryString["orgname"].ToString();
                if (string.IsNullOrEmpty(orgquerystring))
                {
                    orgname = string.Empty;
                }
                else
                {
                    orgname = orgquerystring;
                }
            }

           
            CrmService service = GetCrmService(Context, orgname);
           
            systemuser usuario = new systemuser();
            usuario = (systemuser)service.Retrieve(EntityName.systemuser.ToString(), new Guid(Context.User.Identity.Name), new Query.AllColumns());
            if (usuario.domainname != null)
            {
                Response.Write(usuario.domainname);
                nombreusuario = usuario.domainname;
            }
        }
        catch (SoapException sx)
        {
            Response.Write(sx.Detail.OuterXml);
        }

...

CRM 4.0 - Acceso a CRM desde .NET


private CrmService.CrmService GetCrmService(string organizationName) {
        // Setup the Authentication Token
        CrmService.CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.OrganizationName = organizationName;
        CrmService.CrmService crmService = new CrmService.CrmService();
        crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        crmService.CrmAuthenticationTokenValue = token;
        return crmService;
}

CrmService.CrmService crmService = GetCrmService(organizationName);
crmService.Credentials = new System.Net.NetworkCredential("usuario", "password", "dominio.com");


--------------------------------------------------------------------------------------------------------------------


/// <summary>
/// Retrieves all the CRM Organizations available on the server
/// </summary>
private void GetOrganizations() {

        //Authenticate with the DiscoveryService using
        //Active Directory Windows Integrated Security
        CrmDiscoveryService.CrmDiscoveryService discoveryService = new CrmDiscoveryService.CrmDiscoveryService();
        //discoveryService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        discoveryService.Credentials = new System.Net.NetworkCredential("usuario","password","dominio.com");
        //Make request for organization information
        RetrieveOrganizationsRequest orgsRequest = new RetrieveOrganizationsRequest();
        RetrieveOrganizationsResponse orgsResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgsRequest);

        //Populate the organizations
        for (int i = 0; i < orgsResponse.OrganizationDetails.Length; i++) {
            ddlOrganizations.Items.Add(new ListItem(orgsResponse.OrganizationDetails[i].OrganizationName, orgsResponse.OrganizationDetails[i].OrganizationId.ToString()));
        }
}

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;
      }
   }
}