public static object Convert(object value, Dynamics365Entity entity, string attributeLogicalName, Dynamics365Connection connection, string targetEntityLogicalName) { object convertedValue = default(object); EntityMetadata entityMetadata = entity.GetEntityMetadata(connection); AttributeMetadata attributeMetadata = entityMetadata.Attributes.FirstOrDefault(findField => findField.LogicalName == attributeLogicalName); Dynamics365TypeConverter converter = new Dynamics365TypeConverter(attributeMetadata, targetEntityLogicalName); Type destinationType = converter.Dynamics365Type; if (converter.CanConvertTo(destinationType)) { try { convertedValue = converter.ConvertTo(value, destinationType); } catch (Exception ex) { throw new ArgumentException(string.Format("Cannot convert {0} '{1}' to {2}: {3}", attributeMetadata.DisplayName.UserLocalizedLabel.Label, value, destinationType.Name, ex.Message), ex); } } else { throw new ArgumentException(string.Format("Cannot convert {0} '{1}' to {2}.", attributeMetadata.DisplayName.UserLocalizedLabel.Label, value, destinationType.Name)); } return(convertedValue); }
public static List <Dynamics365Relationship> GetRelationships(Dynamics365Entity entity, Dynamics365Connection connection) { ConnectionCache cache = new ConnectionCache(connection); string cacheKey = string.Format("GetRelationships:{0}", entity.LogicalName); List <Dynamics365Relationship> relationships = (List <Dynamics365Relationship>)cache[cacheKey]; if (relationships == null) { relationships = new List <Dynamics365Relationship>(); RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = entity.LogicalName, EntityFilters = EntityFilters.Relationships, RetrieveAsIfPublished = false }; using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy) { RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request); foreach (ManyToManyRelationshipMetadata metadata in response.EntityMetadata.ManyToManyRelationships) { Dynamics365Relationship relationship = new Dynamics365Relationship() { SchemaName = metadata.SchemaName, EntityLogicalName = metadata.Entity1LogicalName == entity.LogicalName ? metadata.Entity1LogicalName : metadata.Entity2LogicalName, RelatedEntityLogicalName = metadata.Entity1LogicalName == entity.LogicalName ? metadata.Entity2LogicalName : metadata.Entity1LogicalName }; relationships.Add(relationship); } foreach (OneToManyRelationshipMetadata metadata in response.EntityMetadata.ManyToOneRelationships) { Dynamics365Relationship relationship = new Dynamics365Relationship() { SchemaName = metadata.SchemaName, EntityLogicalName = metadata.ReferencedEntity == entity.LogicalName ? metadata.ReferencedEntity : metadata.ReferencingEntity, RelatedEntityLogicalName = metadata.ReferencedEntity == entity.LogicalName ? metadata.ReferencingEntity : metadata.ReferencedEntity }; relationships.Add(relationship); } foreach (OneToManyRelationshipMetadata metadata in response.EntityMetadata.OneToManyRelationships) { Dynamics365Relationship relationship = new Dynamics365Relationship() { SchemaName = metadata.SchemaName, EntityLogicalName = metadata.ReferencedEntity == entity.LogicalName ? metadata.ReferencedEntity : metadata.ReferencingEntity, RelatedEntityLogicalName = metadata.ReferencedEntity == entity.LogicalName ? metadata.ReferencingEntity : metadata.ReferencedEntity }; relationships.Add(relationship); } } cache[cacheKey] = relationships; } return(relationships); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value != default(Dynamics365Entity)) { Dynamics365Entity entity = (Dynamics365Entity)value; return(string.Format("{0} ({1})", entity.DisplayName, entity.LogicalName)); } return(null); }
public List <Dynamics365Entity> GetEntities() { List <Dynamics365Entity> entities = new List <Dynamics365Entity>(); try { entities.AddRange(Dynamics365Entity.GetEntities((Dynamics365Connection)Connection)); } catch { } return(entities); }
/// <summary> /// Gets a list of entities that are owned by a user or team. /// </summary> /// <returns>A list of Dynamics365Entity objects.</returns> public List <Dynamics365Entity> GetUserOrTeamOwnedEntities() { List <Dynamics365Entity> entities = new List <Dynamics365Entity>(); try { entities.AddRange(Dynamics365Entity.GetEntities(Connection).Where(entity => entity.IsUserTeamOwned).ToList()); } catch { } return(entities); }
/// <summary> /// Gets entity fields relevant to the operation type. /// </summary> /// <param name="operationType">The operation type.</param> /// <returns>The fields.</returns> public static List <Dynamics365Field> GetFields(Dynamics365Entity entity, Dynamics365Connection connection) { if (entity == default(Dynamics365Entity)) { throw new ArgumentException("Entity cannot be null", nameof(entity)); } if (connection == default(Dynamics365Connection)) { throw new ArgumentException("Connection cannot be null", nameof(connection)); } ConnectionCache cache = new ConnectionCache(connection); string cacheKey = string.Format("GetFields:{0}", entity.LogicalName); List <Dynamics365Field> fields = (List <Dynamics365Field>)cache[cacheKey]; if (fields == default(List <Dynamics365Field>)) { fields = new List <Dynamics365Field>(); RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = entity.LogicalName, EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = false }; using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy) { RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request); foreach (AttributeMetadata attributeMetadata in response.EntityMetadata.Attributes) { if ((bool)attributeMetadata.IsValidForRead) { Dynamics365Field field = CreateFromMetadata(attributeMetadata, connection); if (field != null) { fields.Add(field); } } } } fields.Sort((field1, field2) => field1.DisplayName.CompareTo(field2.DisplayName)); cache[string.Format(cacheKey, entity.LogicalName)] = fields; } return(fields); }
/// <summary> /// Gets a list of Dynamics365Entity objects. /// </summary> /// <returns>The list of Dynamics365Entity objects.</returns> public List <Dynamics365Entity> GetEntities() { List <Dynamics365Entity> entities = new List <Dynamics365Entity>(); try { if (Parent != default(IConnection)) { entities.AddRange(Dynamics365Entity.GetEntities((Dynamics365Connection)Parent)); } } catch { } return(entities); }
/// <summary> /// Gets views of the specified type for the specified enttiy. /// </summary> /// <param name="entity"></param> /// <param name="viewType"></param> /// <param name="connection"></param> /// <returns></returns> public static List <Dynamics365View> GetViews(Dynamics365Entity entity, ViewType viewType, Dynamics365Connection connection) { List <Dynamics365View> views = null; if (viewType == ViewType.System) { views = GetSystemViews(entity, connection); } else if (viewType == ViewType.Personal) { views = GetPersonalViews(entity, connection); } return(views); }
public List <Field> GetDynamics365SetStateDataDestinationFields() { List <Field> fields = new List <Field>(); try { List <Dynamics365State> states = Dynamics365State.GetStates(Entity, Connection); if (states?.Count > 0) { // add state and status field from destination entity Dynamics365State state = states[0]; Dynamics365Status status = state.Statuses[0]; fields.AddRange(Entity.GetFields(Connection).Where(field => ((Dynamics365Field)field).LogicalName == state.LogicalName || ((Dynamics365Field)field).LogicalName == status.LogicalName)); } if (Entity.LogicalName == CASE_ENTITY_NAME) { Dynamics365Entity incidentResolution = Dynamics365Entity.Create(CASE_RESOLUTION_ENTITY_NAME, Connection); fields.AddRange(incidentResolution.GetFields(Connection).Where(field => ((Dynamics365Field)field).LogicalName == "subject" || ((Dynamics365Field)field).LogicalName == "description")); } else if (Entity.LogicalName == QUOTE_ENTITY_NAME) { Dynamics365Entity quoteClose = Dynamics365Entity.Create(CASE_RESOLUTION_ENTITY_NAME, Connection); fields.AddRange(quoteClose.GetFields(Connection).Where(field => ((Dynamics365Field)field).LogicalName == "subject" || ((Dynamics365Field)field).LogicalName == "description")); } else if (Entity.LogicalName == OPPORTUNITY_ENTITY_NAME) { Dynamics365Entity opportunityClose = Dynamics365Entity.Create(CASE_RESOLUTION_ENTITY_NAME, Connection); fields.AddRange(opportunityClose.GetFields(Connection).Where(field => ((Dynamics365Field)field).LogicalName == "subject" || ((Dynamics365Field)field).LogicalName == "description" || ((Dynamics365Field)field).LogicalName == "actualend" || ((Dynamics365Field)field).LogicalName == "actualrevenue")); } // todo - check this is correct. need to be able to support multiple values for 'first non-null value' logic //foreach (FieldValue value in values) //{ // // prevent fields from being selected more than once // fields.RemoveAll(field => field == value.DestinationField); //} } catch { } return(fields); }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="connection"></param> /// <returns></returns> private static List <Dynamics365View> GetPersonalViews(Dynamics365Entity entity, IConnection connection) { ConnectionCache cache = new ConnectionCache(connection); string cacheKey = string.Format("GetPersonalViews:{0}:{1}", typeof(Dynamics365View).Name, entity.LogicalName); List <Dynamics365View> views = (List <Dynamics365View>)cache[cacheKey]; if (views == null) { views = new List <Dynamics365View>(); QueryExpression query = new QueryExpression("userquery"); query.Criteria.AddCondition("returnedtypecode", ConditionOperator.Equal, entity.ObjectTypeCode); query.Criteria.AddCondition("fetchxml", ConditionOperator.NotNull); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); query.ColumnSet = new ColumnSet(new string[] { "name", "fetchxml" }); // todo - not working? RetrieveMultipleRequest request = new RetrieveMultipleRequest() { Query = query }; using (OrganizationServiceProxy proxy = ((Dynamics365Connection)connection).OrganizationServiceProxy) { RetrieveMultipleResponse response = (RetrieveMultipleResponse)proxy.Execute(request); foreach (Entity viewEntity in response.EntityCollection.Entities) { Dynamics365View view = new Dynamics365View() { ID = viewEntity.Id, DisplayName = (string)viewEntity.Attributes["name"], FetchXml = (string)viewEntity.Attributes["fetchxml"] }; views.Add(view); } views.Sort((view1, view2) => view1.DisplayName.CompareTo(view2.DisplayName)); } cache[cacheKey] = views; } return(views); }
public List <Dynamics365Entity> GetTargetEntities() { List <Dynamics365Entity> targetEntities = new List <Dynamics365Entity>(); try { // todo - this should only display on the form for fields that are lookups. it's not tied in any way to the dynamics365lookupvalue if (((Dynamics365Field)DestinationField).Targets != default(string[])) { foreach (string target in ((Dynamics365Field)DestinationField).Targets) { targetEntities.Add(Dynamics365Entity.Create(target, ((Dynamics365RecordOperation)Parent).Connection)); } } } catch { } return(targetEntities); }
/// <summary> /// Creates an empty DataTable for the specified fields. /// </summary> /// <param name="fields">The fields.</param> /// <returns>The data table.</returns> protected DataTable CreateEmptyDataTable(List <Dynamics365Field> fields) { DataTable dataTable = new DataTable(Name); foreach (Dynamics365Field field in fields) { EntityMetadata entityMetadata = Dynamics365Entity.Create(field.EntityLogicalName, (Dynamics365Connection)Parent).GetEntityMetadata((Dynamics365Connection)Parent); AttributeMetadata attributeMetadata = entityMetadata.Attributes.FirstOrDefault(findField => findField.LogicalName == field.LogicalName); if (attributeMetadata != default(AttributeMetadata)) { AddDataColumns(dataTable, field, attributeMetadata); } else { throw new ApplicationException(string.Format("The field {0} could not be found in {1}", field.LogicalName, entityMetadata.LogicalName)); } } return(dataTable); }
/// <summary> /// Gets a list of fields in an entity or link-entity node of a FetchXML query. /// </summary> /// <param name="entityNode">The entity node.</param> /// <returns>The fields.</returns> private List <Dynamics365Field> GetEntityNodeFields(XmlNode entityNode) { List <Dynamics365Field> fields = new List <Dynamics365Field>(); Dynamics365Entity entity = Dynamics365Entity.Create(entityNode.Attributes["name"].Value, (Dynamics365Connection)Parent); EntityMetadata entityMetadata = entity.GetEntityMetadata((Dynamics365Connection)Parent); foreach (XmlNode node in entityNode.ChildNodes) { if (node.Name.ToLower() == "attribute") { string attributeName = node.Attributes["name"].Value; AttributeMetadata attributeMetadata = entityMetadata.Attributes.FirstOrDefault(findField => findField.LogicalName == attributeName); if (attributeMetadata != default(AttributeMetadata)) { fields.Add(Dynamics365Field.CreateFromMetadata(attributeMetadata, (Dynamics365Connection)Parent)); } else { throw new ApplicationException(string.Format("The {0} field in {1} does not exist in Dynamics 365", attributeName, Name)); } } if (node.Name.ToLower() == "link-entity") { List <Dynamics365Field> linkedFields = GetEntityNodeFields(node); foreach (Dynamics365Field linkedField in linkedFields) { fields.Add(linkedField); } } } return(fields); }
public static List <Dynamics365State> GetStates(Dynamics365Entity entity, Dynamics365Connection connection) { ConnectionCache cache = new ConnectionCache(connection); string cacheKey = string.Format("GetStates:{0}", entity.LogicalName); List <Dynamics365State> states = (List <Dynamics365State>)cache[cacheKey]; if (states == null) { states = new List <Dynamics365State>(); RetrieveEntityRequest request = new RetrieveEntityRequest() { LogicalName = entity.LogicalName, EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = false }; using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy) { RetrieveEntityResponse response = (RetrieveEntityResponse)proxy.Execute(request); StateAttributeMetadata stateMetadata = (StateAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StateAttributeMetadata); if (stateMetadata != null) { foreach (StateOptionMetadata stateOption in stateMetadata.OptionSet.Options) { Dynamics365State state = new Dynamics365State() { Code = (int)stateOption.Value, Name = stateOption.Label.UserLocalizedLabel.Label, LogicalName = stateMetadata.LogicalName }; StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StatusAttributeMetadata); if (statusMetadata != null) { foreach (StatusOptionMetadata statusOption in statusMetadata.OptionSet.Options) { if (statusOption.State == state.Code) { Dynamics365Status status = new Dynamics365Status() { Code = (int)statusOption.Value, Name = statusOption.Label.UserLocalizedLabel.Label, LogicalName = statusMetadata.LogicalName }; state.Statuses.Add(status); } } //state.Statuses.Sort((status1, status2) => status1.Name.CompareTo(status2.Name)); } states.Add(state); } } } //states.Sort((state1, state2) => state1.Name.CompareTo(state2.Name)); cache[cacheKey] = states; } return(states); }
protected override string GetRequestDescription(OrganizationRequest request) { Guid id = Guid.Empty; string state = mode == SetStateMode.Fixed ? State.Name : "<State>"; string status = mode == SetStateMode.Fixed ? Status.Name : "<Status>"; if (request is UpdateRequest updateRequest) { id = updateRequest.Target.Id; } else if (request is SetStateRequest setStateRequest) { id = setStateRequest.EntityMoniker.Id; } else if (request is CloseIncidentRequest closeIncidentRequest) { id = ((EntityReference)closeIncidentRequest.IncidentResolution[CASE_RESOLUTION_INCIDENT_ID]).Id; state = "Resolved"; EntityMetadata metadata = Dynamics365Entity.Create(CASE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME)); status = statusMetadata.OptionSet.Options.First(option => option.Value == closeIncidentRequest.Status.Value).Label.UserLocalizedLabel.Label; } else if (request is ReviseQuoteRequest reviseQuoteRequest) { id = reviseQuoteRequest.QuoteId; state = "Draft"; status = "In Progress"; } else if (request is WinQuoteRequest winQuoteRequest) { id = ((EntityReference)winQuoteRequest.QuoteClose[QUOTE_CLOSE_QUOTE_ID]).Id; state = "Won"; status = "Won"; } else if (request is CloseQuoteRequest closeQuoteRequest) { id = ((EntityReference)closeQuoteRequest.QuoteClose[QUOTE_CLOSE_QUOTE_ID]).Id; state = "Closed"; EntityMetadata metadata = Dynamics365Entity.Create(QUOTE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME)); status = statusMetadata.OptionSet.Options.First(option => option.Value == closeQuoteRequest.Status.Value).Label.UserLocalizedLabel.Label; } else if (request is WinOpportunityRequest winOpportunityRequest) { id = ((EntityReference)winOpportunityRequest.OpportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID]).Id; state = "Won"; EntityMetadata metadata = Dynamics365Entity.Create(OPPORTUNITY_ENTITY_NAME, Connection).GetEntityMetadata(Connection); StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME)); status = statusMetadata.OptionSet.Options.First(option => option.Value == winOpportunityRequest.Status.Value).Label.UserLocalizedLabel.Label; } else if (request is LoseOpportunityRequest loseOpportunityRequest) { id = ((EntityReference)loseOpportunityRequest.OpportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID]).Id; state = "Lost"; EntityMetadata metadata = Dynamics365Entity.Create(OPPORTUNITY_ENTITY_NAME, Connection).GetEntityMetadata(Connection); StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME)); status = statusMetadata.OptionSet.Options.First(option => option.Value == loseOpportunityRequest.Status.Value).Label.UserLocalizedLabel.Label; } return(string.Format(Properties.Resources.Dynamics365SetStateOperationRequestDescription, Entity.DisplayName, id, state, status)); }
protected override List <OrganizationRequest> CreateOrganisationRequests(DataRow row, CancellationToken cancel, IProgress <ExecutionProgress> progress) { List <OrganizationRequest> requests = new List <OrganizationRequest>(); // todo - hard coded strings OptionSetValue stateValue = mode == SetStateMode.Fixed ? new OptionSetValue(State.Code) : (OptionSetValue)Values.First(fieldValue => ((Dynamics365Field)fieldValue.DestinationField).LogicalName == STATECODE_NAME).GetValue(row, cancel, progress); OptionSetValue statusValue = mode == SetStateMode.Fixed ? new OptionSetValue(Status.Code) : (OptionSetValue)Values.First(fieldValue => ((Dynamics365Field)fieldValue.DestinationField).LogicalName == STATUSCODE_NAME).GetValue(row, cancel, progress); if (Entity.LogicalName == CASE_ENTITY_NAME && stateValue.Value == StateCode.CaseResolved) { EntityMetadata metadata = Dynamics365Entity.Create(CASE_RESOLUTION_ENTITY_NAME, Connection).GetEntityMetadata(Connection); Entity incidentResolution = new Entity(metadata.LogicalName); incidentResolution[CASE_RESOLUTION_INCIDENT_ID] = GetTargetEntity(row, cancel, progress).ToEntityReference(); if (mode == SetStateMode.Variable) { PopulateEntityFromDataRow(incidentResolution, row, cancel, progress); } requests.Add(new CloseIncidentRequest() { IncidentResolution = incidentResolution, Status = statusValue }); } else if (Entity.LogicalName == QUOTE_ENTITY_NAME && stateValue.Value == StateCode.QuoteDraft) { requests.Add(new ReviseQuoteRequest() { QuoteId = GetTargetEntity(row, cancel, progress).Id, ColumnSet = new ColumnSet(true) }); } else if (Entity.LogicalName == QUOTE_ENTITY_NAME && stateValue.Value == StateCode.QuoteWon) { EntityMetadata metadata = Dynamics365Entity.Create(QUOTE_CLOSE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); Entity quoteClose = new Entity(metadata.LogicalName); quoteClose[QUOTE_CLOSE_QUOTE_ID] = GetTargetEntity(row, cancel, progress).ToEntityReference(); if (mode == SetStateMode.Variable) { PopulateEntityFromDataRow(quoteClose, row, cancel, progress); } requests.Add(new WinQuoteRequest() { QuoteClose = quoteClose, Status = statusValue }); } else if (Entity.LogicalName == QUOTE_ENTITY_NAME && stateValue.Value == StateCode.QuoteClosed) { EntityMetadata metadata = Dynamics365Entity.Create(QUOTE_CLOSE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); Entity quoteClose = new Entity(metadata.LogicalName); quoteClose[QUOTE_CLOSE_QUOTE_ID] = GetTargetEntity(row, cancel, progress).ToEntityReference(); if (mode == SetStateMode.Variable) { PopulateEntityFromDataRow(quoteClose, row, cancel, progress); } requests.Add(new CloseQuoteRequest() { QuoteClose = quoteClose, Status = statusValue }); } else if (Entity.LogicalName == OPPORTUNITY_ENTITY_NAME && stateValue.Value == StateCode.OpportunityWon) { EntityMetadata metadata = Dynamics365Entity.Create(OPPORTUNITY_CLOSE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); Entity opportunityClose = new Entity(metadata.LogicalName); opportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID] = GetTargetEntity(row, cancel, progress).ToEntityReference(); if (mode == SetStateMode.Variable) { PopulateEntityFromDataRow(opportunityClose, row, cancel, progress); } requests.Add(new WinOpportunityRequest() { OpportunityClose = opportunityClose, Status = statusValue }); } else if (Entity.LogicalName == OPPORTUNITY_ENTITY_NAME && State.Code == StateCode.OpportunityLost) { EntityMetadata metadata = Dynamics365Entity.Create(OPPORTUNITY_CLOSE_ENTITY_NAME, Connection).GetEntityMetadata(Connection); Entity opportunityClose = new Entity(metadata.LogicalName); opportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID] = GetTargetEntity(row, cancel, progress).ToEntityReference(); if (mode == SetStateMode.Variable) { PopulateEntityFromDataRow(opportunityClose, row, cancel, progress); } requests.Add(new LoseOpportunityRequest() { OpportunityClose = opportunityClose, Status = statusValue }); } else if (Entity.LogicalName == PROCESS_ENTITY_NAME) { requests.Add(new SetStateRequest() { EntityMoniker = new EntityReference(Entity.LogicalName, GetTargetEntity(row, cancel, progress).Id), State = new OptionSetValue(stateValue.Value), Status = new OptionSetValue(statusValue.Value) }); } else { UpdateRequest request = new UpdateRequest() { Target = GetTargetEntity(row, cancel, progress) }; request.Target.Attributes[STATECODE_NAME] = stateValue; request.Target.Attributes[STATUSCODE_NAME] = statusValue; requests.Add(request); } return(requests); }
/// <summary> /// Appends rows to the specified data table from the specified EntityCollection. /// </summary> /// <param name="dataTable">The DataTable.</param> /// <param name="entities">The EntityCollection.</param> /// <param name="recordLimit">The record limit.</param> /// <returns>A DataTable with appended rows.</returns> protected DataTable AppendRows(DataTable dataTable, EntityCollection entities, int recordLimit) { Dictionary <string, EntityMetadata> metadata = new Dictionary <string, EntityMetadata>(); foreach (DataColumn column in dataTable.Columns) { string entityLogicalName = column.ColumnName.Substring(0, column.ColumnName.IndexOf(".")); if (!metadata.ContainsKey(entityLogicalName)) { metadata.Add(entityLogicalName, Dynamics365Entity.Create(entityLogicalName, (Dynamics365Connection)Parent).GetEntityMetadata((Dynamics365Connection)Parent)); } } for (int recordIndex = 0; recordIndex < entities.Entities.Count && dataTable.Rows.Count < recordLimit; recordIndex++) { Entity record = entities.Entities[recordIndex]; DataRow row = dataTable.NewRow(); foreach (KeyValuePair <string, object> attribute in record.Attributes) { string entityLogicalName = record.LogicalName; string attributeLogicalName = attribute.Key; object attributeValue = attribute.Value; if (attribute.Value is AliasedValue) { AliasedValue aliasedValue = (AliasedValue)attribute.Value; entityLogicalName = aliasedValue.EntityLogicalName; attributeLogicalName = aliasedValue.AttributeLogicalName; attributeValue = aliasedValue.Value; } string nativeColumnName = string.Format("{0}.{1}", entityLogicalName, attributeLogicalName); if (DataTypes == DataTypes.Native) { if (dataTable.Columns.Contains(nativeColumnName)) { row[nativeColumnName] = attributeValue; } } else if (DataTypes == DataTypes.Neutral) { AttributeMetadata attributeMetadata = metadata[entityLogicalName].Attributes.FirstOrDefault(findField => findField.LogicalName == attributeLogicalName); Dynamics365TypeConverter converter = new Dynamics365TypeConverter(attributeMetadata); if (converter.Dynamics365Type == typeof(EntityReference) || converter.Dynamics365Type == typeof(EntityCollection)) { if (LookupBehaviour == LookupBehaviour.Name || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier) { string nameColumn = string.Format("{0}.Name", nativeColumnName); if (dataTable.Columns.Contains(nameColumn)) { if (converter.Dynamics365Type == typeof(EntityReference)) { row[nameColumn] = ((EntityReference)attributeValue).Name; } else if (converter.Dynamics365Type == typeof(EntityCollection)) { string names = string.Empty; foreach (Entity entity in ((EntityCollection)attributeValue).Entities) { EntityReference party = (EntityReference)entity["partyid"]; names = names == string.Empty ? party.Name : string.Concat(names, PARTYLIST_DELIMITER, party.Name); } row[nameColumn] = names; } } } if (LookupBehaviour == LookupBehaviour.Identifier || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier) { string identifierColumn = string.Format("{0}.Identifier", nativeColumnName); if (dataTable.Columns.Contains(identifierColumn)) { if (converter.Dynamics365Type == typeof(EntityReference)) { row[identifierColumn] = ((EntityReference)attributeValue).Id.ToString(); } else if (converter.Dynamics365Type == typeof(EntityCollection)) { string identifiers = string.Empty; foreach (Entity entity in ((EntityCollection)attributeValue).Entities) { EntityReference party = (EntityReference)entity["partyid"]; identifiers = identifiers == string.Empty ? party.Id.ToString() : string.Concat(identifiers, PARTYLIST_DELIMITER, party.Id.ToString()); } row[identifierColumn] = identifiers; } } } if (LookupBehaviour == LookupBehaviour.Entity || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier) { string entityColumn = string.Format("{0}.Entity", nativeColumnName); if (dataTable.Columns.Contains(entityColumn)) { if (converter.Dynamics365Type == typeof(EntityReference)) { row[entityColumn] = ((EntityReference)attributeValue).LogicalName; } else if (converter.Dynamics365Type == typeof(EntityCollection)) { string logicalNames = string.Empty; foreach (Entity entity in ((EntityCollection)attributeValue).Entities) { EntityReference party = (EntityReference)entity["partyid"]; logicalNames = logicalNames == string.Empty ? party.LogicalName : string.Concat(logicalNames, PARTYLIST_DELIMITER, party.LogicalName); } row[entityColumn] = logicalNames; } } } } else if (converter.Dynamics365Type == typeof(OptionSetValue)) { if (OptionSetBehaviour == OptionSetBehaviour.Name || OptionSetBehaviour == OptionSetBehaviour.NameAndCode) { string nameColumn = string.Format("{0}.Name", nativeColumnName); if (dataTable.Columns.Contains(nameColumn)) { EnumAttributeMetadata enumMetadata = (EnumAttributeMetadata)attributeMetadata; OptionMetadata optionMetadata = enumMetadata.OptionSet.Options.FirstOrDefault(option => option.Value == ((OptionSetValue)attributeValue).Value); if (optionMetadata != default(OptionMetadata)) { row[nameColumn] = optionMetadata.Label.UserLocalizedLabel.Label; } } } if (OptionSetBehaviour == OptionSetBehaviour.Code || OptionSetBehaviour == OptionSetBehaviour.NameAndCode) { string codeColumn = string.Format("{0}.Code", nativeColumnName); if (dataTable.Columns.Contains(codeColumn)) { row[codeColumn] = ((OptionSetValue)attributeValue).Value; } } } else if (converter.Dynamics365Type == typeof(OptionSetValueCollection)) { if (OptionSetBehaviour == OptionSetBehaviour.Name || OptionSetBehaviour == OptionSetBehaviour.NameAndCode) { string nameColumn = string.Format("{0}.Name", nativeColumnName); if (dataTable.Columns.Contains(nameColumn)) { List <string> labels = new List <string>(); EnumAttributeMetadata enumMetadata = (EnumAttributeMetadata)attributeMetadata; OptionSetValueCollection optionSetValues = (OptionSetValueCollection)attributeValue; foreach (OptionSetValue optionSetValue in optionSetValues) { OptionMetadata optionMetadata = enumMetadata.OptionSet.Options.FirstOrDefault(option => option.Value == optionSetValue.Value); if (optionMetadata != default(OptionMetadata)) { labels.Add(optionMetadata.Label.UserLocalizedLabel.Label); } } row[nameColumn] = string.Join(Dynamics365TypeConverter.MULTI_OPTION_SET_DELIMITER, labels.Select(label => label)); } } if (OptionSetBehaviour == OptionSetBehaviour.Code || OptionSetBehaviour == OptionSetBehaviour.NameAndCode) { string codeColumn = string.Format("{0}.Code", nativeColumnName); if (dataTable.Columns.Contains(codeColumn)) { OptionSetValueCollection optionSetValues = (OptionSetValueCollection)attributeValue; row[codeColumn] = string.Join(Dynamics365TypeConverter.MULTI_OPTION_SET_DELIMITER, optionSetValues.Select(optionSet => optionSet.Value.ToString())); } } } else { if (dataTable.Columns.Contains(nativeColumnName)) { row[nativeColumnName] = converter.ConvertFrom(null, null, attributeValue); } } } } dataTable.Rows.Add(row); } return(dataTable); }
public static object Convert(object value, Dynamics365Entity entity, string attributeLogicalName, Dynamics365Connection connection) { return(Convert(value, entity, attributeLogicalName, connection, default(string))); }