Softchief Solutions

Technologies | Life Tips | Socials & Everything

C# Snippets

Convert Entity Collection to Data Table

public DataTable convertEntityCollectionToDataTable(EntityCollection ec)
{
DataTable dt = new DataTable();
int totalCount = ec.Entities.Count;
for (int i = 0; i < totalCount; i++)
{
DataRow row = dt.NewRow();
Entity myEntity = (Entity)ec.Entities[i];
var keys= myEntity.Attributes.Keys;
foreach (var item in keys)
{
string columnName = item;
string value = getValuefromAttribute(myEntity.Attributes[item]);
if (dt.Columns.IndexOf(columnName) == -1)
{
dt.Columns.Add(item, Type.GetType(“System.String”));
}
row[columnName] = value;
}
dt.Rows.Add(row);
}
return dt;
}

private string getValuefromAttribute(object p)
{
if (p.ToString() == “Microsoft.Xrm.Sdk.EntityReference”)
{
return ((EntityReference)p).Name;
}
if (p.ToString() == “Microsoft.Xrm.Sdk.OptionSetValue”)
{
return ((OptionSetValue)p).Value.ToString();
}
if (p.ToString() == “Microsoft.Xrm.Sdk.Money”)
{
return ((Money)p).Value.ToString();
}
if (p.ToString() == “Microsoft.Xrm.Sdk.AliasedValue”)
{
return ((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString();
}
else
{
return p.ToString();
}
}

Run a Plugin for all entities

Use “none”  as primary entity option using Plugin-registration tool.

 And identify the entity in code to do the logic.

public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = 
(IPluginExecutionContext) 
serviceProvider.GetService(typeof(IPluginExecutionContext));

    if (context.InputParameters.Contains("Target") &&
        context.InputParameters["Target"] is Entity)
    {
        Entity entity = (Entity)context.InputParameters["Target"];
        switch (entity.LogicalName)
        {
        case "account":
             // Do your logic
            break;

        case "contact":
            //Do your logic
            break;
       }
}

Check if the user is offline in Plugin

if (context.IsExecutingOffline || context.IsOfflinePlayback)
return;

Advertisements
%d bloggers like this: