Example #1
0
 CodeTypeReference ITypeMappingService.GetTypeForAttributeType(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     var type = typeof (object);
     if (attributeMetadata.AttributeType.HasValue)
     {
         var key = attributeMetadata.AttributeType.Value;
         if (_attributeTypeMapping.ContainsKey(key))
         {
             type = _attributeTypeMapping[key];
         }
         else
         {
             if (key == AttributeTypeCode.PartyList)
             {
                 return BuildCodeTypeReferenceForPartyList(services);
             }
             var attributeOptionSet = GetAttributeOptionSet(attributeMetadata);
             if (attributeOptionSet != null)
             {
                 return BuildCodeTypeReferenceForOptionSet(attributeMetadata.LogicalName, entityMetadata, attributeOptionSet, services);
             }
         }
         if (type.IsValueType)
         {
             type = typeof (Nullable<>).MakeGenericType(new[] {type});
         }
     }
     return TypeRef(type);
 }
        private AttributeMetadata CloneAttributes(AttributeMetadata att, string schemaName, AttributeMetadata newAttributeType)
        {
            var clone = CloneAttributes((dynamic)(newAttributeType ?? att));

            clone.CanModifyAdditionalSettings = att.CanModifyAdditionalSettings;
            clone.Description = att.Description;
            clone.DisplayName = att.DisplayName;
            clone.ExtensionData = att.ExtensionData;
            clone.IsAuditEnabled = att.IsAuditEnabled;
            clone.IsCustomizable = att.IsCustomizable;
            clone.IsRenameable = att.IsRenameable;
            clone.IsSecured = att.IsSecured;
            clone.IsValidForAdvancedFind = att.IsValidForAdvancedFind;
            clone.LinkedAttributeId = att.LinkedAttributeId;
            clone.RequiredLevel = att.RequiredLevel;


            // Fix for issue 1468 Inactive Language Causing Error
            RemoveInvalidLanguageLocalizedLabels(att.Description);
            RemoveInvalidLanguageLocalizedLabels(att.DisplayName);

            clone.LogicalName = schemaName.ToLower();
            clone.SchemaName = schemaName;

            // Update EntityLogicalName for other methods to use
            SetEntityLogicalName(clone, att.EntityLogicalName);
            return clone;
        }
Example #3
0
 /// <summary>
 /// Ideally, we wouldn't generate any attributes, but we must in order to leverage
 /// the logic in CrmSvcUtil.  If the attribute for an OptionSet is not generated,
 /// then a null reference exception is thrown when attempting to create the
 /// OptionSet.  We will remove these in our ICustomizeCodeDomService implementation.
 /// </summary>
 public bool GenerateAttribute(
     AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     return (attributeMetadata.AttributeType == AttributeTypeCode.Picklist
         || attributeMetadata.AttributeType == AttributeTypeCode.State
         || attributeMetadata.AttributeType == AttributeTypeCode.Status);
 }
        /// <summary>
        /// フィールドのオプションセットを取得する。
        /// </summary>
        /// <param name="attr"></param>
        public OptionSetBean(AttributeMetadata attr)
        {
            valueMap = new Dictionary<int, Label>();
            PicklistAttributeMetadata picklistAttr = attr as PicklistAttributeMetadata;
            StateAttributeMetadata stateAttr = attr as StateAttributeMetadata;
            StatusAttributeMetadata statusAttr = attr as StatusAttributeMetadata;

            // オプションセットを取得する。
            OptionSetMetadata option = null;
            if (picklistAttr != null)
            {
                option = picklistAttr.OptionSet;
            }
            else if (stateAttr != null)
            {
                option = stateAttr.OptionSet;
            }
            else if (statusAttr != null)
            {
                option = statusAttr.OptionSet;
            }
            else
            {
                return;
            }

            foreach (OptionMetadata opt in option.Options)
            {
                if (opt.Value != null)
                {

                    valueMap.Add((int)opt.Value, opt.Label);
                }
            }
        }
        private void UpdateForms(IOrganizationService service, AttributeMetadata att)
        {
            /*
             * <row>
             *   <cell id="{056d159e-9144-d809-378b-9e04a7626953}" showlabel="true" locklevel="0">
             *     <labels>
             *       <label description="Points" languagecode="1033" />
             *     </labels>
             *     <control id="new_points" classid="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}" datafieldname="new_points" disabled="true" />
             *   </cell>
             * </row>
             */

            foreach (var form in GetFormsWithAttribute(service, att))
            {
                Trace("Updating Form " + form.Name);
                var xml = form.FormXml;
                var dataFieldStart = "datafieldname=\"" + att.LogicalName + "\"";
                var index = xml.IndexOf(dataFieldStart, StringComparison.OrdinalIgnoreCase);
                while (index >= 0)
                {
                    index = xml.LastIndexOf("<cell ", index, StringComparison.OrdinalIgnoreCase);
                    var cellEnd = xml.IndexOf("</cell>", index, StringComparison.OrdinalIgnoreCase) + "</cell>".Length;
                    xml = xml.Remove(index, cellEnd - index);

                    index = xml.IndexOf(dataFieldStart, index, StringComparison.OrdinalIgnoreCase);
                }
                form.FormXml = xml;
                service.Update(form);
            }
        }
        public void Run(AttributeMetadata att, string newAttributeSchemaName, Steps stepsToPerform, Action actions, AttributeMetadata newAttributeType = null)
        {
            var state = GetApplicationMigrationState(Service, att, newAttributeSchemaName, actions);
            AssertValidStepsForState(att.SchemaName, newAttributeSchemaName, stepsToPerform, state, actions);
            var oldAtt = state.Old;
            var tmpAtt = state.Temp;
            var newAtt = state.New;

            switch (actions)
            {
                case Action.RemoveTemp:
                    RemoveTemp(stepsToPerform, tmpAtt);
                    break;

                case Action.Rename:
                case Action.Rename | Action.ChangeType:
                    CreateNew(newAttributeSchemaName, stepsToPerform, oldAtt, ref newAtt, newAttributeType); // Create or Retrieve the New Attribute
                    MigrateToNew(stepsToPerform, oldAtt, newAtt, actions);
                    RemoveExisting(stepsToPerform, oldAtt);
                    break;

                case Action.ChangeCase:
                case Action.ChangeCase | Action.ChangeType:
                case Action.ChangeType:
                    CreateTemp(stepsToPerform, oldAtt, ref tmpAtt, newAttributeType); // Either Create or Retrieve the Temp
                    MigrateToTemp(stepsToPerform, oldAtt, tmpAtt, actions);
                    RemoveExisting(stepsToPerform, oldAtt);
                    CreateNew(newAttributeSchemaName, stepsToPerform, tmpAtt, ref newAtt, newAttributeType);
                    MigrateToNew(stepsToPerform, tmpAtt, newAtt, actions);
                    RemoveTemp(stepsToPerform, tmpAtt);
                    break;
            }
        }
Example #7
0
 public static string GetNameForAttribute(AttributeMetadata attributeMetadata)
 {
     if (!_attributeNames.ContainsKey(attributeMetadata.LogicalName))
     {
         return null;
     }
     return _attributeNames[attributeMetadata.LogicalName];
 }
 private object CopyValueInternal(AttributeMetadata oldAttribute, IntegerAttributeMetadata newAttribute, object value)
 {
     int output;
     if (int.TryParse(value.ToString(), out output))
     {
         return output;
     }
     Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Integer");
     return null;
 }
 private static UpdateFormulaResponse UpdateForumlaDefinition(dynamic att, AttributeMetadata from, AttributeMetadata to)
 {
     var response = new UpdateFormulaResponse
     {
         CurrentForumla = att.FormulaDefinition,
         NewFormula = UpdateFormula(att.FormulaDefinition, from.LogicalName, to.LogicalName)
     };
     att.FormulaDefinition = response.NewFormula;
     return response;
 }
 /// <summary>
 /// constructor for the wrapper
 /// </summary>
 /// <param name="response">accepts an object that derives from the OrganizationResponse class</param>
 public RetrieveAttributeResponseWrapper(OrganizationResponse response)
 {
     try
     {
         _metadata = ((RetrieveAttributeResponseWrapper)response).AttributeMetadata;
     }
     catch
     {
         _metadata = ((RetrieveAttributeResponse)response).AttributeMetadata;
     }
 }
        /// <summary>
        /// 条件指定用のコンボボックスを設定
        /// </summary>
        /// <param name="attributes"></param>
        /// <returns></returns>
        public void SetAttributeCmb(AttributeMetadata[] attributes, ComboBox cmb)
        {
            List<CmbBean> attributeList = new List<CmbBean>();

            foreach (AttributeMetadata attr in attributes)
            {
                CmbBean bean = new CmbBean(attr.LogicalName, attr.DisplayName);
                attributeList.Add(bean);
            }
            attributeList.Sort((a, b) => a.DisplayName.CompareTo(b.DisplayName));
            SetListToCmb(attributeList, cmb);
        }
 bool ICodeWriterFilterService.GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     if (!string.IsNullOrEmpty(attributeMetadata.AttributeOf))
     {
         return false;
     }
     if ((!attributeMetadata.IsValidForCreate.GetValueOrDefault() && !attributeMetadata.IsValidForRead.GetValueOrDefault()) && !attributeMetadata.IsValidForUpdate.GetValueOrDefault())
     {
         return false;
     }
     return true;
 }
 private void PopulateControls(TreeNode node, AttributeMetadata[] attributes)
 {
     cmbAttribute.Items.Clear();
     if (attributes != null)
     {
         foreach (var attribute in attributes)
         {
             AttributeItem.AddAttributeToComboBox(cmbAttribute, attribute, false);
         }
     }
     var aggregate = FetchXmlBuilder.IsFetchAggregate(node);
     textAlias.Enabled = aggregate;
 }
        private void UpdateViews(IOrganizationService service, AttributeMetadata att)
        {
            foreach (var query in GetViewsWithAttribute(service, att))
            {
                Trace("Updating View " + query.Name);
                query.FetchXml = RemoveFieldFromFetchXml(query.FetchXml, att.LogicalName);

                if (query.LayoutXml != null)
                {
                    query.LayoutXml = RemoveFieldFromFetchXml(query.LayoutXml, att.LogicalName);
                }
                service.Update(query);
            }
        }
 public attributeControl(TreeNode Node, AttributeMetadata[] attributes, FetchXmlBuilder fetchXmlBuilder)
     : this()
 {
     collec = (Dictionary<string, string>)Node.Tag;
     if (collec == null)
     {
         collec = new Dictionary<string, string>();
     }
     node = Node;
     PopulateControls(Node, attributes);
     ControlUtils.FillControls(collec, this.Controls);
     controlsCheckSum = ControlUtils.ControlsChecksum(this.Controls);
     Saved += fetchXmlBuilder.CtrlSaved;
 }
        public void TestEnsureEmailGovdeliveryFieldNoField()
        {
            var service = new Mock<IOrganizationService>();
            service.Setup(dyn => dyn.Execute(It.IsAny<CreateAttributeRequest>()));

            var client = new Mock<DynamicsClient>("http://blah.test.com", "someone", "password");
            client.Setup(obj => obj.getService()).Returns(service.Object);

               var attributes = new AttributeMetadata[]{};
            client.Setup(obj => obj.retrieveMetadataAttributes(It.IsAny<string>())).Returns(attributes);

            client.Object.EnsureEmailGovdeliveryField();
            client.Verify(obj => obj.retrieveMetadataAttributes(It.IsAny<string>()));
            service.Verify(dyn => dyn.Execute(It.IsAny<CreateAttributeRequest>()));
        }
 public string GetNameForAttribute(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     List<string> specifiedNames;
     string attributeName;
     if (EntityAttributeSpecifiedNames.TryGetValue(entityMetadata.LogicalName.ToLower(), out specifiedNames) &&
         specifiedNames.Any(s => string.Equals(s, attributeMetadata.LogicalName, StringComparison.OrdinalIgnoreCase)))
     {
         attributeName = specifiedNames.First(s => string.Equals(s, attributeMetadata.LogicalName, StringComparison.OrdinalIgnoreCase));
     }
     else
     {
         attributeName = DefaultService.GetNameForAttribute(entityMetadata, attributeMetadata, services);
     }
     return attributeName;
 }
        private void UpdateCharts(IOrganizationService service, AttributeMetadata att)
        {
            foreach (var chart in GetSystemChartsWithAttribute(service, att))
            {
                Trace("Updating Chart " + chart.Name);
                chart.DataDescription = RemoveFieldFromFetchXml(chart.DataDescription, att.LogicalName);
                service.Update(chart);
            }

            foreach (var chart in GetUserChartsWithAttribute(service, att))
            {
                Trace("Updating Chart " + chart.Name);
                chart.DataDescription = RemoveFieldFromFetchXml(chart.DataDescription, att.LogicalName);
                service.Update(chart);
            }
        }
Example #19
0
 string INamingService.GetNameForAttribute(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     if (_knowNames.ContainsKey(entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value))
     {
         return _knowNames[entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value];
     }
     var name = StaticNamingService.GetNameForAttribute(attributeMetadata) ?? attributeMetadata.SchemaName;
     name = CreateValidName(name);
     var service = (INamingService) services.GetService(typeof (INamingService));
     if (_reservedAttributeNames.Contains(name) || (name == service.GetNameForEntity(entityMetadata, services)))
     {
         name = name + "1";
     }
     _knowNames.Add(entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value, name);
     return name;
 }
Example #20
0
        public orderControl(TreeNode Node, AttributeMetadata[] attributes, FetchXmlBuilder fetchXmlBuilder)
            : this()
        {
            form = fetchXmlBuilder;
            friendly = fetchXmlBuilder.currentSettings.useFriendlyNames;
            collec = (Dictionary<string, string>)Node.Tag;
            if (collec == null)
            {
                collec = new Dictionary<string, string>();
            }

            PopulateControls(Node, attributes);
            ControlUtils.FillControls(collec, this.Controls);
            controlsCheckSum = ControlUtils.ControlsChecksum(this.Controls);
            Saved += fetchXmlBuilder.CtrlSaved;
        }
 private object CopyValueInternal(AttributeMetadata oldAttribute, BooleanAttributeMetadata newAttribute, object value)
 {
     bool output;
     if (bool.TryParse(value.ToString(), out output))
     {
         return output;
     }
     try
     {
         return Convert.ToBoolean(value);
     }
     catch
     {
         // Failed to convert.  Give Up
     }
     Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double");
     return null;
 }
 private void PopulateControls(TreeNode node, AttributeMetadata[] attributes)
 {
     cmbAttribute.Items.Clear();
     if (attributes != null)
     {
         foreach (var attribute in attributes)
         {
             AttributeItem.AddAttributeToComboBox(cmbAttribute, attribute, false);
         }
     }
     var aggregate = FetchXmlBuilder.IsFetchAggregate(node);
     cmbAggregate.Enabled = aggregate;
     chkGroupBy.Enabled = aggregate;
     if (!aggregate)
     {
         cmbAggregate.SelectedIndex = -1;
         chkGroupBy.Checked = false;
     }
 }
        private void UpdateRelationships(IOrganizationService service, AttributeMetadata att)
        {
            var noneFound = true;
            Trace("Looking up Relationships");
            foreach (var relationship in Metadata.OneToManyRelationships.Where(r => r.ReferencedAttribute == att.LogicalName || r.ReferencingAttribute == att.LogicalName))
            {
                Trace("Deleting One to Many Relationship: " + relationship.SchemaName);
                service.Execute(new DeleteRelationshipRequest
                {
                    Name = relationship.SchemaName
                });
                noneFound = false;
            }
            foreach (var relationship in Metadata.ManyToManyRelationships.Where(r => r.Entity1IntersectAttribute == att.LogicalName || r.Entity2IntersectAttribute == att.LogicalName))
            {
                Trace("Deleting Many to Many Relationship: " + relationship.SchemaName);
                service.Execute(new DeleteRelationshipRequest
                {
                    Name = relationship.SchemaName
                });
                noneFound = false;
            }
            // Think this is the actual entity itself.  
            //foreach (var relationship in Metadata.ManyToOneRelationships.Where(r => r.ReferencedAttribute == att.LogicalName || r.ReferencingAttribute == att.LogicalName))
            //{
            //    Trace("Deleting Many to One Relationship: " + relationship.SchemaName);
            //    service.Execute(new DeleteRelationshipRequest
            //    {
            //        Name = relationship.SchemaName
            //    });
            //    noneFound = false;
            //}

            if (noneFound)
            {
                Trace("No Relationships Found.");
            }
        }
        /// <summary>
        /// DataGridViewのヘッダを設定します。
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="dataGrid"></param>
        public void SetDataGridColumns(AttributeMetadata[] attributes, DataGridView dataGrid)
        {
            foreach (AttributeMetadata attr in attributes)
            {
                // 条件が微妙だが、不要カラムの非表示
                string header = attr.LogicalName;
                if (attr.DisplayName.UserLocalizedLabel == null)
                {
                    continue;
                }
                else
                {
                    header = attr.DisplayName.UserLocalizedLabel.Label;
                }

                DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
                textColumn.DataPropertyName = attr.LogicalName;
                textColumn.Name = attr.LogicalName;
                textColumn.HeaderText = header;

                dataGrid.Columns.Add(textColumn);
            }
        }
 public static void AddAttributeToComboBox(ComboBox cmb, AttributeMetadata meta, bool allowvirtual, bool friendly)
 {
     var add = false;
     if (!friendly)
     {
         add = true;
     }
     else
     {
         add = meta.DisplayName != null && meta.DisplayName.LocalizedLabels != null && meta.DisplayName.LocalizedLabels.Count > 0;
         if (meta.AttributeType == AttributeTypeCode.Money && meta.LogicalName.EndsWith("_base"))
         {
             add = false;
         }
     }
     if (!allowvirtual && meta.AttributeType == AttributeTypeCode.Virtual)
     {
         add = false;
     }
     if (add)
     {
         cmb.Items.Add(new AttributeItem(meta));
     }
 }
        public static MappingField GetMappingField(AttributeMetadata attribute, MappingEntity entity,
                                                   MappingField result, bool isTitleCaseLogicalName)
        {
            result ??= new MappingField();

            result.Entity           = entity;
            result.MetadataId       = attribute.MetadataId;
            result.LogicalName      = attribute.LogicalName ?? result.LogicalName;
            result.AttributeOf      = attribute.AttributeOf ?? result.AttributeOf;
            result.IsValidForCreate = attribute.IsValidForCreate ?? result.IsValidForCreate;
            result.IsValidForRead   = attribute.IsValidForRead ?? result.IsValidForRead;
            result.IsValidForUpdate = attribute.IsValidForUpdate ?? result.IsValidForUpdate;

            if (attribute.AttributeType != null)
            {
                result.FieldType       = attribute.AttributeType.Value;
                result.IsActivityParty = attribute.AttributeType == AttributeTypeCode.PartyList;
                result.IsStateCode     = attribute.AttributeType == AttributeTypeCode.State;
            }

            result.DeprecatedVersion = attribute.DeprecatedVersion ?? result.DeprecatedVersion;

            if (attribute.DeprecatedVersion != null)
            {
                result.IsDeprecated = !string.IsNullOrWhiteSpace(attribute.DeprecatedVersion);
            }

            if (attribute is EnumAttributeMetadata || attribute is BooleanAttributeMetadata)
            {
                result.EnumData =
                    MappingEnum.GetMappingEnum(attribute, result.EnumData, isTitleCaseLogicalName);
            }

            var lookup = attribute as LookupAttributeMetadata;

            if (lookup?.Targets != null && lookup.Targets.Length == 1)
            {
                result.LookupSingleType = lookup.Targets[0];
            }

            ParseDateTime(attribute, result);
            ParseMinMaxValues(attribute, result);

            result.IsPrimaryKey = attribute.IsPrimaryId ?? result.IsPrimaryKey;

            if (attribute.SchemaName != null)
            {
                result.SchemaName = attribute.SchemaName ?? result.SchemaName;

                if (attribute.LogicalName != null)
                {
                    result.DisplayName = Naming.GetProperVariableName(attribute, isTitleCaseLogicalName);
                }
                result.PrivatePropertyName = Naming.GetEntityPropertyPrivateName(attribute.SchemaName);
            }

            result.HybridName = Naming.GetProperHybridFieldName(result.DisplayName,
                                                                new Yagasoft.CrmCodeGenerator.Models.Attributes.CrmPropertyAttribute
            {
                IsEntityReferenceHelper = result.Attribute.IsEntityReferenceHelper,
                IsImage      = result.Attribute.IsImage,
                IsLookup     = result.Attribute.IsLookup,
                IsMultiTyped = result.Attribute.IsMultiTyped,
                LogicalName  = result.Attribute.LogicalName,
                SchemaName   = result.Attribute.SchemaName,
            });

            if (attribute.Description?.UserLocalizedLabel != null)
            {
                result.Description = attribute.Description.UserLocalizedLabel.Label;
            }

            if (attribute.DisplayName != null)
            {
                if (attribute.DisplayName.LocalizedLabels != null)
                {
                    result.LocalizedLabels = attribute.DisplayName
                                             .LocalizedLabels.Select(label => new LocalizedLabelSerialisable
                    {
                        LanguageCode = label.LanguageCode,
                        Label        = label.Label
                    }).ToArray();
                }

                if (attribute.DisplayName.UserLocalizedLabel != null)
                {
                    result.Label = attribute.DisplayName.UserLocalizedLabel.Label;
                }
            }

            if (attribute.RequiredLevel != null)
            {
                result.IsRequired = attribute.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired;
            }

            if (attribute.AttributeType != null)
            {
                result.Attribute =
                    new CrmPropertyAttribute
                {
                    LogicalName = attribute.LogicalName,
                    IsLookup    = attribute.AttributeType == AttributeTypeCode.Lookup ||
                                  attribute.AttributeType == AttributeTypeCode.Owner ||
                                  attribute.AttributeType == AttributeTypeCode.Customer
                };
            }

            result.TargetTypeForCrmSvcUtil = GetTargetType(result);
            result.FieldTypeString         = result.TargetTypeForCrmSvcUtil;

            return(result);
        }
        public static string RetrieveAttributeDisplayName(EntityMetadata emd, string attributeName, string fetchXml, IOrganizationService oService)
        {
            string rAttributeName = attributeName;
            string rEntityName    = string.Empty;

            if (attributeName.Contains("."))
            {
                string[] data = attributeName.ToLower().Split('.');

                if (!string.IsNullOrEmpty(fetchXml))
                {
                    XmlDocument fetchDoc = new XmlDocument();
                    fetchDoc.LoadXml(fetchXml);

                    XmlNode aliasNode = fetchDoc.SelectSingleNode("//link-entity[@alias='" + data[0] + "']");
                    if (aliasNode != null)
                    {
                        data[0] = string.Format("{0}{1}{2}{3}",
                                                emd.LogicalName,
                                                aliasNode.Attributes["to"].Value,
                                                aliasNode.Attributes["name"].Value,
                                                aliasNode.Attributes["from"].Value);
                    }
                }

                foreach (OneToManyRelationshipMetadata otmmd in emd.ManyToOneRelationships)
                {
                    string referencing     = otmmd.ReferencingEntity;
                    string attrreferencing = otmmd.ReferencingAttribute;
                    string referenced      = otmmd.ReferencedEntity;
                    string attrreferenced  = otmmd.ReferencedAttribute;

                    string name = referencing + attrreferencing + referenced + attrreferenced;

                    if (name == data[0])
                    {
                        rAttributeName = data[1];
                        rEntityName    = referenced;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(rEntityName) && !string.IsNullOrEmpty(rAttributeName))
                {
                    EntityMetadata relatedEmd = RetrieveEntity(rEntityName, oService);

                    AttributeMetadata relatedamd = (from attr in relatedEmd.Attributes
                                                    where attr.LogicalName == rAttributeName
                                                    select attr).First <AttributeMetadata>();

                    return(relatedamd.DisplayName.UserLocalizedLabel.Label);
                }

                return(string.Empty);
            }
            else
            {
                AttributeMetadata attribute = (from attr in emd.Attributes
                                               where attr.LogicalName == attributeName
                                               select attr).First <AttributeMetadata>();

                return(attribute.DisplayName.UserLocalizedLabel.Label);
            }
        }
Example #28
0
        private static object GetConvertedValue(CrmTestingContext context, AttributeMetadata metadata, string value, ConvertedObjectType objectType)
        {
            switch (metadata.AttributeType)
            {
            case AttributeTypeCode.Boolean:
                return(GetTwoOptionValue(metadata, value, context));

            case AttributeTypeCode.Double: return(double.Parse(value));

            case AttributeTypeCode.Decimal: return(decimal.Parse(value));

            case AttributeTypeCode.Integer: return(int.Parse(value));

            case AttributeTypeCode.DateTime:
                return(ParseDateTime(metadata, value));

            case AttributeTypeCode.Memo:
            case AttributeTypeCode.String: return(value);

            case AttributeTypeCode.Money:
                if (objectType == ConvertedObjectType.Primitive)
                {
                    return(decimal.Parse(value));
                }
                else
                {
                    return(new Money(decimal.Parse(value)));
                }

            case AttributeTypeCode.Picklist:
            case AttributeTypeCode.State:
            case AttributeTypeCode.Status:
                var optionSet = GetOptionSetValue(metadata, value, context);
                if (objectType == ConvertedObjectType.Primitive)
                {
                    return(optionSet.Value);
                }
                else
                {
                    return(optionSet);
                }

            case AttributeTypeCode.Customer:
            case AttributeTypeCode.Lookup:
            case AttributeTypeCode.Owner:
                var lookup = GetLookupValue(context, metadata, value);
                if (objectType == ConvertedObjectType.Primitive)
                {
                    return(lookup.Id);
                }
                else
                {
                    return(lookup);
                }

            case AttributeTypeCode.Virtual:
                return(ParseVirtualType(context, metadata, value));

            default: throw new NotImplementedException(string.Format("Type {0} not implemented", metadata.AttributeType));
            }
        }
Example #29
0
 public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     return(DefaultService.GenerateAttribute(attributeMetadata, services));
 }
 public AttributeItem(AttributeMetadata Attribute)
 {
     meta = Attribute;
 }
        /// <summary>
        /// Adds attribute type specific metadata information
        /// </summary>
        /// <param name="x">Row number</param>
        /// <param name="y">Cell number</param>
        /// <param name="amd">Attribute metadata</param>
        /// <param name="sheet">Worksheet where to write</param>
        private void AddAdditionalData(int x, int y, AttributeMetadata amd, ExcelWorksheet sheet)
        {
            if (amd.AttributeType != null)
            {
                switch (amd.AttributeType.Value)
                {
                case AttributeTypeCode.BigInt:
                {
                    var bamd = (BigIntAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Minimum value: {0}\r\nMaximum value: {1}",
                        bamd.MinValue.HasValue ? bamd.MinValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        bamd.MaxValue.HasValue ? bamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.Boolean:
                {
                    var bamd = (BooleanAttributeMetadata)amd;

                    if (bamd.OptionSet.TrueOption == null)
                    {
                        return;
                    }

                    var bamdOptionSetTrue  = bamd.OptionSet.TrueOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);
                    var bamdOptionSetFalse = bamd.OptionSet.FalseOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);

                    sheet.Cells[x, y].Value = string.Format(
                        "True: {0}\r\nFalse: {1}\r\nDefault Value: {2}",
                        bamdOptionSetTrue != null ? bamdOptionSetTrue.Label : "",
                        bamdOptionSetFalse != null ? bamdOptionSetFalse.Label : "",
                        bamd.DefaultValue.HasValue ? bamd.DefaultValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.DateTime:
                {
                    var damd = (DateTimeAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Format: {0}",
                        damd.Format.HasValue ? damd.Format.Value.ToString() : "N/A");
                }
                break;

                case AttributeTypeCode.Decimal:
                {
                    var damd = (DecimalAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Minimum value: {0}\r\nMaximum value: {1}\r\nPrecision: {2}",
                        damd.MinValue.HasValue ? damd.MinValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        damd.MaxValue.HasValue ? damd.MaxValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        damd.Precision.HasValue ? damd.Precision.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.Double:
                {
                    var damd = (DoubleAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Minimum value: {0}\r\nMaximum value: {1}\r\nPrecision: {2}",
                        damd.MinValue.HasValue ? damd.MinValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        damd.MaxValue.HasValue ? damd.MaxValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        damd.Precision.HasValue ? damd.Precision.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.EntityName:
                {
                    // Do nothing
                }
                break;

                case AttributeTypeCode.Integer:
                {
                    var iamd = (IntegerAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Minimum value: {0}\r\nMaximum value: {1}",
                        iamd.MinValue.HasValue ? iamd.MinValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        iamd.MaxValue.HasValue ? iamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.Customer:
                case AttributeTypeCode.Owner:
                case AttributeTypeCode.Lookup:
                {
                    var lamd = (LookupAttributeMetadata)amd;

                    var format = lamd.Targets.Aggregate("Targets:", (current, entity) => current + "\r\n" + entity);

                    sheet.Cells[x, y].Value = format;
                }
                break;

                case AttributeTypeCode.Memo:
                {
                    var mamd = (MemoAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Format: {0}\r\nMax length: {1}",
                        mamd.Format.HasValue ? mamd.Format.Value.ToString() : "N/A",
                        mamd.MaxLength.HasValue ? mamd.MaxLength.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.Money:
                {
                    var mamd = (MoneyAttributeMetadata)amd;

                    sheet.Cells[x, y].Value = string.Format(
                        "Minimum value: {0}\r\nMaximum value: {1}\r\nPrecision: {2}",
                        mamd.MinValue.HasValue ? mamd.MinValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        mamd.MaxValue.HasValue ? mamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A",
                        mamd.Precision.HasValue ? mamd.Precision.Value.ToString(CultureInfo.InvariantCulture) : "N/A");
                }
                break;

                case AttributeTypeCode.PartyList:
                {
                    // Do nothing
                }
                break;

                case AttributeTypeCode.Virtual:
                    if (amd is MultiSelectPicklistAttributeMetadata mspamd)
                    {
                        int?defaultValue      = mspamd.DefaultFormValue;
                        OptionSetMetadata osm = mspamd.OptionSet;

                        string format = "Options:";

                        foreach (var omd in osm.Options)
                        {
                            var omdLocLabel = omd.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);
                            if (omdLocLabel != null)
                            {
                                var label = omdLocLabel.Label;

                                format += $"\r\n{omd.Value}: {label}";
                            }
                        }

                        format +=
                            $"\r\nDefault: {(defaultValue.HasValue && defaultValue != -1 ? defaultValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A")}";

                        sheet.Cells[x, y].Value = format;
                    }

                    break;

                case AttributeTypeCode.Picklist:
                {
                    PicklistAttributeMetadata pamd = (PicklistAttributeMetadata)amd;
                    int?defaultValue      = pamd.DefaultFormValue;
                    OptionSetMetadata osm = pamd.OptionSet;

                    string format = "Options:";

                    foreach (var omd in osm.Options)
                    {
                        var omdLocLabel = omd.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);
                        if (omdLocLabel != null)
                        {
                            var label = omdLocLabel.Label;

                            format += string.Format("\r\n{0}: {1}",
                                                    omd.Value,
                                                    label);
                        }
                    }

                    format += string.Format("\r\nDefault: {0}", defaultValue.HasValue && defaultValue != -1 ? defaultValue.Value.ToString(CultureInfo.InvariantCulture) : "N/A");

                    sheet.Cells[x, y].Value = format;
                }
                break;

                case AttributeTypeCode.State:
                {
                    var samd = (StateAttributeMetadata)amd;

                    string format = "States:";

                    foreach (var omd in samd.OptionSet.Options)
                    {
                        var omdLocLabel = omd.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);
                        format += string.Format("\r\n{0}: {1}",
                                                omd.Value,
                                                omdLocLabel != null ? omdLocLabel.Label : "");
                    }

                    sheet.Cells[x, y].Value = format;
                }
                break;

                case AttributeTypeCode.Status:
                {
                    var samd = (StatusAttributeMetadata)amd;

                    string format = "States:";

                    foreach (OptionMetadata omd in samd.OptionSet.Options)
                    {
                        var omdLocLabel = omd.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);
                        format += string.Format("\r\n{0}: {1}",
                                                omd.Value,
                                                omdLocLabel != null ? omdLocLabel.Label : "");
                    }

                    sheet.Cells[x, y].Value = format;
                }
                break;

                case AttributeTypeCode.String:
                {
                    var samd = amd as StringAttributeMetadata;
                    if (samd != null)
                    {
                        sheet.Cells[x, y].Value = string.Format(
                            "Format: {0}\r\nMax length: {1}",
                            samd.Format.HasValue ? samd.Format.Value.ToString() : "N/A",
                            samd.MaxLength.HasValue
                                        ? samd.MaxLength.Value.ToString(CultureInfo.InvariantCulture)
                                        : "N/A");
                    }

                    var mamd = amd as MemoAttributeMetadata;
                    if (mamd != null)
                    {
                        sheet.Cells[x, y].Value = string.Format(
                            "Format: {0}\r\nMax length: {1}",
                            mamd.Format.HasValue ? mamd.Format.Value.ToString() : "N/A",
                            mamd.MaxLength.HasValue
                                        ? mamd.MaxLength.Value.ToString(CultureInfo.InvariantCulture)
                                        : "N/A");
                    }
                }
                break;

                case AttributeTypeCode.Uniqueidentifier:
                {
                    // Do Nothing
                }
                break;
                }
            }
        }
 public AttributeMetadataInfo(AttributeMetadata amd)
 {
     this.amd = amd;
 }
Example #33
0
 public bool GenerateAttribute(AttributeMetadata metadata, IServiceProvider services)
 {
     return(EnableFileDataType && IsFileDataTypeAttribute(metadata) ||
            DefaultService.GenerateAttribute(metadata, services));
 }
Example #34
0
        private IEnumerable <string> checkDifferenceAttributeMetadata(AttributeMetadata originalAttributeMetadata, AttributeMetadata readAttributeMetadata)
        {
            List <string> attributesToUpdate = checkGlobalDifferenceAttributeMetadata(originalAttributeMetadata, readAttributeMetadata);

            switch (originalAttributeMetadata.AttributeType)
            {
            case AttributeTypeCode.Integer:
                IntegerAttributeMetadata intattrMetadata = originalAttributeMetadata as IntegerAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceIntegerAttribute(intattrMetadata, readAttributeMetadata as IntegerAttributeMetadata));
                originalAttributeMetadata = intattrMetadata;
                break;

            case AttributeTypeCode.DateTime:
                DateTimeAttributeMetadata dateattrMetadata = originalAttributeMetadata as DateTimeAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDateTimeAttribute(dateattrMetadata, readAttributeMetadata as DateTimeAttributeMetadata));
                originalAttributeMetadata = dateattrMetadata;
                break;

            case AttributeTypeCode.String:
                StringAttributeMetadata strattrMetadata = originalAttributeMetadata as StringAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceStringAttribute(strattrMetadata, readAttributeMetadata as StringAttributeMetadata));
                originalAttributeMetadata = strattrMetadata;
                break;

            case AttributeTypeCode.Picklist:
                PicklistAttributeMetadata pklattrMetadata = originalAttributeMetadata as PicklistAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferencePicklistAttribute(pklattrMetadata, readAttributeMetadata as PicklistAttributeMetadata));
                originalAttributeMetadata = pklattrMetadata;
                break;

            case AttributeTypeCode.Memo:
                MemoAttributeMetadata memattrMetadata = originalAttributeMetadata as MemoAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceMemoAttribute(memattrMetadata, readAttributeMetadata as MemoAttributeMetadata));
                originalAttributeMetadata = memattrMetadata;
                break;

            case AttributeTypeCode.Double:
                DoubleAttributeMetadata dblattrMetadata = originalAttributeMetadata as DoubleAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDoubleAttribute(dblattrMetadata, readAttributeMetadata as DoubleAttributeMetadata));
                originalAttributeMetadata = dblattrMetadata;
                break;

            case AttributeTypeCode.Decimal:
                DecimalAttributeMetadata dcmattrMetadata = originalAttributeMetadata as DecimalAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDecimalAttribute(dcmattrMetadata, readAttributeMetadata as DecimalAttributeMetadata));
                originalAttributeMetadata = dcmattrMetadata;
                break;

            case AttributeTypeCode.Boolean:
                BooleanAttributeMetadata blnattrMetadata = originalAttributeMetadata as BooleanAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceBooleanAttribute(blnattrMetadata, readAttributeMetadata as BooleanAttributeMetadata));
                originalAttributeMetadata = blnattrMetadata;
                break;

            case AttributeTypeCode.Money:
                MoneyAttributeMetadata mnyattrMetadata = originalAttributeMetadata as MoneyAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceMoneyAttribute(mnyattrMetadata, readAttributeMetadata as MoneyAttributeMetadata));
                originalAttributeMetadata = mnyattrMetadata;
                break;
            }
            return(attributesToUpdate);
        }
 public static void SetSealedPropertyValue(this AttributeMetadata attributeMetadata, string sPropertyName, object value)
 {
     attributeMetadata.GetType().GetProperty(sPropertyName).SetValue(attributeMetadata, value, null);
 }
 protected virtual AttributeInfo CreateVirtual(AttributeMetadata attributeMetadata)
 {
     //var attMeta = (VirtualAttributeInfo)attributeMetadata;
     var attInfo = new VirtualAttributeInfo();
     return attInfo;
 }
 protected virtual AttributeInfo CreateStatus(AttributeMetadata attributeMetadata)
 {
     var attMeta = (StatusAttributeMetadata)attributeMetadata;
     var attInfo = new StatusAttributeInfo(attMeta.OptionSet);
     attInfo.DefaultValue = attMeta.DefaultFormValue;
     return attInfo;
 }
Example #38
0
 public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     return(false);
 }
 public AttributeMetadataDto(AttributeMetadata attribute)
 {
     this.attribute = attribute;
 }
        /// <summary>
        /// Add an attribute metadata
        /// </summary>
        /// <param name="amd">Attribute metadata</param>
        /// <param name="sheet">Worksheet where to write</param>
        public void AddAttribute(AttributeMetadata amd, ExcelWorksheet sheet)
        {
            var y = 1;

            if (!attributesHeaderAdded)
            {
                InsertAttributeHeader(sheet, lineNumber, y);
                attributesHeaderAdded = true;
            }
            lineNumber++;

            if (settings.GenerateOnlyOneTable)
            {
                sheet.Cells[lineNumber, y].Value = emdCache.First(e => e.LogicalName == amd.EntityLogicalName)
                                                   .DisplayName?.UserLocalizedLabel?.Label ?? "N/A";
                y++;

                sheet.Cells[lineNumber, y].Value = amd.EntityLogicalName;
                y++;
            }

            sheet.Cells[lineNumber, y].Value = amd.LogicalName;
            y++;

            sheet.Cells[lineNumber, y].Value = amd.SchemaName;
            y++;

            var amdDisplayName = amd.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);

            sheet.Cells[lineNumber, y].Value = amd.DisplayName.LocalizedLabels.Count == 0 ? "N/A" : amdDisplayName != null ? amdDisplayName.Label : "";
            y++;

            if (amd.AttributeType != null)
            {
                sheet.Cells[lineNumber, y].Value = amd.AttributeType.Value.ToString();
            }
            if (amd.AttributeType.Value == AttributeTypeCode.Virtual && amd is MultiSelectPicklistAttributeMetadata)
            {
                sheet.Cells[lineNumber, y].Value = "MultiSelect OptionSet";
            }
            y++;

            var amdDescription = amd.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode);

            sheet.Cells[lineNumber, y].Value = amd.Description.LocalizedLabels.Count == 0 ? "N/A" : amdDescription != null ? amdDescription.Label : "";
            y++;

            sheet.Cells[lineNumber, y].Value = (amd.IsCustomAttribute != null && amd.IsCustomAttribute.Value).ToString(CultureInfo.InvariantCulture);
            y++;

            sheet.Cells[lineNumber, y].Value = (amd.SourceType ?? 0) == 0 ? "Simple" : (amd.SourceType ?? 0) == 1 ? "Calculated" : "Rollup";
            y++;

            if (settings.AddRequiredLevelInformation)
            {
                sheet.Cells[lineNumber, y].Value = amd.RequiredLevel.Value.ToString();
                y++;
            }

            if (settings.AddValidForAdvancedFind)
            {
                sheet.Cells[lineNumber, y].Value = amd.IsValidForAdvancedFind.Value.ToString(CultureInfo.InvariantCulture);
                y++;
            }

            if (settings.AddAuditInformation)
            {
                sheet.Cells[lineNumber, y].Value = amd.IsAuditEnabled.Value.ToString(CultureInfo.InvariantCulture);
                y++;
            }

            if (settings.AddFieldSecureInformation)
            {
                sheet.Cells[lineNumber, y].Value = (amd.IsSecured != null && amd.IsSecured.Value).ToString(CultureInfo.InvariantCulture);
                y++;
            }

            if (settings.AddFormLocation)
            {
                var entity = settings.EntitiesToProceed.FirstOrDefault(e => e.Name == amd.EntityLogicalName);
                if (entity != null)
                {
                    foreach (var form in entity.FormsDefinitions.Where(fd => entity.Forms.Contains(fd.Id) || entity.Forms.Count == 0))
                    {
                        var formName    = form.GetAttributeValue <string>("name");
                        var xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(form["formxml"].ToString());

                        var controlNode = xmlDocument.SelectSingleNode("//control[@datafieldname='" + amd.LogicalName + "']");
                        if (controlNode != null)
                        {
                            XmlNodeList sectionNodes = controlNode.SelectNodes("ancestor::section");
                            XmlNodeList headerNodes  = controlNode.SelectNodes("ancestor::header");
                            XmlNodeList footerNodes  = controlNode.SelectNodes("ancestor::footer");

                            if (sectionNodes.Count > 0)
                            {
                                if (sectionNodes[0].SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']") != null)
                                {
                                    var sectionName = sectionNodes[0].SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']").Attributes["description"].Value;

                                    XmlNode tabNode = sectionNodes[0].SelectNodes("ancestor::tab")[0];
                                    if (tabNode != null && tabNode.SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']") != null)
                                    {
                                        var tabName = tabNode.SelectSingleNode("labels/label[@languagecode='" + settings.DisplayNamesLangugageCode + "']").Attributes["description"].Value;

                                        if (sheet.Cells[lineNumber, y].Value != null)
                                        {
                                            sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/{1}/{2}", formName, tabName, sectionName);
                                        }
                                        else
                                        {
                                            sheet.Cells[lineNumber, y].Value = string.Format("{0}/{1}/{2}", formName, tabName, sectionName);
                                        }
                                    }
                                }
                            }
                            else if (headerNodes.Count > 0)
                            {
                                if (sheet.Cells[lineNumber, y].Value != null)
                                {
                                    sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/Header", formName);
                                }
                                else
                                {
                                    sheet.Cells[lineNumber, y].Value = string.Format("{0}/Header", formName);
                                }
                            }
                            else if (footerNodes.Count > 0)
                            {
                                if (sheet.Cells[lineNumber, y].Value != null)
                                {
                                    sheet.Cells[lineNumber, y].Value = sheet.Cells[lineNumber, y].Value + "\r\n" + string.Format("{0}/Footer", formName);
                                }
                                else
                                {
                                    sheet.Cells[lineNumber, y].Value = string.Format("{0}/Footer", formName);
                                }
                            }
                        }
                    }
                }

                sheet.Column(y).PageBreak = true;

                y++;
            }

            sheet.Column(y).PageBreak = true;

            AddAdditionalData(lineNumber, y, amd, sheet);
        }
        private void UpdateWorkflows(IOrganizationService service, AttributeMetadata att)
        {
            Trace("Checking for Workflow Dependencies");
            var depends = ((RetrieveDependenciesForDeleteResponse)service.Execute(new RetrieveDependenciesForDeleteRequest
            {
                ComponentType = (int)ComponentType.Attribute,
                ObjectId = att.MetadataId.GetValueOrDefault()
            })).EntityCollection.ToEntityList <Dependency>().Where(d => d.DependentComponentTypeEnum == ComponentType.Workflow).ToList();

            if (!depends.Any())
            {
                Trace("No Workflow Dependencies Found");
                return;
            }

            foreach (var workflow in service.GetEntitiesById <Workflow>(depends.Select(d => d.DependentComponentObjectId.GetValueOrDefault())))
            {
                var workflowToUpdate = new Workflow {
                    Id = workflow.Id
                };
                Trace("Updating {0} - {1} ({2})", workflow.CategoryEnum.ToString(), workflow.Name, workflow.Id);
                workflowToUpdate.Xaml = RemoveParentXmlNodesWithTagValue(workflow.Xaml, "mxswa:ActivityReference AssemblyQualifiedName=\"Microsoft.Crm.Workflow.Activities.StepComposite,", "mcwb:Control", "DataFieldName", att.LogicalName, "mxswa:ActivityReference");
                var unsupportedXml = RemoveXmlNodesWithTagValue(workflow.Xaml, "mxswa:GetEntityProperty", "Attribute", att.LogicalName);
                if (workflowToUpdate.Xaml != unsupportedXml)
                {
                    throw new NotImplementedException("Attribute is used in a Business Rules Get Entity Property.  This is unsupported for manual deletion.  Delete the Business Rule " + workflow.Name + " manually to be able to delete the attribute.");
                }

                var activate = workflow.StateCode == WorkflowState.Activated;
                if (activate)
                {
                    service.Execute(new SetStateRequest
                    {
                        EntityMoniker = workflow.ToEntityReference(),
                        State         = new OptionSetValue((int)WorkflowState.Draft),
                        Status        = new OptionSetValue((int)Workflow_StatusCode.Draft)
                    });
                }
                try
                {
                    var triggers = service.GetEntities <ProcessTrigger>(ProcessTrigger.Fields.ProcessId,
                                                                        workflow.Id,
                                                                        ProcessTrigger.Fields.ControlName,
                                                                        att.LogicalName);

                    foreach (var trigger in triggers)
                    {
                        Trace("Deleting Trigger {0} for Workflow", trigger.Id);
                        service.Delete(ProcessTrigger.EntityLogicalName, trigger.Id);
                    }

                    if (workflow.TriggerOnUpdateAttributeList != null)
                    {
                        var newValue = RemoveValueFromCsvValues(workflow.TriggerOnUpdateAttributeList, att.LogicalName);
                        if (newValue != workflow.TriggerOnUpdateAttributeList)
                        {
                            Trace("Updating workflow {0} Trigger On Update Filter - \"{1}\" to \"{2}\"", workflow.Name, workflow.TriggerOnUpdateAttributeList, newValue);
                            workflowToUpdate.TriggerOnUpdateAttributeList = newValue;
                        }
                    }

                    service.Update(workflowToUpdate);
                }
                finally
                {
                    if (activate)
                    {
                        service.Execute(new SetStateRequest()
                        {
                            EntityMoniker = workflow.ToEntityReference(),
                            State         = new OptionSetValue((int)WorkflowState.Activated),
                            Status        = new OptionSetValue((int)Workflow_StatusCode.Activated)
                        });
                    }
                }
            }
        }
Example #42
0
        public static void SetMetadata(EntityMetadata metadata, Type earlyBoundEntity, EntityLogicalNameAttribute entityLogicalNameAttribute)
        {
            metadata.LogicalName = entityLogicalNameAttribute.LogicalName;

            FieldInfo entityTypeCode = earlyBoundEntity.GetField("EntityTypeCode", BindingFlags.Static | BindingFlags.Public);

            if (entityTypeCode != null)
            {
                metadata.SetFieldValue("_objectTypeCode", entityTypeCode.GetValue(null));
            }

            List <AttributeMetadata> attributeMetadatas = new List <AttributeMetadata>();
            List <ManyToManyRelationshipMetadata> manyToManyRelationshipMetadatas = new List <ManyToManyRelationshipMetadata>();
            List <OneToManyRelationshipMetadata>  oneToManyRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();
            List <OneToManyRelationshipMetadata>  manyToOneRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();

            var idProperty = earlyBoundEntity.GetProperty("Id");
            AttributeLogicalNameAttribute attributeLogicalNameAttribute;

            if (idProperty != null && (attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(idProperty)) != null)
            {
                metadata.SetFieldValue("_primaryIdAttribute", attributeLogicalNameAttribute.LogicalName);
            }

            var properties = earlyBoundEntity.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(x => x.Name != "Id" && Attribute.IsDefined(x, typeof(AttributeLogicalNameAttribute)) ||
                                    Attribute.IsDefined(x, typeof(RelationshipSchemaNameAttribute)));

            foreach (var property in properties)
            {
                RelationshipSchemaNameAttribute relationshipSchemaNameAttribute = GetCustomAttribute <RelationshipSchemaNameAttribute>(property);
                attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(property);

                if (relationshipSchemaNameAttribute == null)
                {
#if !FAKE_XRM_EASY
                    if (property.PropertyType == typeof(byte[]))
                    {
                        metadata.SetFieldValue("_primaryImageAttribute", attributeLogicalNameAttribute.LogicalName);
                    }
#endif
                    AttributeMetadata attributeMetadata;
                    if (attributeLogicalNameAttribute.LogicalName == "statecode")
                    {
                        attributeMetadata = new StateAttributeMetadata();
                    }
                    else if (attributeLogicalNameAttribute.LogicalName == "statuscode")
                    {
                        attributeMetadata = new StatusAttributeMetadata();
                    }
                    else if (attributeLogicalNameAttribute.LogicalName == metadata.PrimaryIdAttribute)
                    {
                        attributeMetadata = new AttributeMetadata();
                        attributeMetadata.SetSealedPropertyValue("AttributeType", AttributeTypeCode.Uniqueidentifier);
                    }
                    else
                    {
                        attributeMetadata = CreateAttributeMetadata(property.PropertyType);
                    }

                    attributeMetadata.SetFieldValue("_entityLogicalName", entityLogicalNameAttribute.LogicalName);
                    attributeMetadata.SetFieldValue("_logicalName", attributeLogicalNameAttribute.LogicalName);

                    attributeMetadatas.Add(attributeMetadata);
                }
                else
                {
                    if (property.PropertyType.Name == "IEnumerable`1")
                    {
                        PropertyInfo peerProperty = property.PropertyType.GetGenericArguments()[0].GetProperties()
                                                    .SingleOrDefault(x => x.PropertyType == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName);

                        if (peerProperty == null || peerProperty.PropertyType.Name == "IEnumerable`1") // N:N relationship
                        {
                            ManyToManyRelationshipMetadata relationshipMetadata = new ManyToManyRelationshipMetadata();
                            relationshipMetadata.SchemaName = relationshipSchemaNameAttribute.SchemaName;

                            manyToManyRelationshipMetadatas.Add(relationshipMetadata);
                        }
                        else // 1:N relationship
                        {
                            AddOneToManyRelationshipMetadata(earlyBoundEntity, property, property.PropertyType.GetGenericArguments()[0], peerProperty, oneToManyRelationshipMetadatas);
                        }
                    }
                    else //N:1 Property
                    {
                        AddOneToManyRelationshipMetadata(property.PropertyType, property.PropertyType.GetProperties()
                                                         .SingleOrDefault(x => x.PropertyType.GetGenericArguments().SingleOrDefault() == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName), earlyBoundEntity, property, manyToOneRelationshipMetadatas);
                    }
                }
            }
            if (attributeMetadatas.Any())
            {
                metadata.SetSealedPropertyValue("Attributes", attributeMetadatas.ToArray());
            }
            if (manyToManyRelationshipMetadatas.Any())
            {
                metadata.SetSealedPropertyValue("ManyToManyRelationships", manyToManyRelationshipMetadatas.ToArray());
            }
            if (manyToOneRelationshipMetadatas.Any())
            {
                metadata.SetSealedPropertyValue("ManyToOneRelationships", manyToOneRelationshipMetadatas.ToArray());
            }
            if (oneToManyRelationshipMetadatas.Any())
            {
                metadata.SetSealedPropertyValue("OneToManyRelationships", oneToManyRelationshipMetadatas.ToArray());
            }
        }
 private static string ExtractLabel(AttributeMetadata attributeMetadata, string logicalName)
 {
     return(attributeMetadata.DisplayName.UserLocalizedLabel == null ||
            string.IsNullOrEmpty(attributeMetadata.DisplayName.UserLocalizedLabel.Label) ?
            logicalName : attributeMetadata.DisplayName.UserLocalizedLabel.Label);
 }
        protected internal void AddEntity(Entity e)
        {
            //Automatically detect proxy types assembly if an early bound type was used.
            if (ProxyTypesAssembly == null &&
                e.GetType().IsSubclassOf(typeof(Entity)))
            {
                ProxyTypesAssembly = Assembly.GetAssembly(e.GetType());
            }

            ValidateEntity(e); //Entity must have a logical name and an Id

            //Add the entity collection
            if (!Data.ContainsKey(e.LogicalName))
            {
                Data.Add(e.LogicalName, new Dictionary <Guid, Entity>());
            }

            if (Data[e.LogicalName].ContainsKey(e.Id))
            {
                Data[e.LogicalName][e.Id] = e;
            }
            else
            {
                Data[e.LogicalName].Add(e.Id, e);
            }


            //Update metadata for that entity
            if (!AttributeMetadata.ContainsKey(e.LogicalName))
            {
                AttributeMetadata.Add(e.LogicalName, new Dictionary <string, string>());
            }

            //Update attribute metadata
            if (ProxyTypesAssembly != null)
            {
                //If the context is using a proxy types assembly then we can just guess the metadata from the generated attributes
                var type = FindReflectedType(e.LogicalName);
                if (type != null)
                {
                    var props = type.GetProperties();
                    foreach (var p in props)
                    {
                        if (!AttributeMetadata[e.LogicalName].ContainsKey(p.Name))
                        {
                            AttributeMetadata[e.LogicalName].Add(p.Name, p.Name);
                        }
                    }
                }
                else
                {
                    throw new Exception(string.Format("Couldnt find reflected type for {0}", e.LogicalName));
                }
            }
            else
            {
                //If dynamic entities are being used, then the only way of guessing if a property exists is just by checking
                //if the entity has the attribute in the dictionary
                foreach (var attKey in e.Attributes.Keys)
                {
                    if (!AttributeMetadata[e.LogicalName].ContainsKey(attKey))
                    {
                        AttributeMetadata[e.LogicalName].Add(attKey, attKey);
                    }
                }
            }
        }
Example #45
0
 /// <summary>
 /// Ideally, we wouldn't generate any attributes, but we must in order to leverage
 /// the logic in CrmSvcUtil.  If the attribute for an OptionSet is not generated,
 /// then a null reference exception is thrown when attempting to create the
 /// OptionSet.  We will remove these in our ICustomizeCodeDomService implementation.
 /// </summary>
 public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
 {
     return(attributeMetadata.AttributeType == AttributeTypeCode.Picklist ||
            attributeMetadata.AttributeType == AttributeTypeCode.State ||
            attributeMetadata.AttributeType == AttributeTypeCode.Status);
 }
        public UserControl CreateControlForAttribute(IOrganizationServiceExtented service, bool fillAllways, EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, Entity entity, object value)
        {
            if (attributeMetadata is MemoAttributeMetadata memoAttrib)
            {
                string initialValue = null;

                if (value != null && value is string)
                {
                    initialValue = (string)value;
                }

                return(new MemoAttributeMetadataControl(fillAllways, memoAttrib, initialValue));
            }

            if (attributeMetadata is StringAttributeMetadata stringAttrib)
            {
                string initialValue = null;

                if (value != null && value is string)
                {
                    initialValue = (string)value;
                }

                return(new StringAttributeMetadataControl(fillAllways, stringAttrib, initialValue));
            }

            if (attributeMetadata is IntegerAttributeMetadata intAttrib)
            {
                int?initialValue = null;

                if (value != null && value is int)
                {
                    initialValue = (int)value;
                }

                return(new IntegerAttributeMetadataControl(fillAllways, intAttrib, initialValue));
            }

            if (attributeMetadata is BigIntAttributeMetadata bigIntAttrib)
            {
                long?initialValue = null;

                if (value != null && value is long)
                {
                    initialValue = (long)value;
                }

                return(new BigIntAttributeMetadataControl(fillAllways, bigIntAttrib, initialValue));
            }

            if (attributeMetadata is DecimalAttributeMetadata decimalAttrib)
            {
                decimal?initialValue = null;

                if (value != null && value is decimal)
                {
                    initialValue = (decimal)value;
                }

                return(new DecimalAttributeMetadataControl(fillAllways, decimalAttrib, initialValue));
            }

            if (attributeMetadata is DoubleAttributeMetadata doubleAttrib)
            {
                double?initialValue = null;

                if (value != null && value is double)
                {
                    initialValue = (double)value;
                }

                return(new DoubleAttributeMetadataControl(fillAllways, doubleAttrib, initialValue));
            }

            if (attributeMetadata is MoneyAttributeMetadata moneyAttrib)
            {
                Money initialValue = null;

                if (value != null && value is Money)
                {
                    initialValue = (Money)value;
                }

                return(new MoneyAttributeMetadataControl(fillAllways, moneyAttrib, initialValue));
            }

            if (attributeMetadata is DateTimeAttributeMetadata dateTimeAttrib)
            {
                DateTime?initialValue = null;

                if (value != null && value is DateTime)
                {
                    initialValue = (DateTime)value;
                }

                return(new DateTimeAttributeMetadataControl(fillAllways, dateTimeAttrib, initialValue));
            }

            if (attributeMetadata is BooleanAttributeMetadata boolAttrib)
            {
                bool?initialValue = null;

                if (value != null && value is bool boolValue)
                {
                    initialValue = boolValue;
                }

                return(new BooleanAttributeMetadataControl(fillAllways, boolAttrib, initialValue));
            }

            if (attributeMetadata is ManagedPropertyAttributeMetadata managedPropertyAttributeMetadata)
            {
                if (managedPropertyAttributeMetadata.ValueAttributeTypeCode == AttributeTypeCode.Boolean)
                {
                    BooleanManagedProperty initialValue = null;

                    if (value != null && value is BooleanManagedProperty booleanManagedProperty)
                    {
                        initialValue = booleanManagedProperty;
                    }

                    return(new BooleanManagedPropertyAttributeMetadataControl(fillAllways, managedPropertyAttributeMetadata, initialValue));
                }
            }

            if (attributeMetadata is PicklistAttributeMetadata picklistAttrib)
            {
                int?initialValue = null;

                if (value != null && value is OptionSetValue optionSetValue)
                {
                    initialValue = optionSetValue.Value;
                }

                return(new PicklistAttributeMetadataControl(fillAllways, entity, picklistAttrib, initialValue));
            }

            if (attributeMetadata is MultiSelectPicklistAttributeMetadata multiSelectPicklistAttributeMetadata)
            {
                OptionSetValueCollection initialValue = null;

                if (value != null && value is OptionSetValueCollection optionSetValueCollection)
                {
                    initialValue = optionSetValueCollection;
                }

                return(new MultiSelectPicklistAttributeMetadataControl(fillAllways, multiSelectPicklistAttributeMetadata, initialValue));
            }

            if (attributeMetadata is StatusAttributeMetadata statusAttrib)
            {
                var stateAttrib = entityMetadata.Attributes.OfType <StateAttributeMetadata>().FirstOrDefault();

                if (stateAttrib != null)
                {
                    int?initialValueStatus = null;
                    int?initialValueState  = null;

                    if (value != null && value is OptionSetValue optionSetValueStatus)
                    {
                        initialValueStatus = optionSetValueStatus.Value;
                    }

                    if (entity != null &&
                        entity.Attributes.ContainsKey(stateAttrib.LogicalName) &&
                        entity.Attributes[stateAttrib.LogicalName] != null &&
                        entity.Attributes[stateAttrib.LogicalName] is OptionSetValue optionSetValueState
                        )
                    {
                        initialValueState = optionSetValueState.Value;
                    }

                    return(new StatusAttributeMetadataControl(fillAllways, entity, statusAttrib, stateAttrib, initialValueStatus, initialValueState));
                }
            }

            if (attributeMetadata is LookupAttributeMetadata lookupAttrib)
            {
                EntityReference initialValue = null;

                if (value != null && value is EntityReference)
                {
                    initialValue = (EntityReference)value;
                }

                return(new LookupAttributeMetadataControl(service, fillAllways, lookupAttrib, initialValue));
            }

            if (attributeMetadata is EntityNameAttributeMetadata entityNameAttrib)
            {
                string initialValue = null;

                if (value != null && value is string entityName)
                {
                    initialValue = entityName;
                }

                return(new EntityNameAttributeMetadataControl(service, fillAllways, entityNameAttrib, initialValue));
            }

            if (attributeMetadata is UniqueIdentifierAttributeMetadata uniqueAttrib ||
                attributeMetadata.AttributeType == AttributeTypeCode.Uniqueidentifier
                )
            {
                Guid?initialValue = null;

                if (value != null && value is Guid valueGuid)
                {
                    initialValue = valueGuid;
                }

                return(new UniqueIdentifierAttributeMetadataControl(fillAllways, attributeMetadata, initialValue));
            }

            return(null);
        }
Example #47
0
        /// <summary>
        /// Draw on a Visio page the entity relationships defined in the passed-in relationship collection.
        /// </summary>
        /// <param name="entity">Core entity</param>
        /// <param name="rect">Shape representing the core entity</param>
        /// <param name="relationshipCollection">Collection of entity relationships to draw</param>
        /// <param name="areReferencingRelationships">Whether or not the core entity is the referencing entity in the relationship</param>
        private void DrawRelationships(CrmServiceClient service, EntityMetadata entity, VisioApi.Shape rect, RelationshipMetadataBase[] relationshipCollection, bool areReferencingRelationships)
        {
            ManyToManyRelationshipMetadata currentManyToManyRelationship = null;
            OneToManyRelationshipMetadata  currentOneToManyRelationship  = null;
            EntityMetadata    entity2    = null;
            AttributeMetadata attribute2 = null;
            AttributeMetadata attribute  = null;
            Guid metadataID   = Guid.NewGuid();
            bool isManyToMany = false;

            // Draw each relationship in the relationship collection.
            foreach (RelationshipMetadataBase entityRelationship in relationshipCollection)
            {
                entity2 = null;

                if (entityRelationship is ManyToManyRelationshipMetadata)
                {
                    isManyToMany = true;
                    currentManyToManyRelationship = entityRelationship as ManyToManyRelationshipMetadata;
                    // The entity passed in is not necessarily the originator of this relationship.
                    if (String.Compare(entity.LogicalName, currentManyToManyRelationship.Entity1LogicalName, true) != 0)
                    {
                        entity2 = GetEntityMetadata(service, currentManyToManyRelationship.Entity1LogicalName);
                    }
                    else
                    {
                        entity2 = GetEntityMetadata(service, currentManyToManyRelationship.Entity2LogicalName);
                    }
                    attribute2 = GetAttributeMetadata(service, entity2, entity2.PrimaryIdAttribute);
                    attribute  = GetAttributeMetadata(service, entity, entity.PrimaryIdAttribute);
                    metadataID = currentManyToManyRelationship.MetadataId.Value;
                }
                else if (entityRelationship is OneToManyRelationshipMetadata)
                {
                    isManyToMany = false;
                    currentOneToManyRelationship = entityRelationship as OneToManyRelationshipMetadata;
                    entity2    = GetEntityMetadata(service, areReferencingRelationships ? currentOneToManyRelationship.ReferencingEntity : currentOneToManyRelationship.ReferencedEntity);
                    attribute2 = GetAttributeMetadata(service, entity2, areReferencingRelationships ? currentOneToManyRelationship.ReferencingAttribute : currentOneToManyRelationship.ReferencedAttribute);
                    attribute  = GetAttributeMetadata(service, entity, areReferencingRelationships ? currentOneToManyRelationship.ReferencedAttribute : currentOneToManyRelationship.ReferencingAttribute);
                    metadataID = currentOneToManyRelationship.MetadataId.Value;
                }
                // Verify relationship is either ManyToManyMetadata or OneToManyMetadata
                if (entity2 != null)
                {
                    if (_processedRelationships.Contains(metadataID))
                    {
                        // Skip relationships we have already drawn
                        continue;
                    }
                    else
                    {
                        // Record we are drawing this relationship
                        _processedRelationships.Add(metadataID);

                        // Define convenience variables based upon the direction of referencing with respect to the core entity.
                        VisioApi.Shape rect2;


                        // Do not draw relationships involving the entity itself, SystemUser, BusinessUnit,
                        // or those that are intentionally excluded.
                        if (String.Compare(entity2.LogicalName, "systemuser", true) != 0 &&
                            String.Compare(entity2.LogicalName, "businessunit", true) != 0 &&
                            String.Compare(entity2.LogicalName, rect.Name, true) != 0 &&
                            String.Compare(entity.LogicalName, "systemuser", true) != 0 &&
                            String.Compare(entity.LogicalName, "businessunit", true) != 0 &&
                            !_excludedEntityTable.ContainsKey(entity2.LogicalName.GetHashCode()) &&
                            !_excludedRelationsTable.ContainsKey(attribute.LogicalName.GetHashCode()))
                        {
                            // Either find or create a shape that represents this secondary entity, and add the name of
                            // the involved attribute to the shape's text.
                            try
                            {
                                rect2 = rect.ContainingPage.Shapes.get_ItemU(entity2.SchemaName);

                                if (rect2.Text.IndexOf(attribute2.SchemaName) == -1)
                                {
                                    rect2.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowXFormOut, (short)VisioApi.VisCellIndices.visXFormHeight).ResultIU += 0.25;
                                    rect2.Text += "\n" + attribute2.SchemaName;

                                    // If the attribute is a primary key for the entity, append a [PK] label to the attribute name to indicate this.
                                    if (String.Compare(entity2.PrimaryIdAttribute, attribute2.LogicalName) == 0)
                                    {
                                        rect2.Text += "  [PK]";
                                    }
                                }
                            }
                            catch (System.Runtime.InteropServices.COMException)
                            {
                                rect2       = DrawEntityRectangle(service, rect.ContainingPage, entity2.SchemaName, entity2.OwnershipType.Value);
                                rect2.Text += "\n" + attribute2.SchemaName;

                                // If the attribute is a primary key for the entity, append a [PK] label to the attribute name to indicate so.
                                if (String.Compare(entity2.PrimaryIdAttribute, attribute2.LogicalName) == 0)
                                {
                                    rect2.Text += "  [PK]";
                                }
                            }

                            // Add the name of the involved attribute to the core entity's text, if not already present.
                            if (rect.Text.IndexOf(attribute.SchemaName) == -1)
                            {
                                rect.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowXFormOut, (short)VisioApi.VisCellIndices.visXFormHeight).ResultIU += HEIGHT;
                                rect.Text += "\n" + attribute.SchemaName;

                                // If the attribute is a primary key for the entity, append a [PK] label to the attribute name to indicate so.
                                if (String.Compare(entity.PrimaryIdAttribute, attribute.LogicalName) == 0)
                                {
                                    rect.Text += "  [PK]";
                                }
                            }

                            // Update the style of the entity name
                            VisioApi.Characters characters  = rect.Characters;
                            VisioApi.Characters characters2 = rect2.Characters;

                            //set the font family of the text to segoe for the visio 2013.
                            if (VersionName == "15.0")
                            {
                                characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterFont, (short)FONT_STYLE);
                                characters2.set_CharProps((short)VisioApi.VisCellIndices.visCharacterFont, (short)FONT_STYLE);
                            }
                            switch (entity2.OwnershipType)
                            {
                            case OwnershipTypes.BusinessOwned:
                                // set the font color of the text
                                characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visBlack);
                                characters2.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visBlack);
                                break;

                            case OwnershipTypes.OrganizationOwned:
                                // set the font color of the text
                                characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visBlack);
                                characters2.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visBlack);
                                break;

                            case OwnershipTypes.UserOwned:
                                // set the font color of the text
                                characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visWhite);
                                characters2.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visWhite);
                                break;

                            default:
                                break;
                            }

                            // Draw the directional, dynamic connector between the two entity shapes.
                            if (areReferencingRelationships)
                            {
                                DrawDirectionalDynamicConnector(service, rect, rect2, isManyToMany);
                            }
                            else
                            {
                                DrawDirectionalDynamicConnector(service, rect2, rect, isManyToMany);
                            }
                        }
                        else
                        {
                            Debug.WriteLine(String.Format("<{0} - {1}> not drawn.", rect.Name, entity2.LogicalName), "Relationship");
                        }
                    }
                }
            }
        }
 /// <summary>
 /// If true a child attribute cannot be published or externally consumed.
 /// </summary>
 private bool IsNotExposedChildAttribute(AttributeMetadata attributeMetadata)
 {
     return(!string.IsNullOrEmpty(attributeMetadata.AttributeOf) && !(attributeMetadata is ImageAttributeMetadata) && !attributeMetadata.LogicalName.EndsWith("_url", StringComparison.OrdinalIgnoreCase) && !attributeMetadata.LogicalName.EndsWith("_timestamp", StringComparison.OrdinalIgnoreCase));
 }
Example #49
0
        public void MapAttributes(Entity entity, object[] data)
        {
            foreach (var dataMapping in this.mappings)
            {
                AttributeMetadata attributeMetadata = this.attributeMetadataDictionary[dataMapping.Target];
                object            obj = data[this.columnMetadataDictionary[dataMapping.Source].ColumnIndex];

                if (obj == null)
                {
                    entity.Attributes.Add(dataMapping.Target, null);
                    continue;
                }

                switch (attributeMetadata.AttributeType.Value)
                {
                case AttributeTypeCode.BigInt:
                    long longValue = Convert.ToInt64(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, longValue);
                    break;

                case AttributeTypeCode.Boolean:
                    bool booleanValue = Convert.ToBoolean(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, booleanValue);
                    break;

                case AttributeTypeCode.Customer:
                    throw new NotImplementedException("Customermappings are not supported in marketinglists right now!");

                case AttributeTypeCode.DateTime:
                    if (obj.GetType() == typeof(DateTime))
                    {
                        entity.Attributes.Add(dataMapping.Target, (DateTime)obj);
                    }
                    else
                    {
                        DateTime?dt = DateTimeHelper.ConvertStringToDateTime(obj.ToString(), dataMapping.ValueFormat);
                        if (dt != null)
                        {
                            entity.Attributes.Add(attributeMetadata.LogicalName, dt);
                        }
                        else
                        {
                            throw new Exception("Could not convert value " + obj.ToString() + " to datetime. Please correct value or check valueformat!");
                        }
                    }
                    break;

                case AttributeTypeCode.Decimal:
                    decimal decimalValue = Convert.ToDecimal(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, decimalValue);
                    break;

                case AttributeTypeCode.Double:
                    double doubleValue = Convert.ToDouble(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, doubleValue);
                    break;

                case AttributeTypeCode.Integer:
                    int intValue = Convert.ToInt32(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, intValue);
                    break;

                case AttributeTypeCode.Owner:
                case AttributeTypeCode.Lookup:
                    throw new NotImplementedException("Loojups are not supported in marketinglists right now!");

                case AttributeTypeCode.Money:
                    decimal moneyValue = Convert.ToDecimal(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, new Money(moneyValue));
                    break;

                case AttributeTypeCode.Memo:
                case AttributeTypeCode.String:
                    string stringValue = obj.ToString();
                    entity.Attributes.Add(dataMapping.Target, stringValue);
                    break;

                case AttributeTypeCode.Status:
                case AttributeTypeCode.Picklist:
                    throw new NotImplementedException("Picklists are not supported in marketinglists right now!");

                case AttributeTypeCode.Uniqueidentifier:
                    Guid id = new Guid(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, id);
                    break;

                default:
                    throw new Exception("Could not convert attribute with type " + attributeMetadata.AttributeType.Value.ToString());
                }
            }
        }
Example #50
0
        public static MappingField Parse(AttributeMetadata attribute, MappingEntity entity)
        {
            var result = new MappingField();

            result.Entity            = entity;
            result.AttributeOf       = attribute.AttributeOf;
            result.IsValidForCreate  = (bool)attribute.IsValidForCreate;
            result.IsValidForRead    = (bool)attribute.IsValidForRead;
            result.IsValidForUpdate  = (bool)attribute.IsValidForUpdate;
            result.IsActivityParty   = attribute.AttributeType == AttributeTypeCode.PartyList ? true : false;
            result.IsStateCode       = attribute.AttributeType == AttributeTypeCode.State ? true : false;
            result.IsOptionSet       = attribute.AttributeType == AttributeTypeCode.Picklist;
            result.IsTwoOption       = attribute.AttributeType == AttributeTypeCode.Boolean;
            result.DeprecatedVersion = attribute.DeprecatedVersion;
            result.IsDeprecated      = !string.IsNullOrWhiteSpace(attribute.DeprecatedVersion);

            if (attribute is PicklistAttributeMetadata)
            {
                result.EnumData =
                    MappingEnum.Parse(attribute as PicklistAttributeMetadata);
            }

            if (attribute is LookupAttributeMetadata)
            {
                var lookup = attribute as LookupAttributeMetadata;

                if (lookup.Targets.Count() == 1)
                {
                    result.LookupSingleType = lookup.Targets[0];
                }
            }

            ParseMinMaxValues(attribute, result);

            if (attribute.AttributeType != null)
            {
                result.FieldType = attribute.AttributeType.Value;
            }

            result.IsPrimaryKey = attribute.IsPrimaryId == true;

            result.LogicalName         = attribute.LogicalName;
            result.DisplayName         = Naming.GetProperVariableName(attribute);
            result.PrivatePropertyName = Naming.GetEntityPropertyPrivateName(attribute.SchemaName);
            result.HybridName          = Naming.GetProperHybridFieldName(result.DisplayName, result.Attribute);

            if (attribute.Description != null)
            {
                if (attribute.Description.UserLocalizedLabel != null)
                {
                    result.Description = attribute.Description.UserLocalizedLabel.Label;
                }
            }

            if (attribute.DisplayName != null)
            {
                if (attribute.DisplayName.UserLocalizedLabel != null)
                {
                    result.Label = attribute.DisplayName.UserLocalizedLabel.Label;
                }
            }

            result.IsRequired = attribute.RequiredLevel != null && attribute.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired;

            result.Attribute =
                new CrmPropertyAttribute
            {
                LogicalName = attribute.LogicalName,
                IsLookup    = attribute.AttributeType == AttributeTypeCode.Lookup || attribute.AttributeType == AttributeTypeCode.Customer
            };
            result.TargetTypeForCrmSvcUtil = GetTargetType(result);
            result.FieldTypeString         = result.TargetTypeForCrmSvcUtil;


            return(result);
        }
Example #51
0
        private static KeyValuePair <string, string>?GetSearchResultAttribute(OrganizationServiceContext context, Entity entity, AttributeMetadata attributeMetadata, IDictionary <string, EntityMetadata> metadataCache)
        {
            var label = attributeMetadata.DisplayName.GetLocalizedLabelString();

            if (AttributeTypeEqualsOneOf(attributeMetadata, "lookup", "customer"))
            {
                return(null);
            }

            if (AttributeTypeEqualsOneOf(attributeMetadata, "picklist"))
            {
                var picklistMetadata = attributeMetadata as PicklistAttributeMetadata;

                if (picklistMetadata == null)
                {
                    return(null);
                }

                var picklistValue = entity.GetAttributeValue <OptionSetValue>(attributeMetadata.LogicalName);

                if (picklistValue == null)
                {
                    return(null);
                }

                var option = picklistMetadata.OptionSet.Options.FirstOrDefault(o => o.Value != null && o.Value.Value == picklistValue.Value);

                if (option == null || option.Label == null || option.Label.UserLocalizedLabel == null)
                {
                    return(null);
                }

                new KeyValuePair <string, string>(label, option.Label.GetLocalizedLabelString());
            }

            var value = entity.GetAttributeValue <object>(attributeMetadata.LogicalName);

            return(value == null ? null : new KeyValuePair <string, string>?(new KeyValuePair <string, string>(label, value.ToString())));
        }
Example #52
0
        private static bool AttributeTypeEqualsOneOf(AttributeMetadata attributeMetadata, params string[] typeNames)
        {
            var attributeTypeName = attributeMetadata.AttributeType.Value.ToString();

            return(typeNames.Any(name => string.Equals(attributeTypeName, name, StringComparison.InvariantCultureIgnoreCase)));
        }
        /// <summary>
        /// Adds DataColumns to the specified dataTable for the specified field.
        /// </summary>
        /// <param name="dataTable">The data table.</param>
        /// <param name="field">The field.</param>
        /// <param name="attributeMetadata">The field attribute metadata.</param>
        protected void AddDataColumns(DataTable dataTable, Dynamics365Field field, AttributeMetadata attributeMetadata)
        {
            Dynamics365TypeConverter converter = new Dynamics365TypeConverter(attributeMetadata);

            if (DataTypes == DataTypes.Native)
            {
                DataColumn nativeColumn = new DataColumn()
                {
                    ColumnName = string.Format("{0}.{1}", field.EntityLogicalName, field.LogicalName),
                    Caption    = field.DisplayName,
                    DataType   = converter.Dynamics365Type
                };

                if (!dataTable.Columns.Contains(nativeColumn.ColumnName))
                {
                    dataTable.Columns.Add(nativeColumn);
                }
            }
            else if (DataTypes == DataTypes.Neutral)
            {
                if (converter.Dynamics365Type == typeof(EntityReference) || converter.Dynamics365Type == typeof(EntityCollection))
                {
                    if (LookupBehaviour == LookupBehaviour.Name || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                    {
                        DataColumn nameColumn = new DataColumn()
                        {
                            ColumnName = string.Format("{0}.{1}{2}", field.EntityLogicalName, field.LogicalName, LookupBehaviour == LookupBehaviour.Name ? string.Empty : ".Name"),
                            Caption    = string.Format("{0}{1}", field.DisplayName, LookupBehaviour == LookupBehaviour.Name ? string.Empty : " (Name)"),
                            DataType   = typeof(string)
                        };

                        if (!dataTable.Columns.Contains(nameColumn.ColumnName)) // todo - fetch xml view on team entity caused duplication - investigate why
                        {
                            dataTable.Columns.Add(nameColumn);
                        }
                    }

                    if (LookupBehaviour == LookupBehaviour.Identifier || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                    {
                        DataColumn identifierColumn = new DataColumn()
                        {
                            ColumnName = string.Format("{0}.{1}{2}", field.EntityLogicalName, field.LogicalName, LookupBehaviour == LookupBehaviour.Identifier ? string.Empty : ".Identifier"),
                            Caption    = string.Format("{0}{1}", field.DisplayName, LookupBehaviour == LookupBehaviour.Identifier ? string.Empty : " (Identifier)"),
                            DataType   = converter.Dynamics365Type == typeof(EntityReference) ? typeof(Guid) : typeof(string)
                        };
                        dataTable.Columns.Add(identifierColumn);
                    }

                    if (LookupBehaviour == LookupBehaviour.Entity || LookupBehaviour == LookupBehaviour.EntityAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                    {
                        DataColumn entityColumn = new DataColumn()
                        {
                            ColumnName = string.Format("{0}.{1}{2}", field.EntityLogicalName, field.LogicalName, LookupBehaviour == LookupBehaviour.Entity ? string.Empty : ".Entity"),
                            Caption    = string.Format("{0}{1}", field.DisplayName, LookupBehaviour == LookupBehaviour.Entity ? string.Empty : " (Entity)"),
                            DataType   = typeof(string)
                        };

                        if (!dataTable.Columns.Contains(entityColumn.ColumnName))
                        {
                            dataTable.Columns.Add(entityColumn);
                        }
                    }
                }
                else if (converter.Dynamics365Type == typeof(OptionSetValue) || converter.Dynamics365Type == typeof(OptionSetValueCollection))
                {
                    if (OptionSetBehaviour == OptionSetBehaviour.Name || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                    {
                        DataColumn nameColumn = new DataColumn()
                        {
                            ColumnName = string.Format("{0}.{1}{2}", field.EntityLogicalName, field.LogicalName, OptionSetBehaviour == OptionSetBehaviour.Name ? string.Empty : ".Name"),
                            Caption    = string.Format("{0}{1}", field.DisplayName, OptionSetBehaviour == OptionSetBehaviour.Name ? string.Empty : " (Name)"),
                            DataType   = typeof(string)
                        };

                        if (!dataTable.Columns.Contains(nameColumn.ColumnName))
                        {
                            dataTable.Columns.Add(nameColumn);
                        }
                    }

                    if (OptionSetBehaviour == OptionSetBehaviour.Code || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                    {
                        DataColumn codeColumn = new DataColumn()
                        {
                            ColumnName = string.Format("{0}.{1}{2}", field.EntityLogicalName, field.LogicalName, OptionSetBehaviour == OptionSetBehaviour.Code ? string.Empty : ".Code"),
                            Caption    = string.Format("{0}{1}", field.DisplayName, OptionSetBehaviour == OptionSetBehaviour.Code ? string.Empty : " (Code)"),
                            DataType   = converter.Dynamics365Type == typeof(OptionSetValue) ? typeof(int) : typeof(string)
                        };

                        if (!dataTable.Columns.Contains(codeColumn.ColumnName))
                        {
                            dataTable.Columns.Add(codeColumn);
                        }
                    }
                }
                else
                {
                    DataColumn neutralColumn = new DataColumn()
                    {
                        ColumnName = string.Format("{0}.{1}", field.EntityLogicalName, field.LogicalName),
                        Caption    = field.DisplayName,
                        DataType   = converter.NeutralType
                    };

                    if (!dataTable.Columns.Contains(neutralColumn.ColumnName))
                    {
                        dataTable.Columns.Add(neutralColumn);
                    }
                }
            }
        }
Example #54
0
        private List <string> checkGlobalDifferenceAttributeMetadata(AttributeMetadata originalAttributeMetadata, AttributeMetadata readAttributeMetadata)
        {
            List <string> attributeToChange = new List <string>();

            if (Utils.getLocalizedLabel(originalAttributeMetadata.DisplayName.LocalizedLabels, languageCode) != Utils.getLocalizedLabel(readAttributeMetadata.DisplayName.LocalizedLabels, languageCode))
            {
                Utils.setLocalizedLabel(originalAttributeMetadata.DisplayName.LocalizedLabels, languageCode, Utils.getLocalizedLabel(readAttributeMetadata.DisplayName.LocalizedLabels, languageCode));
                attributeToChange.Add("Display Name");
            }
            if (Utils.getLocalizedLabel(originalAttributeMetadata.Description.LocalizedLabels, languageCode) != Utils.getLocalizedLabel(readAttributeMetadata.Description.LocalizedLabels, languageCode))
            {
                Utils.setLocalizedLabel(originalAttributeMetadata.Description.LocalizedLabels, languageCode, Utils.getLocalizedLabel(readAttributeMetadata.Description.LocalizedLabels, languageCode));
                attributeToChange.Add("Description");
            }

            if (originalAttributeMetadata.RequiredLevel.Value != readAttributeMetadata.RequiredLevel.Value)
            {
                originalAttributeMetadata.RequiredLevel = readAttributeMetadata.RequiredLevel;
                attributeToChange.Add("RequiredLevel");
            }
            if (originalAttributeMetadata.IsValidForAdvancedFind.Value != readAttributeMetadata.IsValidForAdvancedFind.Value)
            {
                originalAttributeMetadata.IsValidForAdvancedFind = readAttributeMetadata.IsValidForAdvancedFind;
                attributeToChange.Add("IsValidForAdvancedFind");
            }
            if (originalAttributeMetadata.IsSecured.Value != readAttributeMetadata.IsSecured.Value)
            {
                originalAttributeMetadata.IsSecured = readAttributeMetadata.IsSecured;
                attributeToChange.Add("IsSecured");
            }
            if (originalAttributeMetadata.IsAuditEnabled.Value != readAttributeMetadata.IsAuditEnabled.Value)
            {
                originalAttributeMetadata.IsAuditEnabled = readAttributeMetadata.IsAuditEnabled;
                attributeToChange.Add("IsAuditEnabled");
            }
            return(attributeToChange);
        }
 protected virtual AttributeInfo CreatePicklist(AttributeMetadata attributeMetadata)
 {
     var attMeta = (PicklistAttributeMetadata)attributeMetadata;
     var attInfo = new PicklistAttributeInfo(attMeta.OptionSet);
     attInfo.DefaultValue = attMeta.DefaultFormValue;
     return attInfo;
 }
        /// <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);
        }
 protected virtual AttributeInfo CreateString(AttributeMetadata attributeMetadata)
 {
     var attMeta = (StringAttributeMetadata)attributeMetadata;
     var attInfo = new StringAttributeInfo();
     attInfo.Length = attMeta.MaxLength.GetValueOrDefault();
     return attInfo;
 }
Example #58
0
        public void WriteData(IConnection connection, IDatabaseInterface databaseInterface, IDatastore dataObject, ReportProgressMethod reportProgress)
        {
            reportProgress(new SimpleProgressReport("Building logging database"));
            this.logger = new Logger(databaseInterface);
            this.logger.InitializeDatabase();

            reportProgress(new SimpleProgressReport("Connection to crm"));
            this.service = connection.GetConnection() as IOrganizationService;

            reportProgress(new SimpleProgressReport("Loading Entitymetadata"));
            var entityMetaData = Crm2013Wrapper.Crm2013Wrapper.GetEntityMetadata(service, this.Configuration.EntityName);
            var primaryKeyAttributeMetadataDictionary = new Dictionary <string, AttributeMetadata>();

            foreach (string primaryKey in this.Configuration.PrimaryKeyAttributes)
            {
                AttributeMetadata attributeMetadata = entityMetaData.Attributes.Where(t => t.LogicalName == primaryKey).FirstOrDefault();
                primaryKeyAttributeMetadataDictionary.Add(primaryKey, attributeMetadata);
            }

            attributeMetadataDictionary = entityMetaData.GetAttributeMetadata();

            reportProgress(new SimpleProgressReport("Initialize service-objects"));
            var entityMapper            = new EntityMapper(attributeMetadataDictionary, dataObject.Metadata, Configuration.Mapping, Configuration.PicklistMapping);
            var entityAttributeComparer = new EntityAttributeComparer(attributeMetadataDictionary);

            entityUpdateHandler = new EntityUpdateHandler(entityAttributeComparer);

            reportProgress(new SimpleProgressReport("Mapping attributes of records"));
            Entity[] entities = new Entity[dataObject.Count];
            for (int i = 0; i < dataObject.Count; i++)
            {
                object[] data = dataObject[i];

                Entity entity = new Entity(this.Configuration.EntityName);
                entityMapper.MapAttributes(entity, data);

                entities[i] = entity;
                logger.AddRecord(i);

                if (StatusHelper.MustShowProgress(i, dataObject.Count) == true)
                {
                    reportProgress(new SimpleProgressReport("Mapped " + (i + 1) + " of " + dataObject.Count + " records"));
                }
            }

            reportProgress(new SimpleProgressReport("Resolving relationship entities"));

            foreach (var relationMapping in Configuration.RelationMapping)
            {
                reportProgress(new SimpleProgressReport("Resolving relationship - load metadata for entity " + relationMapping.EntityName));
                EntityMetadata relationEntityMetadata = Crm2013Wrapper.Crm2013Wrapper.GetEntityMetadata(service, relationMapping.EntityName);

                reportProgress(new SimpleProgressReport("Resolving relationship - load related records"));
                JoinResolver relationResolver = new JoinResolver(service, relationEntityMetadata, relationMapping.Mapping);
                Dictionary <string, Guid[]> relatedEntities = relationResolver.BuildMassResolverIndex();

                reportProgress(new SimpleProgressReport("Resolving relationship - set relations"));

                RelationSetter relationSetter = new RelationSetter(relationEntityMetadata, relationMapping.Mapping);
                relationSetter.SetRelation(relationMapping.LogicalName, entities, dataObject, relatedEntities);
            }

            reportProgress(new SimpleProgressReport("Resolving primarykeys of records"));
            var primaryKeyResolver = new PrimaryKeyResolver(service, entityMetaData, primaryKeyAttributeMetadataDictionary);
            var resolvedEntities   = primaryKeyResolver.BatchResolver(entities, Configuration.GetAllMappedAttributes(), Configuration.BatchSizeResolving);

            reportProgress(new SimpleProgressReport("Writing records to crm"));
            WriteEntity(entities, resolvedEntities, primaryKeyAttributeMetadataDictionary, reportProgress);
        }
Example #59
0
        private string GetAddAdditionalData(AttributeMetadata amd)
        {
            if (amd.AttributeType != null)
                switch (amd.AttributeType.Value)
                {
                    case AttributeTypeCode.BigInt:
                        {
                            var bamd = (BigIntAttributeMetadata)amd;

                            return string.Format(
                                "Minimum value: {0}\nMaximum value: {1}",
                                bamd.MinValue.HasValue
                                    ? bamd.MinValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                bamd.MaxValue.HasValue
                                    ? bamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Boolean:
                        {
                            var bamd = (BooleanAttributeMetadata)amd;

                            var trueLabel = bamd.OptionSet.TrueOption.Label.LocalizedLabels.Count == 0
                                                ? null
                                                : bamd.OptionSet.TrueOption.Label.LocalizedLabels.FirstOrDefault(
                                                    l => l.LanguageCode == _settings.DisplayNamesLangugageCode);
                            var falseLabel = bamd.OptionSet.FalseOption.Label.LocalizedLabels.Count == 0
                                                 ? null
                                                 : bamd.OptionSet.FalseOption.Label.LocalizedLabels.
                                                        FirstOrDefault(
                                                            l =>
                                                            l.LanguageCode == _settings.DisplayNamesLangugageCode);

                            return string.Format(
                                "True: {0}\nFalse: {1}\nDefault Value: {2}",
                                bamd.OptionSet.TrueOption == null
                                    ? "N/A"
                                    : trueLabel != null ? trueLabel.Label : "Not Translated",
                                bamd.OptionSet.FalseOption == null
                                    ? "N/A"
                                    : falseLabel != null ? falseLabel.Label : "Not Translated",
                                (bamd.DefaultValue != null && bamd.DefaultValue.Value).ToString(
                                    CultureInfo.InvariantCulture));
                        }
                    case AttributeTypeCode.Customer:
                        {
                            // Do Nothing
                        }
                        break;

                    case AttributeTypeCode.DateTime:
                        {
                            var damd = (DateTimeAttributeMetadata)amd;

                            return string.Format(
                                "Format: {0}",
                                damd.Format.HasValue ? damd.Format.Value.ToString() : "N/A");
                        }
                    case AttributeTypeCode.Decimal:
                        {
                            var damd = (DecimalAttributeMetadata)amd;

                            return string.Format(
                                "Minimum value: {0}\nMaximum value: {1}\nPrecision: {2}",
                                damd.MinValue.HasValue
                                    ? damd.MinValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                damd.MaxValue.HasValue
                                    ? damd.MaxValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                damd.Precision.HasValue
                                    ? damd.Precision.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Double:
                        {
                            var damd = (DoubleAttributeMetadata)amd;

                            return string.Format(
                                "Minimum value: {0}\nMaximum value: {1}\nPrecision: {2}",
                                damd.MinValue.HasValue
                                    ? damd.MinValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                damd.MaxValue.HasValue
                                    ? damd.MaxValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                damd.Precision.HasValue
                                    ? damd.Precision.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.EntityName:
                        {
                            // Do nothing
                        }
                        break;

                    case AttributeTypeCode.Integer:
                        {
                            var iamd = (IntegerAttributeMetadata)amd;

                            return string.Format(
                                "Minimum value: {0}\nMaximum value: {1}",
                                iamd.MinValue.HasValue
                                    ? iamd.MinValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                iamd.MaxValue.HasValue
                                    ? iamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Lookup:
                        {
                            var lamd = (LookupAttributeMetadata)amd;

                            return lamd.Targets.Aggregate("Targets:", (current, entity) => current + ("\n" + entity));
                        }
                    case AttributeTypeCode.Memo:
                        {
                            var mamd = (MemoAttributeMetadata)amd;

                            return string.Format(
                                "Format: {0}\nMax length: {1}",
                                mamd.Format.HasValue ? mamd.Format.Value.ToString() : "N/A",
                                mamd.MaxLength.HasValue
                                    ? mamd.MaxLength.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Money:
                        {
                            var mamd = (MoneyAttributeMetadata)amd;

                            return string.Format(
                                "Minimum value: {0}\nMaximum value: {1}\nPrecision: {2}",
                                mamd.MinValue.HasValue
                                    ? mamd.MinValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                mamd.MaxValue.HasValue
                                    ? mamd.MaxValue.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A",
                                mamd.Precision.HasValue
                                    ? mamd.Precision.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Owner:
                        {
                            // Do nothing
                        }
                        break;

                    case AttributeTypeCode.PartyList:
                        {
                            // Do nothing
                        }
                        break;

                    case AttributeTypeCode.Picklist:
                        {
                            var pamd = (PicklistAttributeMetadata)amd;

                            var format = "Options:";

                            foreach (var omd in pamd.OptionSet.Options)
                            {
                                var optionLabel = omd.Label.LocalizedLabels.Count == 0
                                                      ? null
                                                      : omd.Label.LocalizedLabels.FirstOrDefault(
                                                          l =>
                                                          l.LanguageCode == _settings.DisplayNamesLangugageCode);

                                format += string.Format("\n{0}: {1}",
                                                        omd.Value,
                                                        optionLabel != null ? optionLabel.Label : "Not Translated");
                            }

                            format += string.Format("\nDefault: {0}",
                                                    pamd.DefaultFormValue.HasValue
                                                        ? pamd.DefaultFormValue.Value.ToString(
                                                            CultureInfo.InvariantCulture)
                                                        : "N/A");

                            return format;
                        }
                    case AttributeTypeCode.State:
                        {
                            var samd = (StateAttributeMetadata)amd;

                            var format = "States:";

                            foreach (var omd in samd.OptionSet.Options)
                            {
                                var optionLabel = omd.Label.LocalizedLabels.Count == 0
                                                      ? null
                                                      : omd.Label.LocalizedLabels.FirstOrDefault(
                                                          l =>
                                                          l.LanguageCode == _settings.DisplayNamesLangugageCode);

                                format += string.Format("\n{0}: {1}",
                                                        omd.Value,
                                                        optionLabel != null ? optionLabel.Label : "Not Translated");
                            }

                            return format;
                        }
                    case AttributeTypeCode.Status:
                        {
                            var samd = (StatusAttributeMetadata)amd;

                            string format = "States:";

                            foreach (var omd in samd.OptionSet.Options)
                            {
                                var optionLabel = omd.Label.LocalizedLabels.Count == 0
                                                      ? null
                                                      : omd.Label.LocalizedLabels.FirstOrDefault(
                                                          l =>
                                                          l.LanguageCode == _settings.DisplayNamesLangugageCode);

                                format += string.Format("\n{0}: {1}",
                                                        omd.Value,
                                                        optionLabel != null ? optionLabel.Label : "Not Translated");
                            }

                            return format;
                        }
                    case AttributeTypeCode.String:
                        {
                            var samd = (StringAttributeMetadata)amd;

                            return string.Format(
                                "Format: {0}\nMax length: {1}",
                                samd.Format.HasValue ? samd.Format.Value.ToString() : "N/A",
                                samd.MaxLength.HasValue
                                    ? samd.MaxLength.Value.ToString(CultureInfo.InvariantCulture)
                                    : "N/A");
                        }
                    case AttributeTypeCode.Uniqueidentifier:
                        {
                            // Do Nothing
                        }
                        break;
                }

            return string.Empty;
        }
Example #60
0
        public static AttributeMetadata SetMetadataType(string type, string prefix, string name)
        {
            AttributeMetadata value = new AttributeMetadata();

            switch (type)
            {
            case "Single Line of Text":
                value = new StringAttributeMetadata();
                ((StringAttributeMetadata)value).Format    = Microsoft.Xrm.Sdk.Metadata.StringFormat.Text;
                ((StringAttributeMetadata)value).MaxLength = 100;
                break;

            case "Two Options":
                value = new BooleanAttributeMetadata();
                ((BooleanAttributeMetadata)value).OptionSet = new BooleanOptionSetMetadata(new OptionMetadata(
                                                                                               new Microsoft.Xrm.Sdk.Label("Yes", 1033), 10000),
                                                                                           new OptionMetadata(new Microsoft.Xrm.Sdk.Label("No", 1033), 10001));
                ((BooleanAttributeMetadata)value).DefaultValue = false;
                break;

            case "Whole Number":
                value = new IntegerAttributeMetadata();
                ((IntegerAttributeMetadata)value).Format   = Microsoft.Xrm.Sdk.Metadata.IntegerFormat.None;
                ((IntegerAttributeMetadata)value).MinValue = -2147483648;
                ((IntegerAttributeMetadata)value).MaxValue = 2147483647;
                break;

            case "Floating Point Number":
                value = new DoubleAttributeMetadata();
                ((DoubleAttributeMetadata)value).Precision = 2;
                ((DoubleAttributeMetadata)value).MinValue  = 0.00;
                ((DoubleAttributeMetadata)value).MaxValue  = 1000000000.00;
                break;

            case "Decimal Number":
                value = new DecimalAttributeMetadata();
                ((DecimalAttributeMetadata)value).Precision = 2;
                ((DecimalAttributeMetadata)value).MinValue  = (decimal)0.00;
                ((DecimalAttributeMetadata)value).MaxValue  = (decimal)1000000000.00;
                break;

            case "Currency":
                value = new MoneyAttributeMetadata();
                ((MoneyAttributeMetadata)value).Precision       = 4;
                ((MoneyAttributeMetadata)value).PrecisionSource = 2;
                ((MoneyAttributeMetadata)value).MinValue        = 0.0000;
                ((MoneyAttributeMetadata)value).MaxValue        = 1000000000.0000;
                break;

            case "Multiple Lines of Text":
                value = new MemoAttributeMetadata();
                ((MemoAttributeMetadata)value).MaxLength = 2000;
                break;

            case "Date and Time":
                value = new DateTimeAttributeMetadata();
                ((DateTimeAttributeMetadata)value).Format = Microsoft.Xrm.Sdk.Metadata.DateTimeFormat.DateOnly;
                break;
            }
            value.SchemaName     = prefix + "_" + name.ToLower();
            value.DisplayName    = new Microsoft.Xrm.Sdk.Label(name, 1033);
            value.IsAuditEnabled = new BooleanManagedProperty(true);
            return(value);
        }