C# FUNCTIONS
Get Primary Field Name
public static string GetPrimaryFieldName(string entityname)
{
RetrieveEntityRequest retrievesEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Entity,
LogicalName = entityname
};
//Execute Request
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)service.Execute(retrievesEntityRequest);
// Gets the primaryid attribute
// var idFieldName = retrieveEntityResponse.EntityMetadata.PrimaryIdAttribute;
// Gets the primary field name
return retrieveEntityResponse.EntityMetadata.PrimaryNameAttribute;
}
Create Instance of a class
public object CreateEntity(string entityname)
{
var assembly = Assembly.Load("CW_CommonUtilities_Entities");
var typeassembly = assembly.GetExportedTypes().Where(x => x.Name != null && x.Name.ToLower() == entityname.ToLower()).Select(x => x.FullName).FirstOrDefault();
return assembly.CreateInstance(typeassembly);
}
Add attribute to entity based on the type
public void AddAttributeToEntity(string key, string value, string entityname, ref Entity entity)
{
var parsedEntity = CreateEntity(entityname);
var attribute = parsedEntity.GetType().GetProperties().Where(x => x.Name != null && x.Name.ToLower() == key).Select(x => x).FirstOrDefault();
string typeAttribute = string.Empty;
int optionValue = int.MinValue;
if (attribute.PropertyType.GenericTypeArguments != null && attribute.PropertyType.GenericTypeArguments.Length > 0)
{
if (attribute.PropertyType.GenericTypeArguments.First().Namespace.Contains("Common"))
{
var optionset = CreateEntity(attribute.PropertyType.GenericTypeArguments.First().Name);
optionValue = (int)Enum.Parse(optionset.GetType(), optionset.GetType().GetFields().Where(x => x.Name.ToLower() == value.ToLower().Replace(" ", "")).Select(x => x.Name).FirstOrDefault());
typeAttribute = optionset.GetType().BaseType.Name;
}
else
{
typeAttribute = attribute.PropertyType.GenericTypeArguments.FirstOrDefault().Name;
}
}
else
{
typeAttribute = attribute.PropertyType.Name;
}
switch (typeAttribute)
{
case "EntityReference":
var entityInTheBag = (Entity)Bag[value];
entity[key] = entityInTheBag.ToEntityReference();
break;
case "Enum":
entity[key] = new OptionSetValue(optionValue);
break;
case "DateTime":
entity[key] = DateTime.Parse(value);
break;
case "Boolean":
entity[key] = bool.Parse(value);
break;
default:
entity[key] = value;
break;
}
}