public void InvalidUpdateIsValidForReadFalse()
        {
            var attribute = new AttributeMetadata
            {
                LogicalName = "contactattnoentity1"
            };
            var isLogicalEntityField = attribute.GetType().GetRuntimeFields().First(a => a.Name == "_validForRead");

            isLogicalEntityField.SetValue(attribute, (bool?)false);

            var item = new System.Windows.Forms.ListViewItem("Item1");

            FluentActions.Invoking(() => systemUnderTest.InvalidUpdate(attribute, item))
            .Should()
            .NotThrow();

            item.ToolTipText.Should().Contain("Not readable, ");
        }
Пример #2
0
        public string GetOptionSetText(string entityName, string attributeName, OptionSetValue optionSetValue, int?lcid)
        {
            if (optionSetValue == null)
            {
                return(string.Empty);
            }

            AttributeMetadata attrMetadata = _attributeMetadataList.FirstOrDefault(md => md.LogicalName == attributeName && md.EntityLogicalName == entityName);

            if (attrMetadata == null)
            {
                var attReq = new RetrieveAttributeRequest();
                attReq.EntityLogicalName     = entityName;
                attReq.LogicalName           = attributeName;
                attReq.RetrieveAsIfPublished = true;

                var attResponse = (RetrieveAttributeResponse)this.OrganizationService.Execute(attReq);
                attrMetadata = attResponse.AttributeMetadata;

                _attributeMetadataList.Add(attrMetadata);
            }

            OptionSetMetadata optionSet = null;

            switch (attrMetadata.GetType().Name)
            {
            case "PicklistAttributeMetadata":
                optionSet = ((PicklistAttributeMetadata)attrMetadata).OptionSet;
                break;

            case "StatusAttributeMetadata":
                optionSet = ((StatusAttributeMetadata)attrMetadata).OptionSet;
                break;

            case "StateAttributeMetadata":
                optionSet = ((StateAttributeMetadata)attrMetadata).OptionSet;
                break;
            }

            var option = optionSet.Options.Where(x => x.Value == optionSetValue.Value).FirstOrDefault();

            return(option?.Label.LocalizedLabels.Where(l => l.LanguageCode == (lcid.HasValue ? lcid.Value : DEFAULT_LOCALIZED_ENGLISH_LANGUAGE_CODE)).FirstOrDefault().Label);
        }
Пример #3
0
        private void GenerateGetterForOptionSetProperty(CodeNamespace codeNamespace, AttributeMetadata attributeMetadata, CodeMemberProperty codeMemberProperty, EntityMetadata entityMetadata)
        {
            if (codeNamespace == null)
            {
                throw new ArgumentNullException(nameof(codeNamespace));
            }
            if (attributeMetadata == null)
            {
                throw new ArgumentNullException(nameof(attributeMetadata));
            }
            if (codeMemberProperty == null)
            {
                throw new ArgumentNullException(nameof(codeMemberProperty));
            }
            if (entityMetadata == null)
            {
                throw new ArgumentNullException(nameof(entityMetadata));
            }
            if (attributeMetadata.GetType() != typeof(PicklistAttributeMetadata))
            {
                throw new InvalidCastException(AttributeIsNotExpectedMessage);
            }

            OptionSetMetadata osm = ((PicklistAttributeMetadata)attributeMetadata).OptionSet;
            string            osn = ServiceHelper.GetOptionSetName(entityMetadata, osm); if (string.IsNullOrWhiteSpace(osn))

            {
                return;
            }

            osn = string.IsNullOrWhiteSpace(codeNamespace.Name) ? osn : string.Format(CultureInfo.InvariantCulture, "{0}.{1}", codeNamespace.Name, osn);

            codeMemberProperty.GetStatements.Clear();
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\tvar optionSet = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(\"{0}\");", attributeMetadata.LogicalName)));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\tif (optionSet == null)"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t\treturn null;"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t}"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\telse"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t{"));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement(string.Format(CultureInfo.InvariantCulture, "\t\t\t\t\treturn ({0})(System.Enum.ToObject(typeof({0}), optionSet.Value));", osn)));
            codeMemberProperty.GetStatements.Add(new CodeSnippetStatement("\t\t\t\t}"));
        }
        protected static void InsertAttributeList(EntityMetadata entityMetadata, List <string> attributeLogicalNames)
        {
            var attributeList = new List <AttributeMetadata>();

            if (attributeLogicalNames != null)
            {
                foreach (var item in attributeLogicalNames)
                {
                    var attribute = new AttributeMetadata
                    {
                        LogicalName = item,
                        DisplayName = new Label
                        {
                            UserLocalizedLabel = new LocalizedLabel {
                                Label = item
                            }
                        }
                    };

                    var attributeTypeName = attribute.GetType().GetRuntimeFields().First(a => a.Name == "_attributeTypeDisplayName");
                    attributeTypeName.SetValue(attribute, new AttributeTypeDisplayName {
                        Value = item
                    });

                    attributeList.Add(attribute);
                }

                var field = entityMetadata?.GetType().GetRuntimeFields().First(a => a.Name == "_attributes");
                field.SetValue(entityMetadata, attributeList.ToArray());

                var isIntersectField = entityMetadata.GetType().GetRuntimeFields().First(a => a.Name == "_isIntersect");
                isIntersectField.SetValue(entityMetadata, (bool?)false);

                var isLogicalEntityField = entityMetadata.GetType().GetRuntimeFields().First(a => a.Name == "_isLogicalEntity");
                isLogicalEntityField.SetValue(entityMetadata, (bool?)false);

                var isCustomEntityField = entityMetadata.GetType().GetRuntimeFields().First(a => a.Name == "_isCustomEntity");
                isCustomEntityField.SetValue(entityMetadata, (bool?)true);
            }
        }
Пример #5
0
        public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
        {
            var solutionEntities = services.LoadSolutionEntities();

            var generate = false;

            if (attributeMetadata.AttributeType == AttributeTypeCode.Uniqueidentifier)
            {
                generate = true;
            }
            else if (attributeMetadata.AttributeOf != null && attributeMetadata.GetType() != typeof(ImageAttributeMetadata))
            {
                generate = false;
            }
            else if (solutionEntities.Any(x => x.LogicalName == attributeMetadata.EntityLogicalName && x.IncludedFields.Any(y => y.LogicalName == attributeMetadata.LogicalName)))
            {
                generate = _defaultService.GenerateAttribute(attributeMetadata, services);
            }

            this.Debug(generate, attributeMetadata.EntityLogicalName, attributeMetadata.LogicalName);

            return(generate);
        }
Пример #6
0
        internal static OptionSetMetadataBase GetAttributeOptionSet(AttributeMetadata attribute)
        {
            OptionSetMetadataBase result = null;
            var type = attribute.GetType();

            if (type == typeof(BooleanAttributeMetadata))
            {
                result = ((BooleanAttributeMetadata)attribute).OptionSet;
            }
            else if (type == typeof(StateAttributeMetadata))
            {
                result = ((StateAttributeMetadata)attribute).OptionSet;
            }
            else if (type == typeof(PicklistAttributeMetadata))
            {
                result = ((PicklistAttributeMetadata)attribute).OptionSet;
            }
            else if (type == typeof(StatusAttributeMetadata))
            {
                result = ((StatusAttributeMetadata)attribute).OptionSet;
            }
            return(result);
        }
Пример #7
0
        public void StoreLookUpAttributeNotLookupAttributeMetadata()
        {
            var    attributeLogicalName = "contactId";
            string primaryAttribute     = "contactId";
            var    crmField             = new Capgemini.Xrm.DataMigration.Model.CrmField()
            {
                PrimaryKey = false,
                FieldName  = primaryAttribute,
                FieldType  = "entityreference"
            };

            var attribute = new AttributeMetadata
            {
                LogicalName = attributeLogicalName,
                DisplayName = new Label
                {
                    UserLocalizedLabel = new LocalizedLabel {
                        Label = attributeLogicalName
                    }
                }
            };

            var attributeTypeName = attribute.GetType().GetRuntimeFields().First(a => a.Name == "_attributeTypeDisplayName");

            attributeTypeName.SetValue(attribute, new AttributeTypeDisplayName {
                Value = attributeLogicalName
            });

            NotificationServiceMock.Setup(x => x.DisplayFeedback("The supplied attribute is null. Expecting an Entity Reference!"))
            .Verifiable();

            FluentActions.Invoking(() => systemUnderTest.StoreLookUpAttribute(attribute, crmField, NotificationServiceMock.Object))
            .Should()
            .NotThrow();

            NotificationServiceMock.Verify(x => x.DisplayFeedback("The supplied attribute is null. Expecting an Entity Reference!"), Times.Once);
        }
Пример #8
0
        public static void SetGroupBoxNameByAttributeMetadata(GroupBox gbAttribute, AttributeMetadata attributeMetadata)
        {
            StringBuilder header = new StringBuilder(attributeMetadata.LogicalName);

            var displayName = CreateFileHandler.GetLocalizedLabel(attributeMetadata.DisplayName);
            var description = CreateFileHandler.GetLocalizedLabel(attributeMetadata.Description);

            if (attributeMetadata.AttributeTypeName != null && !string.IsNullOrEmpty(attributeMetadata.AttributeTypeName.Value))
            {
                header.AppendFormat(" - {0}", attributeMetadata.AttributeTypeName.Value);
            }
            else if (attributeMetadata.AttributeType.HasValue)
            {
                header.AppendFormat(" - {0}", attributeMetadata.AttributeType.ToString());
            }

            var attrType = attributeMetadata.GetType();

            if (attrType != typeof(AttributeMetadata))
            {
                header.AppendFormat(" - {0}", attrType.Name);
            }

            if (!string.IsNullOrEmpty(displayName))
            {
                header.AppendFormat(" - {0}", displayName);
            }
            else if (!string.IsNullOrEmpty(description))
            {
                header.AppendFormat(" - {0}", description);
            }

            header.Replace("_", "__");

            gbAttribute.Header = header.ToString();
        }
Пример #9
0
 private void SetEntityLogicalName(AttributeMetadata att, string entityLogicalName)
 {
     var prop = att.GetType().GetProperty("EntityLogicalName");
     prop.SetValue(att, entityLogicalName);
 }
Пример #10
0
        private void CopyData(IOrganizationService service, AttributeMetadata from, AttributeMetadata to, Action actions)
        {
            if (!MigrateData) { return; }

            var total = GetRecordCount(service, from);
            var count = 0;

            Trace("Copying data from {0} to {1}", from.LogicalName, to.LogicalName);
            var requests = new OrganizationRequestCollection();
            // Grab from and to, and only update if not equal.  This is to speed things up if it has failed part way through
            foreach (var entity in service.GetAllEntities<Entity>(new QueryExpression(from.EntityLogicalName) { ColumnSet = new ColumnSet(from.LogicalName, to.LogicalName) }))
            {
                if (count++ % 100 == 0 || count == total)
                {
                    if (requests.Any())
                    {
                        PerformUpdates(service, requests);
                    }

                    Trace("Copying {0} / {1}", count, total);
                    requests.Clear();
                }

                var value = entity.GetAttributeValue<Object>(from.LogicalName);
                if (actions.HasFlag(Action.ChangeType) && from.GetType() != to.GetType())
                {
                    value = CopyValue(from, to, value);
                }
                var toValue = entity.GetAttributeValue<Object>(to.LogicalName);
                
                if (value != null)
                {
                    if (value.Equals(toValue)) continue;

                    entity.Attributes[to.LogicalName] = value;
                    requests.Add(new UpdateRequest { Target = entity });
                }
                else if (toValue != null)
                {
                    entity.Attributes[to.LogicalName] = null;
                    requests.Add(new UpdateRequest { Target = entity });
                }
            }

            if (requests.Any())
            {
                PerformUpdates(service, requests);
            }

            Trace("Data Migration Complete", count, total);
        }
Пример #11
0
        private void CopyData(IOrganizationService service, AttributeMetadata from, AttributeMetadata to, Action actions)
        {
            if (!MigrateData)
            {
                return;
            }

            var total = GetRecordCount(service, from);
            var count = 0;

            Trace("Copying data from {0} to {1}", from.LogicalName, to.LogicalName);
            var requests = new OrganizationRequestCollection();

            // Grab from and to, and only update if not equal.  This is to speed things up if it has failed part way through
            foreach (var entity in service.GetAllEntities <Entity>(new QueryExpression(from.EntityLogicalName)
            {
                ColumnSet = new ColumnSet(from.LogicalName, to.LogicalName)
            }))
            {
                if (count++ % 100 == 0 || count == total)
                {
                    if (requests.Any())
                    {
                        PerformUpdates(service, requests);
                    }

                    Trace("Copying {0} / {1}", count, total);
                    requests.Clear();
                }

                var value = entity.GetAttributeValue <Object>(from.LogicalName);
                if (actions.HasFlag(Action.ChangeType) && from.GetType() != to.GetType())
                {
                    value = CopyValue(from, to, value);
                }
                var toValue = entity.GetAttributeValue <Object>(to.LogicalName);

                if (value != null)
                {
                    if (value.Equals(toValue))
                    {
                        continue;
                    }

                    entity.Attributes[to.LogicalName] = value;
                    requests.Add(new UpdateRequest
                    {
                        Target = entity
                    });
                }
                else if (toValue != null)
                {
                    entity.Attributes[to.LogicalName] = null;
                    requests.Add(new UpdateRequest
                    {
                        Target = entity
                    });
                }
            }

            if (requests.Any())
            {
                PerformUpdates(service, requests);
            }

            Trace("Data Migration Complete", count, total);
        }
Пример #12
0
        public static Type GetAttributeType(this AttributeMetadata attrMetadata)
        {
            if (attrMetadata is MultiSelectPicklistAttributeMetadata)
            {
                return(typeof(OptionSetValueCollection));
            }

            var typeCode = attrMetadata.AttributeType;

            if (attrMetadata is ManagedPropertyAttributeMetadata managedProp)
            {
                typeCode = managedProp.ValueAttributeTypeCode;
            }

            if (attrMetadata is BooleanAttributeMetadata || typeCode == AttributeTypeCode.Boolean)
            {
                return(typeof(bool?));
            }

            if (attrMetadata is DateTimeAttributeMetadata || typeCode == AttributeTypeCode.DateTime)
            {
                return(typeof(DateTime?));
            }

            if (attrMetadata is DecimalAttributeMetadata || typeCode == AttributeTypeCode.Decimal)
            {
                return(typeof(decimal?));
            }

            if (attrMetadata is DoubleAttributeMetadata || typeCode == AttributeTypeCode.Double)
            {
                return(typeof(double?));
            }

            if (attrMetadata is EntityNameAttributeMetadata || typeCode == AttributeTypeCode.EntityName)
            {
                return(typeof(int?));
            }

            if (attrMetadata is ImageAttributeMetadata)
            {
                return(typeof(byte[]));
            }

            if (attrMetadata is IntegerAttributeMetadata || typeCode == AttributeTypeCode.Integer)
            {
                return(typeof(int?));
            }

            if (attrMetadata is BigIntAttributeMetadata || typeCode == AttributeTypeCode.BigInt)
            {
                return(typeof(long?));
            }

            if (typeCode == AttributeTypeCode.PartyList)
            {
                return(typeof(EntityCollection));
            }

            if (attrMetadata is LookupAttributeMetadata || typeCode == AttributeTypeCode.Lookup || typeCode == AttributeTypeCode.Customer || typeCode == AttributeTypeCode.Owner)
            {
                return(typeof(Guid?));
            }

            if (attrMetadata is MemoAttributeMetadata || typeCode == AttributeTypeCode.Memo)
            {
                return(typeof(string));
            }

            if (attrMetadata is MoneyAttributeMetadata || typeCode == AttributeTypeCode.Money)
            {
                return(typeof(decimal?));
            }

            if (attrMetadata is PicklistAttributeMetadata || typeCode == AttributeTypeCode.Picklist)
            {
                return(typeof(int?));
            }

            if (attrMetadata is StateAttributeMetadata || typeCode == AttributeTypeCode.State)
            {
                return(typeof(int?));
            }

            if (attrMetadata is StatusAttributeMetadata || typeCode == AttributeTypeCode.Status)
            {
                return(typeof(int?));
            }

            if (attrMetadata is StringAttributeMetadata || typeCode == AttributeTypeCode.String)
            {
                return(typeof(string));
            }

            if (attrMetadata is UniqueIdentifierAttributeMetadata || typeCode == AttributeTypeCode.Uniqueidentifier)
            {
                return(typeof(Guid?));
            }

            if (attrMetadata.AttributeType == AttributeTypeCode.Virtual)
            {
                return(typeof(string));
            }

            throw new ApplicationException("Unknown attribute type " + attrMetadata.GetType());
        }
Пример #13
0
        public void Process(BackgroundWorker worker, ConnectionDetail detail)
        {
            var eiCache = new List <EntityInfo>();

            byte[] file = File.ReadAllBytes(settings.FilePath);
            using (MemoryStream ms = new MemoryStream(file))
                using (ExcelPackage package = new ExcelPackage(ms))
                {
                    ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
                    int            percent   = 0;
                    int            index     = 0;
                    for (int i = 3; i <= workSheet.Dimension.End.Row; i++)
                    {
                        if (string.IsNullOrEmpty(workSheet.GetValue <string>(i, TypeCellIndex)) ||
                            workSheet.GetValue <string>(i, 1) == "Ignore")
                        {
                            continue;
                        }

                        if (worker.CancellationPending)
                        {
                            return;
                        }

                        index++;

                        var info = new ProcessResult
                        {
                            DisplayName = workSheet.GetValue <string>(i, DisplayNameCellIndex),
                            Attribute   = workSheet.GetValue <string>(i, SchemaNameCellIndex),
                            Type        = workSheet.GetValue <string>(i, TypeCellIndex),
                            Entity      = workSheet.GetValue <string>(i, EntityCellIndex),
                            Processing  = true,
                        };

                        if ((info.Type == "Customer" || info.Type == "Lookup") && settings.AddLookupSuffix && !info.Attribute.EndsWith("Id"))
                        {
                            info.Attribute = $"{info.Attribute}Id";
                        }
                        if (info.Type == "OptionSet" && settings.AddOptionSetSuffix && !info.Attribute.ToLower().EndsWith("code"))
                        {
                            info.Attribute = $"{info.Attribute}Code";
                        }

                        worker.ReportProgress(percent, info);
                        percent = index * 100 / (workSheet.Dimension.End.Row - 2);

                        try
                        {
                            AttributeMetadata amd = null;
                            var fakeAmd           = GetFakeAmd(info, workSheet, i);

                            // Check validity for an Update
                            var ei = eiCache.FirstOrDefault(e => e.Name == info.Entity);
                            if (ei == null)
                            {
                                ei = new EntityInfo(info.Entity, service);
                                eiCache.Add(ei);
                            }

                            var existingAttribute = ei.Attributes.FirstOrDefault(a => a.LogicalName == info.Attribute.ToLower());
                            if (existingAttribute != null)
                            {
                                fakeAmd.MetadataId = existingAttribute.MetadataId;
                            }

                            var type = workSheet.GetValue <string>(i, TypeCellIndex);
                            switch (type)
                            {
                            case "Single line of text":

                                if (!string.IsNullOrEmpty(workSheet.GetValue <string>(i, PropertiesFirstCellIndex + 2)) && detail.OrganizationMajorVersion < 9)
                                {
                                    throw new Exception(
                                              "Autonumber attributes can only be created in a version 9 or above of Microsoft Dynamics 365");
                                }

                                amd = CreateStringAttribute(workSheet, i, PropertiesFirstCellIndex);
                                break;

                            case "OptionSet":
                                amd = CreateOptionsetAttribute(workSheet, i, PropertiesFirstCellIndex + 4, false, info.DisplayName, info.Attribute, info.Entity, fakeAmd.Description?.LocalizedLabels[0]?.Label, (existingAttribute as PicklistAttributeMetadata)?.OptionSet);
                                break;

                            case "Multiselect OptionSet":

                                if (detail.OrganizationMajorVersion < 9)
                                {
                                    throw new Exception(
                                              "Multiselect OptionSet can only be created in a version 9 or above of Microsoft Dynamics 365");
                                }

                                amd = CreateOptionsetAttribute(workSheet, i, PropertiesFirstCellIndex + 4, true, info.DisplayName, info.Attribute, info.Entity, fakeAmd.Description?.LocalizedLabels[0]?.Label, (existingAttribute as PicklistAttributeMetadata)?.OptionSet);
                                break;

                            case "Two options":
                                amd = CreateBooleanAttribute(workSheet, i, PropertiesFirstCellIndex + 8);
                                break;

                            case "Whole number":
                                amd = CreateNumberAttribute(workSheet, i, PropertiesFirstCellIndex + 11);
                                break;

                            case "Float number":
                                amd = CreateFloatAttribute(workSheet, i, PropertiesFirstCellIndex + 15);
                                break;

                            case "Decimal number":
                                amd = CreateDecimalAttribute(workSheet, i, PropertiesFirstCellIndex + 19);
                                break;

                            case "Money":
                                amd = CreateMoneyAttribute(workSheet, i, PropertiesFirstCellIndex + 23);
                                break;

                            case "Multiple lines of text":
                                amd = CreateMemoAttribute(workSheet, i, PropertiesFirstCellIndex);
                                break;

                            case "Date and time":
                                amd = CreateDateTimeAttribute(workSheet, i, PropertiesFirstCellIndex + 27);
                                break;

                            case "Lookup":
                                amd = CreateLookupAttribute(workSheet, i, PropertiesFirstCellIndex + 30, fakeAmd, info, !fakeAmd.MetadataId.HasValue);
                                break;

                            case "Customer":
                                amd = CreateCustomerAttribute(workSheet, i, PropertiesFirstCellIndex + 31, fakeAmd, existingAttribute, info, !fakeAmd.MetadataId.HasValue);
                                break;

                            case "File":
                                amd = CreateFileAttribute(workSheet, i, PropertiesFirstCellIndex + 45);
                                break;

                            case "Image":
                                amd = CreateImageAttribute(workSheet, i, PropertiesFirstCellIndex + 47);
                                break;
                            }

                            if (amd == null)
                            {
                                info.Success    = true;
                                info.Processing = false;
                                worker.ReportProgress(percent, info);
                                continue;
                            }

                            if (existingAttribute != null)
                            {
                                if (existingAttribute.GetType() != amd.GetType())
                                {
                                    throw new Exception(
                                              @"Attribute in Excel file is not of same type as existing attribute in organization");
                                }
                            }

                            amd.DisplayName            = fakeAmd.DisplayName;
                            amd.SchemaName             = fakeAmd.SchemaName;
                            amd.LogicalName            = fakeAmd.LogicalName;
                            amd.IsValidForAdvancedFind = fakeAmd.IsValidForAdvancedFind;
                            amd.IsSecured      = fakeAmd.IsSecured;
                            amd.IsAuditEnabled = fakeAmd.IsAuditEnabled;
                            amd.SourceType     = fakeAmd.SourceType;
                            amd.MetadataId     = fakeAmd.MetadataId;
                            amd.RequiredLevel  = fakeAmd.RequiredLevel;
                            if (fakeAmd.Description != null)
                            {
                                amd.Description = fakeAmd.Description;
                            }

                            info.Attribute = amd.SchemaName;

                            OrganizationRequest request;
                            if (amd.MetadataId.HasValue)
                            {
                                request = new UpdateAttributeRequest
                                {
                                    Attribute          = amd,
                                    EntityName         = info.Entity,
                                    SolutionUniqueName = settings.Solution.UniqueName,
                                    MergeLabels        = true
                                };

                                info.IsCreate = false;
                            }
                            else
                            {
                                request = new CreateAttributeRequest
                                {
                                    Attribute          = amd,
                                    EntityName         = info.Entity,
                                    SolutionUniqueName = settings.Solution.UniqueName
                                };

                                info.IsCreate = true;
                            }

                            try
                            {
                                service.Execute(request);
                                info.Success    = true;
                                info.Processing = false;
                                worker.ReportProgress(percent, info);
                            }
                            catch (FaultException <OrganizationServiceFault> error)
                            {
                                // Special handle for file attribute as they are not returned by the query
                                if (info.IsCreate && error.Detail.ErrorCode == -2147192813)
                                {
                                    request = new UpdateAttributeRequest
                                    {
                                        Attribute          = amd,
                                        EntityName         = info.Entity,
                                        SolutionUniqueName = settings.Solution.UniqueName,
                                        MergeLabels        = true
                                    };

                                    info.IsCreate = false;

                                    service.Execute(request);
                                    info.Success    = true;
                                    info.Processing = false;
                                    worker.ReportProgress(percent, info);
                                }
                                else
                                {
                                    info.Success    = false;
                                    info.Processing = false;
                                    info.Message    = error.Message;
                                    worker.ReportProgress(percent, info);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            info.Success    = false;
                            info.Processing = false;
                            info.Message    = e.Message;
                            worker.ReportProgress(percent, info);
                        }
                    }
                }
        }
Пример #14
0
        /// <summary>
        /// Add output columns
        /// </summary>
        /// <param name="propertyValue"></param>
        public void AddOutputColumns(String propertyValue)
        {
            if (!String.IsNullOrEmpty(propertyValue))
            {
                if (service == null)
                {
                    AcquireConnections(null);
                }

                if (service != null)
                {
                    DataTable dt = GetData(propertyValue, true);

                    IDTSOutput100 output = ComponentMetaData.OutputCollection[0];

                    output.OutputColumnCollection.RemoveAll();
                    output.ExternalMetadataColumnCollection.RemoveAll();

                    if (dt != null)
                    {
                        //Check if there are any rows in the datatable
                        if (dt.Rows != null && dt.Rows.Count > 0)
                        {
                            DataTable schemaDT = dt.CreateDataReader().GetSchemaTable();
                            foreach (DataRow row in schemaDT.Rows)
                            {
                                IDTSOutputColumn100 outputCol = output.OutputColumnCollection.New();



                                AttributeMetadata mdta = entMetadata.Attributes.FirstOrDefault(m => m.LogicalName == row["ColumnName"].ToString());

                                bool     isLong = false;
                                DataType dType  = DataRecordTypeToBufferType((Type)row["DataType"]);
                                dType = ConvertBufferDataTypeToFitManaged(dType, ref isLong);
                                int length    = ((int)row["ColumnSize"]) == -1 ? 4000 : (int)row["ColumnSize"];
                                int precision = row["NumericPrecision"] is System.DBNull ? 0 : (short)row["NumericPrecision"];
                                int scale     = row["NumericScale"] is System.DBNull ? 0 : (short)row["NumericScale"];
                                int codePage  = schemaDT.Locale.TextInfo.ANSICodePage;

                                switch (dType)
                                {
                                //case DataType.DT_DATE:

                                //    precision = 0;
                                //    scale = 0;
                                //    break;
                                case DataType.DT_STR:
                                case DataType.DT_TEXT:
                                    MemoAttributeMetadata att = (MemoAttributeMetadata)mdta;
                                    if (att.MaxLength.HasValue)
                                    {
                                        length = (int)att.MaxLength;
                                    }
                                    else
                                    {
                                        length = 1048576;
                                    }

                                    precision = 0;
                                    scale     = 0;
                                    break;

                                case DataType.DT_CY:
                                    MoneyAttributeMetadata attMoney = (MoneyAttributeMetadata)mdta;
                                    if (attMoney.PrecisionSource == 0)     //TODO get the other types of precision sources
                                    {
                                        if (attMoney.Precision.HasValue)
                                        {
                                            scale = (int)attMoney.Precision;
                                        }
                                        else
                                        {
                                            scale = 2;
                                        }
                                    }
                                    else
                                    {
                                        scale = 4;
                                    }

                                    int precision1 = 0, precision2 = 0;

                                    if (attMoney.MaxValue.HasValue)
                                    {
                                        precision1 = attMoney.MaxValue.Value.ToString().Length;
                                    }

                                    if (attMoney.MinValue.HasValue)
                                    {
                                        precision2 = attMoney.MinValue.Value.ToString().Length;
                                    }
                                    if (precision1 > precision2)
                                    {
                                        precision = precision1;
                                    }
                                    else
                                    {
                                        precision = precision2;
                                    }

                                    length   = 0;
                                    codePage = 0;
                                    if (precision == 0)
                                    {
                                        precision = 23;
                                    }

                                    if (precision > 38)
                                    {
                                        precision = 38;
                                    }
                                    if (scale > precision)
                                    {
                                        scale = precision;
                                    }
                                    break;

                                case DataType.DT_NUMERIC:
                                case DataType.DT_DECIMAL:
                                    DecimalAttributeMetadata attDecimal = (DecimalAttributeMetadata)mdta;

                                    if (attDecimal.Precision.HasValue)
                                    {
                                        scale = (int)attDecimal.Precision;
                                    }
                                    else
                                    {
                                        scale = 2;
                                    }


                                    int precisiondec1 = 0, precisiondec2 = 0;

                                    if (attDecimal.MaxValue.HasValue)
                                    {
                                        precisiondec1 = attDecimal.MaxValue.Value.ToString().Length;
                                    }

                                    if (attDecimal.MinValue.HasValue)
                                    {
                                        precisiondec2 = attDecimal.MinValue.Value.ToString().Length;
                                    }
                                    if (precisiondec1 > precisiondec2)
                                    {
                                        precision = precisiondec1;
                                    }
                                    else
                                    {
                                        precision = precisiondec2;
                                    }

                                    length   = 0;
                                    codePage = 0;
                                    if (precision == 0)
                                    {
                                        precision = 23;
                                    }

                                    if (precision > 38)
                                    {
                                        precision = 38;
                                    }
                                    if (scale > precision)
                                    {
                                        scale = precision;
                                    }
                                    break;


                                case DataType.DT_WSTR:



                                    if (mdta.GetType() == typeof(StringAttributeMetadata))
                                    {
                                        StringAttributeMetadata attstring = (StringAttributeMetadata)mdta;
                                        if (attstring.MaxLength.HasValue)
                                        {
                                            length = (int)attstring.MaxLength;
                                        }
                                        else
                                        {
                                            length = 4000;
                                        }
                                    }
                                    else
                                    {
                                        MemoAttributeMetadata attmemo = (MemoAttributeMetadata)mdta;
                                        length = (int)attmemo.MaxLength;
                                    }



                                    precision = 0;
                                    scale     = 0;
                                    codePage  = 0;
                                    break;

                                default:
                                    length    = 0;
                                    precision = 0;
                                    scale     = 0;
                                    codePage  = 0;
                                    break;
                                }

                                outputCol.Name = row["ColumnName"].ToString();
                                outputCol.SetDataTypeProperties(dType, length, precision, scale, codePage);

                                CreateExternalMetaDataColumn(output, outputCol);
                            }
                        }
                    }
                }
            }
        }
Пример #15
0
 internal static OptionSetMetadataBase GetAttributeOptionSet(AttributeMetadata attribute)
 {
     OptionSetMetadataBase optionSet = null;
     var type = attribute.GetType();
     if (type == typeof (BooleanAttributeMetadata))
     {
         var metadata = (BooleanAttributeMetadata) attribute;
         return metadata.OptionSet;
     }
     if (type == typeof (StateAttributeMetadata))
     {
         var metadata2 = (StateAttributeMetadata) attribute;
         return metadata2.OptionSet;
     }
     if (type == typeof (PicklistAttributeMetadata))
     {
         var metadata3 = (PicklistAttributeMetadata) attribute;
         return metadata3.OptionSet;
     }
     if (type == typeof (StatusAttributeMetadata))
     {
         var metadata4 = (StatusAttributeMetadata) attribute;
         optionSet = metadata4.OptionSet;
     }
     return optionSet;
 }
Пример #16
0
 public static void SetSealedPropertyValue(this AttributeMetadata attributeMetadata, string sPropertyName, object value)
 {
     attributeMetadata.GetType().GetProperty(sPropertyName).SetValue(attributeMetadata, value, null);
 }
        private async Task <List <string> > GetDifferenceAttribute(AttributeMetadata attr1, AttributeMetadata attr2)
        {
            List <string> strDifference = new List <string>();

            {
                FormatTextTableHandler table = new FormatTextTableHandler(true);

                table.CalculateLineLengths("LanguageCode", "Value");
                table.CalculateLineLengths("LanguageCode", "Organization", "Value");

                var isDifferentDisplayName = LabelComparer.GetDifference(attr1.DisplayName, attr2.DisplayName);
                var isDifferentDescription = LabelComparer.GetDifference(attr1.Description, attr2.Description);

                isDifferentDisplayName.LabelsOnlyIn1.ForEach(i => table.CalculateLineLengths(i.Locale, i.Value));
                isDifferentDisplayName.LabelsOnlyIn2.ForEach(i => table.CalculateLineLengths(i.Locale, i.Value));
                isDifferentDisplayName.LabelDifference.ForEach(i =>
                {
                    table.CalculateLineLengths(i.Locale, _connectionName1, i.Value1);
                    table.CalculateLineLengths(i.Locale, _connectionName2, i.Value2);
                });

                isDifferentDescription.LabelsOnlyIn1.ForEach(i => table.CalculateLineLengths(i.Locale, i.Value));
                isDifferentDescription.LabelsOnlyIn2.ForEach(i => table.CalculateLineLengths(i.Locale, i.Value));
                isDifferentDescription.LabelDifference.ForEach(i =>
                {
                    table.CalculateLineLengths(i.Locale, _connectionName1, i.Value1);
                    table.CalculateLineLengths(i.Locale, _connectionName2, i.Value2);
                });

                if (!isDifferentDisplayName.IsEmpty)
                {
                    if (isDifferentDisplayName.LabelsOnlyIn1.Count > 0)
                    {
                        strDifference.Add(string.Format("DisplayNames ONLY in {0}: {1}", _connectionName1, isDifferentDisplayName.LabelsOnlyIn1.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Value"));
                        isDifferentDisplayName.LabelsOnlyIn1.ForEach(e => strDifference.Add(_tabSpacer + table.FormatLine(e.Locale, e.Value)));
                    }

                    if (isDifferentDisplayName.LabelsOnlyIn2.Count > 0)
                    {
                        strDifference.Add(string.Format("DisplayNames ONLY in {0}: {1}", _connectionName2, isDifferentDisplayName.LabelsOnlyIn2.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Value"));
                        isDifferentDisplayName.LabelsOnlyIn2.ForEach(e => strDifference.Add(_tabSpacer + table.FormatLine(e.Locale, e.Value)));
                    }

                    if (isDifferentDisplayName.LabelDifference.Count > 0)
                    {
                        strDifference.Add(string.Format("DisplayNames DIFFERENT in {0} and {1}: {2}", _connectionName1, _connectionName2, isDifferentDisplayName.LabelDifference.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Organization", "Value"));
                        isDifferentDisplayName.LabelDifference.ForEach(i =>
                        {
                            strDifference.Add(_tabSpacer + table.FormatLine(i.Locale, _connectionName1, i.Value1));
                            strDifference.Add(_tabSpacer + table.FormatLine(i.Locale, _connectionName2, i.Value2));
                        });
                    }
                }

                if (!isDifferentDescription.IsEmpty)
                {
                    if (isDifferentDescription.LabelsOnlyIn1.Count > 0)
                    {
                        strDifference.Add(string.Format("Descriptions ONLY in {0}: {1}", _connectionName1, isDifferentDescription.LabelsOnlyIn1.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Value"));
                        isDifferentDescription.LabelsOnlyIn1.ForEach(e => strDifference.Add(_tabSpacer + table.FormatLine(e.Locale, e.Value)));
                    }

                    if (isDifferentDescription.LabelsOnlyIn2.Count > 0)
                    {
                        strDifference.Add(string.Format("Descriptions ONLY in {0}: {1}", _connectionName2, isDifferentDescription.LabelsOnlyIn2.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Value"));
                        isDifferentDescription.LabelsOnlyIn2.ForEach(e => strDifference.Add(_tabSpacer + table.FormatLine(e.Locale, e.Value)));
                    }

                    if (isDifferentDescription.LabelDifference.Count > 0)
                    {
                        strDifference.Add(string.Format("Descriptions DIFFERENT in {0} and {1}: {2}", _connectionName1, _connectionName2, isDifferentDescription.LabelDifference.Count));
                        strDifference.Add(_tabSpacer + table.FormatLine("LanguageCode", "Organization", "Value"));
                        isDifferentDescription.LabelDifference.ForEach(i =>
                        {
                            strDifference.Add(_tabSpacer + table.FormatLine(i.Locale, _connectionName1, i.Value1));
                            strDifference.Add(_tabSpacer + table.FormatLine(i.Locale, _connectionName2, i.Value2));
                        });
                    }
                }
            }

            {
                var table = new FormatTextTableHandler(true);
                table.SetHeader("Property", _connectionName1, _connectionName2);

                List <string> additionalDifference = new List <string>();

                if (attr1.GetType().Name == attr2.GetType().Name)
                {
                    if (attr1 is Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata)
                    {
                        var enumAttributeMetadata1 = attr1 as Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata;
                        var enumAttributeMetadata2 = attr2 as Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata;

                        if (enumAttributeMetadata1.OptionSet != null && enumAttributeMetadata2.OptionSet != null)
                        {
                            if (!CreateFileHandler.IgnoreAttribute(enumAttributeMetadata1.EntityLogicalName, enumAttributeMetadata1.LogicalName))
                            {
                                var diffenrenceOptionSet = await _optionSetComparer.GetDifference(enumAttributeMetadata1.OptionSet, enumAttributeMetadata2.OptionSet, attr1.EntityLogicalName, attr1.LogicalName);

                                if (diffenrenceOptionSet.Count > 0)
                                {
                                    additionalDifference.Add(string.Format("Difference in OptionSet {0} and {1}"
                                                                           , enumAttributeMetadata1.OptionSet.Name + (enumAttributeMetadata1.OptionSet.IsGlobal.GetValueOrDefault() ? "(Global)" : "(Local)")
                                                                           , enumAttributeMetadata2.OptionSet.Name + (enumAttributeMetadata2.OptionSet.IsGlobal.GetValueOrDefault() ? "(Global)" : "(Local)")
                                                                           )
                                                             );
                                    diffenrenceOptionSet.ForEach(s => additionalDifference.Add(_tabSpacer + s));
                                }
                            }
                        }
                    }
                }

                if (table.Count > 0)
                {
                    strDifference.AddRange(table.GetFormatedLines(true));
                }

                if (additionalDifference.Count > 0)
                {
                    strDifference.AddRange(additionalDifference);
                }
            }

            return(strDifference);
        }
Пример #18
0
        public static Type GetAttributeSqlType(this AttributeMetadata attrMetadata)
        {
            if (attrMetadata is MultiSelectPicklistAttributeMetadata)
            {
                return(typeof(SqlString));
            }

            var typeCode = attrMetadata.AttributeType;

            if (attrMetadata is ManagedPropertyAttributeMetadata managedProp)
            {
                typeCode = managedProp.ValueAttributeTypeCode;
            }

            if (attrMetadata is BooleanAttributeMetadata || typeCode == AttributeTypeCode.Boolean)
            {
                return(typeof(SqlBoolean));
            }

            if (attrMetadata is DateTimeAttributeMetadata || typeCode == AttributeTypeCode.DateTime)
            {
                return(typeof(SqlDateTime));
            }

            if (attrMetadata is DecimalAttributeMetadata || typeCode == AttributeTypeCode.Decimal)
            {
                return(typeof(SqlDecimal));
            }

            if (attrMetadata is DoubleAttributeMetadata || typeCode == AttributeTypeCode.Double)
            {
                return(typeof(SqlDouble));
            }

            if (attrMetadata is EntityNameAttributeMetadata || typeCode == AttributeTypeCode.EntityName)
            {
                return(typeof(SqlString));
            }

            if (attrMetadata is ImageAttributeMetadata)
            {
                return(typeof(SqlBinary));
            }

            if (attrMetadata is IntegerAttributeMetadata || typeCode == AttributeTypeCode.Integer)
            {
                return(typeof(SqlInt32));
            }

            if (attrMetadata is BigIntAttributeMetadata || typeCode == AttributeTypeCode.BigInt)
            {
                return(typeof(SqlInt64));
            }

            if (typeCode == AttributeTypeCode.PartyList)
            {
                return(typeof(SqlString));
            }

            if (attrMetadata is LookupAttributeMetadata || attrMetadata.IsPrimaryId == true || typeCode == AttributeTypeCode.Lookup || typeCode == AttributeTypeCode.Customer || typeCode == AttributeTypeCode.Owner)
            {
                return(typeof(SqlEntityReference));
            }

            if (attrMetadata is MemoAttributeMetadata || typeCode == AttributeTypeCode.Memo)
            {
                return(typeof(SqlString));
            }

            if (attrMetadata is MoneyAttributeMetadata || typeCode == AttributeTypeCode.Money)
            {
                return(typeof(SqlMoney));
            }

            if (attrMetadata is PicklistAttributeMetadata || typeCode == AttributeTypeCode.Picklist)
            {
                return(typeof(SqlInt32));
            }

            if (attrMetadata is StateAttributeMetadata || typeCode == AttributeTypeCode.State)
            {
                return(typeof(SqlInt32));
            }

            if (attrMetadata is StatusAttributeMetadata || typeCode == AttributeTypeCode.Status)
            {
                return(typeof(SqlInt32));
            }

            if (attrMetadata is StringAttributeMetadata || typeCode == AttributeTypeCode.String)
            {
                return(typeof(SqlString));
            }

            if (attrMetadata is UniqueIdentifierAttributeMetadata || typeCode == AttributeTypeCode.Uniqueidentifier)
            {
                return(typeof(SqlGuid));
            }

            if (attrMetadata.AttributeTypeName == AttributeTypeDisplayName.FileType)
            {
                return(typeof(SqlGuid));
            }

            if (attrMetadata.AttributeType == AttributeTypeCode.Virtual)
            {
                return(typeof(SqlString));
            }

            throw new ApplicationException("Unknown attribute type " + attrMetadata.GetType());
        }
Пример #19
0
        private void SetEntityLogicalName(AttributeMetadata att, string entityLogicalName)
        {
            var prop = att.GetType().GetProperty("EntityLogicalName");

            prop.SetValue(att, entityLogicalName);
        }
        private void ExtractMetadata()
        {
            if (AttributeMetadata.GetType() == typeof(BigIntAttributeMetadata))
            {
                var metadata = AttributeMetadata as BigIntAttributeMetadata;

                MaxValue = metadata.MaxValue;
                MinValue = metadata.MinValue;
            }
            else if (AttributeMetadata.GetType() == typeof(DateTimeAttributeMetadata))
            {
                var metadata = AttributeMetadata as DateTimeAttributeMetadata;

                Format = metadata.Format.HasValue
                                        ? Enum.GetName(typeof(DateTimeFormat), metadata.Format.Value)
                                        : null;
            }
            else if (AttributeMetadata.GetType() == typeof(DecimalAttributeMetadata))
            {
                var metadata = AttributeMetadata as DecimalAttributeMetadata;

                MaxValue = metadata.MaxValue;
                MinValue = metadata.MinValue;
            }
            else if (AttributeMetadata.GetType() == typeof(DoubleAttributeMetadata))
            {
                var metadata = AttributeMetadata as DoubleAttributeMetadata;

                MaxValue = (decimal)metadata.MaxValue;
                MinValue = (decimal)metadata.MinValue;
            }
            else if (AttributeMetadata.GetType() == typeof(IntegerAttributeMetadata))
            {
                var metadata = AttributeMetadata as IntegerAttributeMetadata;

                Format = metadata.Format.HasValue
                                        ? Enum.GetName(typeof(IntegerFormat), metadata.Format.Value)
                                        : null;
                MaxValue = metadata.MaxValue;
                MinValue = metadata.MinValue;
            }
            else if (AttributeMetadata.GetType() == typeof(MemoAttributeMetadata))
            {
                var metadata = AttributeMetadata as MemoAttributeMetadata;

                Format = metadata.Format.HasValue
                                        ? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
                                        : null;
            }
            else if (AttributeMetadata.GetType() == typeof(MoneyAttributeMetadata))
            {
                var metadata = AttributeMetadata as MoneyAttributeMetadata;

                MaxValue = (decimal)metadata.MaxValue;
                MinValue = (decimal)metadata.MinValue;
            }
            else if (AttributeMetadata.GetType() == typeof(StringAttributeMetadata))
            {
                var metadata = AttributeMetadata as StringAttributeMetadata;

                Format = metadata.Format.HasValue
                                        ? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
                                        : null;
            }

            var localiazedDescription = AttributeMetadata.Description.LocalizedLabels.SingleOrDefault(label => label.LanguageCode == LanguageCode);

            if (localiazedDescription != null)
            {
                ToolTip = localiazedDescription.Label;
            }
        }
Пример #21
0
        /// <summary>
        /// This method validate for Format of each type.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ValidateValue(object sender, RoutedEventArgs e)
        {
            // If there is no data, then do nothing.
            if (string.IsNullOrEmpty(Text))
            {
                return;
            }

            T      value = new T();
            bool   success;
            string message = "";

            try
            {
                // Try parsing the text value to it's type.
                value   = (T)typeof(T).GetRuntimeMethod("Parse", new Type[] { typeof(string) }).Invoke(null, new object[] { this.Text });
                success = true;
            }
            catch
            {
                success = false;
                message = loader.GetString("WrongFormat");
            }

            // If parse succeeded, then check if the value is in its range.
            if (success && ((int)typeof(T).GetRuntimeMethod("CompareTo", new Type[] { typeof(T) }).Invoke(value, new object[] { MinValue }) < 0 ||
                            (int)typeof(T).GetRuntimeMethod("CompareTo", new Type[] { typeof(T) }).Invoke(value, new object[] { MaxValue }) > 0))
            {
                success = false;
                message = String.Format(loader.GetString("WrongFormatMoreLess"), MinValue.ToString(), MaxValue.ToString());
            }

            // If value is in its range, then check Precision
            if (success)
            {
                // Use Regex to check the pricision
                string pattern = @"^[0-9]+\.*[0-9]{0," + Precision + "}$";
                System.Text.RegularExpressions.Match match = Regex.Match(((TextBox)sender).Text.Trim(), pattern, RegexOptions.IgnoreCase);

                // If not match, then considered to be failed.
                if (!match.Success)
                {
                    success = false;
                    message = String.Format(loader.GetString("WrongPrecision"), Precision);
                }
            }

            // Finally set the value back to DataContext
            if (success)
            {
                // If it is Money type, then create Money instance
                if (AttributeMetadata.GetType().Equals(typeof(MoneyAttributeMetadata)))
                {
                    (this.DataContext as FormFieldData).FieldData = new Money(decimal.Parse(value.ToString()));
                }
                else
                {
                    (this.DataContext as FormFieldData).FieldData = value;
                }
            }
            else
            {
                // Restore the original value.
                if (AttributeMetadata.GetType().Equals(typeof(MoneyAttributeMetadata)))
                {
                    ((TextBox)sender).Text = ((((TextBox)sender).DataContext as FormFieldData).FieldData == null) ?
                                             "" : ((((TextBox)sender).DataContext as FormFieldData).FieldData as Money).Value.ToString();
                }
                else
                {
                    ((TextBox)sender).Text = ((((TextBox)sender).DataContext as FormFieldData).FieldData == null) ?
                                             "" : (((TextBox)sender).DataContext as FormFieldData).FieldData.ToString();
                }

                // If something happens, show the error message and back forcus to the text box.
                MessageDialog messageDialog = new MessageDialog(message);
                await messageDialog.ShowAsync();

                ((TextBox)sender).Focus(Windows.UI.Xaml.FocusState.Keyboard);
            }
        }