Saturday, November 20, 2010

Convert a Dynamic Entity to a System Entity

This sample code shows how to convert a dynamic entity instance into a strongly typed account entity instance. The code first creates a dynamic entity, populates its properties with account attributes and values, and then converts the dynamic entity to an account entity.
using System;
using System.Reflection;

using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
public class ConvertDynamicToCore
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft
// Dynamics CRM Server and Microsoft Dynamics CRM organization.
ConvertDynamicToCore.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Create an account dynamic entity.
DynamicEntity accountDynamicEntity = new DynamicEntity();

//Set a few account properties.
StringProperty name = new StringProperty();
name.Name = "name";
name.Value = "Fabrikam Inc.";

StringProperty accountnumber = new StringProperty();
accountnumber.Name = "accountnumber";
accountnumber.Value = "AZ1200";

Picklist plist = new Picklist();
plist.name = "UPS";
plist.Value = 2;

PicklistProperty shippingmethodcode = new PicklistProperty();
shippingmethodcode.Name = "address1_shippingmethodcode";
shippingmethodcode.Value = plist;

accountDynamicEntity.Properties = new Property[] { name, accountnumber, shippingmethodcode };
accountDynamicEntity.Name = EntityName.account.ToString();

//Create a strongly typed account entity to copy the dynamic entity into.
account coreAccount = new account();

//Convert the dynamic entity to a strongly typed business entity.
coreAccount = (account)Convert(accountDynamicEntity);

Console.WriteLine("\n|Core Account Attributes\n|=======================");
Console.WriteLine("|name: {0}", coreAccount.name);
Console.WriteLine("|accountnumber: {0}", coreAccount.accountnumber);
Console.WriteLine("|address1_shipmethodcode: {0}", coreAccount.address1_shippingmethodcode.Value);

return true;
}

///
/// Convert a dynamic entity into a strongly typed business entity.
///

public static BusinessEntity Convert(DynamicEntity entity)
{
string coreEntityName = entity.Name;

Type entType = (new account()).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;
}

///
/// This method returns the value of a dynamic entity attribute.
///

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

PublishXml Message (CrmService)

Publish the customizations for the specified entities.
The relevant classes are: 1) PublishXmlRequest 2) PublishXmlResponse
Remarks
To use this message, pass an instance of the PublishXmlRequest class as the request parameter in the Execute method.
For a list of required privileges, see PublishXml Privileges.
Example
The following code example shows how to use the PublishXml message.
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
PublishXmlRequest request = new PublishXmlRequest();

request.ParameterXml = @"<importexportxml>
<entities>
<entity>account</entity>
<entity>contact</entity>
</entities>
<nodes/>
<securityroles/>
<settings/>
<workflows/>
</importexportxml>";

// Execute the request.
PublishXmlResponse response = (PublishXmlResponse)service.Execute(request);

Create Custom Entity Message (MetadataService)

The relevant classes: 1) CreateEntityRequest 2) CreateEntityResponse

Remarks
To perform this action, the caller must be a user in the organization for which metadata is requested and must haveCreate Entity and Read Entity privileges.

The entity created will have a property value of true for the EntityMetadata.IsCustomEntity property.

You must publish the changes to the metadata before this change will be visible in the application. For more information see Publishing the Metadata.

Example with Source Code:

// Create an authentication token.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "AdventureWorksCycle";

// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;

// Create the metadata Web service.
MetadataService metadataService = new MetadataService();
metadataService.Url = "http://<servername>:<port>/MSCRMServices/2007/MetadataService.asmx";
metadataService.CrmAuthenticationTokenValue = token;
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
metadataService.PreAuthenticate = true;

// Create the entity.
EntityMetadata timesheetEntity = new EntityMetadata();
timesheetEntity.SchemaName = "new_timesheet";
timesheetEntity.OwnershipType = new CrmOwnershipTypes();
timesheetEntity.OwnershipType.Value = OwnershipTypes.UserOwned;
timesheetEntity.DisplayName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Timesheet", 1033);
timesheetEntity.DisplayCollectionName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Timesheets", 1033);
timesheetEntity.Description = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Employee Timesheet", 1033);

// Create the primary attribute.
StringAttributeMetadata primaryAttribute = new StringAttributeMetadata();
primaryAttribute.SchemaName = "new_name";
primaryAttribute.RequiredLevel = new CrmAttributeRequiredLevel();
primaryAttribute.RequiredLevel.Value = AttributeRequiredLevel.None;
primaryAttribute.MaxLength = new MetadataServiceSdk.CrmNumber();
primaryAttribute.MaxLength.Value = 100;
primaryAttribute.DisplayName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Name", 1033);
primaryAttribute.Description = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Employee Name", 1033);

// Create the entity request.
CreateEntityRequest createEntity = new CreateEntityRequest();
createEntity.Entity = timesheetEntity;
createEntity.HasActivities = false;
createEntity.HasNotes = true;
createEntity.PrimaryAttribute = primaryAttribute;

// Execute the request.
CreateEntityResponse entityResponse = (CreateEntityResponse )metadataService.Execute(createEntity);

// Publish the new custom entity.
// Note that the custom entities cannot be used until they have been published.
PublishAllXmlRequest publishAllRequest = new PublishAllXmlRequest();
PublishAllXmlResponse publishAllResponse = (PublishAllXmlResponse)metadataService.Execute(publishAllRequest);

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...