private static void ApplyMetadataAwareAttributes(IEnumerable<Attribute> attributes, ModelMetadata result)
 {
     foreach (IMetadataAware awareAttribute in attributes.OfType<IMetadataAware>())
     {
         awareAttribute.OnMetadataCreated(result);
     }
 }
示例#2
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var newConcepts = new List<IConceptInfo>();

            var changesOnChangesItems = existingConcepts.OfType<ChangesOnChangedItemsInfo>()
                .Where(change => change.Computation == EntityComputedFrom.Source)
                .ToArray();

            newConcepts.AddRange(changesOnChangesItems.Select(change =>
                new KeepSynchronizedOnChangedItemsInfo { EntityComputedFrom = EntityComputedFrom, UpdateOnChange = change, FilterSaveExpression = FilterSaveExpression }));

            // If the computed data source is an extension, but its value does not depend on changes in its base data structure,
            // it should still be computed every time the base data structure data is inserted.

            var dataSourceExtension = existingConcepts.OfType<DataStructureExtendsInfo>()
                .Where(ex => ex.Extension == EntityComputedFrom.Source)
                .SingleOrDefault();

            if (dataSourceExtension != null
                && dataSourceExtension.Base is IWritableOrmDataStructure
                && !changesOnChangesItems.Any(c => c.DependsOn == dataSourceExtension.Base)
                && !existingConcepts.OfType<ChangesOnBaseItemInfo>().Where(c => c.Computation == EntityComputedFrom.Source).Any())
                newConcepts.Add(new ComputeForNewBaseItemsInfo { EntityComputedFrom = EntityComputedFrom, FilterSaveExpression = FilterSaveExpression });

            return newConcepts;
        }
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            ModelMetadata metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType,
                                                         propertyName);
            RegularExpressionAttribute regularExpressionAttribute =
                attributes.OfType<RegularExpressionAttribute>().FirstOrDefault();
            RangeAttribute rangeAttribute = attributes.OfType<RangeAttribute>().FirstOrDefault();
            CurrencyAttribute currencyAttribute = attributes.OfType<CurrencyAttribute>().FirstOrDefault();
            StringLengthAttribute stringLengthAttribute = attributes.OfType<StringLengthAttribute>().FirstOrDefault();
            MaxLengthAttribute maxLengthAttribute = attributes.OfType<MaxLengthAttribute>().FirstOrDefault();

            if (regularExpressionAttribute != null)
                metadata.AdditionalValues["RegularExpression"] = regularExpressionAttribute;

            if (rangeAttribute != null)
                metadata.AdditionalValues["Range"] = rangeAttribute;

            if (currencyAttribute != null)
                metadata.AdditionalValues["Currency"] = currencyAttribute;

            if (stringLengthAttribute != null && maxLengthAttribute == null && stringLengthAttribute.MaximumLength > 0)
                metadata.AdditionalValues["MaxLength"] = stringLengthAttribute.MaximumLength;

            if (maxLengthAttribute != null)
                metadata.AdditionalValues["MaxLength"] = maxLengthAttribute.Length;

            return metadata;
        }
        private void InitializeVariables(IEnumerable<IVariable> variables)
        {
            ValidateInputProperties();

            Index1Variable = variables.OfType<IVariable>().First(v => v.Name == Index1VariableName);
            Index2Variable = variables.OfType<IVariable>().First(v => v.Name == Index2VariableName);
            XVariable = variables.OfType<IVariable<double>>().First(v => v.Name == XVariableName);
            YVariable = variables.OfType<IVariable<double>>().First(v => v.Name == YVariableName);
            ValuesVariable = variables.First(v => v.Name == ValuesVariableName);

            if(!string.IsNullOrEmpty(TimeVariableName))
            {
                TimeVariable = variables.First(v => v.Name == TimeVariableName);
            }

/*
            if(!XVariable.Arguments.SequenceEqual(YVariable.Arguments))
            {
                throw new NotSupportedException("Arguments used in X variable must be the same as in Y variable");
            }

            if (!XVariable.Arguments.SequenceEqual(ValuesVariable.Arguments))
            {
                throw new NotSupportedException("Arguments used in Values variable must be the same as in X and Y variables");
            }
*/
        }
示例#5
0
 /// <summary>
 /// Populate asynchronously.
 /// </summary>
 /// <param name="done">The callback.</param>
 public void Populate(Action<ISeries> done) {
     _series.Populate(() => {
         _children = _series.Children.Select(x => new Chapter(x) as IChapter).ToArray();
         foreach (var source in _children.OfType<Chapter>()) {
             if (source.Number != -1) continue;
             var differential = new Dictionary<double, int>();
             var origin = null as Chapter;
             foreach (var candidate in _children.OfType<Chapter>()) {
                 if (candidate != source && candidate.Number != -1 && candidate.Volume == source.Volume) {
                     if (origin != null) {
                         var difference = Math.Round(candidate.Number - origin.Number, 4);
                         if (differential.ContainsKey(difference)) {
                             differential[difference]++;
                         } else {
                             differential[difference] = 1;
                         }
                     }
                     origin = candidate;
                 }
             }
             if (differential.Count == 0) {
                 source.Number = origin == null ? 0.5 : origin.Number + origin.Number / 2;
             } else {
                 var shift = differential.OrderByDescending(x => x.Value).FirstOrDefault().Key;
                 source.Number = Math.Round(origin.Number + (shift <= 0 || shift >= 1 ? 1 : shift) / 2, 4);
             }
         }
         done(this);
     });
 }
        protected override ModelMetadata CreateMetadata(
            IEnumerable<Attribute> attributes,
            Type containerType,
            Func<object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            //attributes.OfType<DataTypeAttribute>().ToList().ForEach(m => { if (m.DataType.Equals(DataType.Date) || (m.DataType.Equals(DataType.Custom) && m.CustomDataType == "DateTimeDto")) modelMetadata.TemplateHint = "DatePicker"; });
            attributes.OfType<DataTypeAttribute>().ToList().ForEach(m =>
            {
                if (m.DataType.Equals(DataType.Custom) &&
                 (m.CustomDataType == "TimesheetDto"))
                    modelMetadata.TemplateHint = "TimesheetEditor";
            });
            attributes.OfType<DataTypeAttribute>().ToList().ForEach(m =>
            {
                if (m.DataType.Equals(DataType.Custom) &&
                 (m.CustomDataType == "TimesheetDtoList"))
                    modelMetadata.TemplateHint = "TimesheetList";
                if (m.DataType.Equals(DataType.Custom) &&
                (m.CustomDataType == "TerraGraphicDtoList"))
                    modelMetadata.TemplateHint = "TerraGraphicsList";
            });
            //attributes.OfType<DataTypeAttribute>().ToList().ForEach(m =>
            //{
            //    if (m.DataType.Equals(DataType.Custom) && (m.CustomDataType == "DropdownDto"))
            //        modelMetadata.TemplateHint = "Dropdown";
            //});
            attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));

            return modelMetadata;
        }
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
                                                        Func<object> modelAccessor, Type modelType, string propertyName) {
            ModelMetadata metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            DisplayAttribute display = attributes.OfType<DisplayAttribute>().FirstOrDefault();
            if (display != null) {
                string name = display.GetName();
                if (name != null) {
                    metadata.DisplayName = name;
                }

                metadata.Description = display.GetDescription();
                metadata.ShortDisplayName = display.GetShortName();
                metadata.Watermark = display.GetPrompt();
            }

            EditableAttribute editable = attributes.OfType<EditableAttribute>().FirstOrDefault();
            if (editable != null) {
                metadata.IsReadOnly = !editable.AllowEdit;
            }

            DisplayFormatAttribute displayFormat = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();
            if (displayFormat != null && !displayFormat.HtmlEncode && String.IsNullOrWhiteSpace(metadata.DataTypeName)) {
                metadata.DataTypeName = DataType.Html.ToString();
            }

            foreach (IMetadataAware awareAttribute in attributes.OfType<IMetadataAware>()) {
                awareAttribute.OnMetadataCreated(metadata);
            }

            return metadata;
        }
示例#8
0
 private static bool IsHiddenBy(IEntity entity, IEnumerable<IEntity> members)
 {
     var m = entity as IMethod;
     if (m != null)
         return members.OfType<IMethod>().Any(existing => SameNameAndSignature(m, existing));
     return members.OfType<IEntity>().Any(existing => existing.Name == entity.Name);
 }
示例#9
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var newConcepts = new List<IConceptInfo>();

            var cloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
            var property = (PropertyInfo)cloneMethod.Invoke(Source, null);
            property.DataStructure = Destination;
            newConcepts.Add(property);

            //var destinationEntity = Destination as EntityInfo;
            //if (destinationEntity != null)
            //{

            var required = existingConcepts.OfType<RequiredPropertyInfo>().Where(ci => ci.Property == Source)
                .Select(ci => new RequiredPropertyInfo { Property = property })
                .SingleOrDefault();
            if (required != null)
                newConcepts.Add(required);

            var destinationProperties = new HashSet<string>(
                existingConcepts.OfType<PropertyInfo>()
                    .Where(ci => ci.DataStructure == Destination)
                    .Select(ci => ci.Name));

            if (SqlIndexMultipleInfo.IsSupported(Destination))
                foreach (var sourceIndex in existingConcepts.OfType<SqlIndexMultipleInfo>().Where(ci => ci.Entity == Source.DataStructure))
                {
                    var indexProperties = sourceIndex.PropertyNames.Split(' ');
                    if (property.Name == indexProperties.FirstOrDefault()
                        && indexProperties.Skip(1).All(indexProperty => destinationProperties.Contains(indexProperty)))
                        newConcepts.Add(new SqlIndexMultipleInfo { Entity = Destination, PropertyNames = sourceIndex.PropertyNames });
                }

            return newConcepts;
        }
 private void CacheAttributes(IEnumerable<Attribute> attributes)
 {
     Display = attributes.OfType<DisplayAttribute>().FirstOrDefault();
     DisplayFormat = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();
     Editable = attributes.OfType<EditableAttribute>().FirstOrDefault();
     ReadOnly = attributes.OfType<ReadOnlyAttribute>().FirstOrDefault();
 }
示例#11
0
        protected Broker(IEnumerable <IBrokerBehavior> behaviors, ILoggerFactory loggerFactory)
        {
            _producerBehaviors = behaviors?.OfType <IProducerBehavior>() ?? Enumerable.Empty <IProducerBehavior>();
            _consumerBehaviors = behaviors?.OfType <IConsumerBehavior>() ?? Enumerable.Empty <IConsumerBehavior>();

            LoggerFactory = loggerFactory;
            _logger       = loggerFactory.CreateLogger(GetType());
        }
 public CachedDataAnnotationsMetadataAttributes(IEnumerable<Attribute> attributes)
 {
     Display = attributes.OfType<DisplayAttribute>().FirstOrDefault();
     DisplayFormat = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();
     DisplayName = attributes.OfType<DisplayNameAttribute>().FirstOrDefault();
     Editable = attributes.OfType<EditableAttribute>().FirstOrDefault();
     ReadOnly = attributes.OfType<ReadOnlyAttribute>().FirstOrDefault();
 }
		PackagingProject GetPackagingProject (IEnumerable<IWorkspaceFileObject> items)
		{
			Solution solution = items.OfType<Solution> ().FirstOrDefault ();
			if (solution != null) {
				return GetPackagingProject (solution.GetAllProjects ());
			}

			return items.OfType<PackagingProject> ().FirstOrDefault ();
		}
 public static PropertyValidator FromAttributes(IEnumerable attributes, string propertyName) {
     try {
         var validationAttributes = attributes != null ? attributes.OfType<ValidationAttribute>().ToArray() : new ValidationAttribute[0];
         var dxValidationAttributes = attributes != null ? attributes.OfType<DXValidationAttribute>().ToArray() : new DXValidationAttribute[0];
         return validationAttributes.Any() || dxValidationAttributes.Any() ? new PropertyValidator(validationAttributes, dxValidationAttributes, propertyName) : null;
     } catch(TypeAccessException) {
         return null;
     }
 }
        internal override bool IsContradicting(IEnumerable<BinaryRelationship> relationships)
        {
            // a < b and a <= b contradicts b < a
            var isLessOpContradicting = relationships
                .OfType<ComparisonRelationship>()
                .Where(c => c.ComparisonKind == ComparisonKind.Less)
                .Any(rel => AreOperandsSwapped(rel));

            if (isLessOpContradicting)
            {
                return true;
            }

            if (ComparisonKind == ComparisonKind.Less)
            {
                // a < b contradicts b <= a
                var isLessEqualOpContradicting = relationships
                    .OfType<ComparisonRelationship>()
                    .Where(c => c.ComparisonKind == ComparisonKind.LessOrEqual)
                    .Any(rel => AreOperandsSwapped(rel));

                if (isLessEqualOpContradicting)
                {
                    return true;
                }

                // a < b contradicts a == b and b == a
                var isEqualOpContradicting = relationships
                    .OfType<EqualsRelationship>()
                    .Any(rel => AreOperandsMatching(rel));

                if (isEqualOpContradicting)
                {
                    return true;
                }
            }

            if (ComparisonKind == ComparisonKind.LessOrEqual)
            {
                // a <= b contradicts a >= b && a != b
                var isLessEqualOp = relationships
                    .OfType<ComparisonRelationship>()
                    .Where(c => c.ComparisonKind == ComparisonKind.LessOrEqual)
                    .Any(rel => AreOperandsSwapped(rel));

                var isNotEqualOpContradicting = relationships
                    .OfType<ValueNotEqualsRelationship>()
                    .Any(rel => AreOperandsMatching(rel));

                if (isLessEqualOp && isNotEqualOpContradicting)
                {
                    return true;
                }
            }

            return false;
        }
		IEnumerable<DotNetProject> GetLibraryProjects (IEnumerable<IWorkspaceFileObject> items)
		{
			Solution solution = items.OfType<Solution> ().FirstOrDefault ();
			if (solution != null) {
				return GetLibraryProjects (solution.GetAllProjects ());
			}

			return items.OfType<DotNetProject> ().Where (p => !(p is PackagingProject));
		}
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var newConcepts = new List<IConceptInfo>();

            var sourceProperties = existingConcepts.OfType<PropertyInfo>().Where(p => p.DataStructure == EntityComputedFrom.Source);

            // Some computed properties might be customized, so ignore existing ones:

            var existingComputedPropertiesSource = new HashSet<string>(
                existingConcepts.OfType<PropertyComputedFromInfo>()
                    .Where(comp => comp.EntityComputedFrom == EntityComputedFrom)
                    .Select(comp => comp.Source.Name));

            var newSourceProperties = sourceProperties
                .Where(sp => !existingComputedPropertiesSource.Contains(sp.Name)).ToArray();

            // Clone source properties, including their cascade delete and extension concepts (only for automatically created propeties):

            newConcepts.AddRange(newSourceProperties.Select(sp => new PropertyFromInfo { Source = sp, Destination = EntityComputedFrom.Target }));

            AllPropertiesFromInfo.CloneExtension(EntityComputedFrom.Source, EntityComputedFrom.Target, existingConcepts, newConcepts);

            newConcepts.AddRange(existingConcepts.OfType<ReferenceCascadeDeleteInfo>()
                .Where(ci => ci.Reference.DataStructure == EntityComputedFrom.Source)
                .Where(ci => newSourceProperties.Contains(ci.Reference))
                .Select(ci => new ReferenceCascadeDeleteInfo
                {
                    Reference = new ReferencePropertyInfo
                    {
                        DataStructure = EntityComputedFrom.Target,
                        Name = ci.Reference.Name,
                        Referenced = ci.Reference.Referenced
                    }
                }));

            // Assign ComputedFrom to the target properties and extension:

            newConcepts.AddRange(newSourceProperties.Select(sp =>
                    new PropertyComputedFromInfo
                    {
                        Target = new PropertyInfo { DataStructure = EntityComputedFrom.Target, Name = sp.Name },
                        Source = sp,
                        EntityComputedFrom = EntityComputedFrom
                    }));

            IConceptInfo extensionComputedFrom = existingConcepts.OfType<DataStructureExtendsInfo>()
                .Where(extension => extension.Extension == EntityComputedFrom.Source)
                .Select(extension => new ExtensionComputedFromInfo { EntityComputedFrom = EntityComputedFrom })
                .SingleOrDefault();

            if (extensionComputedFrom != null)
                newConcepts.Add(extensionComputedFrom);

            return newConcepts;
        }
示例#18
0
        public static ModelMetadataItem CreateModelMetadataItem(ModelMetadata modelMetadata, IEnumerable<Attribute> attributes)
        {
            Throw.IfNullArgument(modelMetadata, "modelMetadata");
            var item = new ModelMetadataItem();

            item.ShowForDisplay = modelMetadata.ShowForDisplay;
            item.IsReadOnly = modelMetadata.IsReadOnly;
            item.ShowForEdit = modelMetadata.ShowForEdit && !modelMetadata.IsReadOnly;
            DisplayAttribute displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();
            RequiredAttribute requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();
            DisplayFormatAttribute displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();

            if (displayAttribute != null)
                item.DisplayName = () => displayAttribute.GetName();
            else
                item.DisplayName = () => modelMetadata.GetDisplayName();

            if (displayAttribute != null)
                item.ShortDisplayName = () => displayAttribute.GetShortName();
            else
                item.ShortDisplayName = () => modelMetadata.ShortDisplayName;

            item.TemplateName = modelMetadata.TemplateHint ?? modelMetadata.DataTypeName;

            if (displayAttribute != null)
                item.Description = () => displayAttribute.GetDescription();
            else
                item.Description = () => modelMetadata.Description;

            if (modelMetadata.NullDisplayText != null)
                item.NullDisplayText = () => modelMetadata.NullDisplayText;

            if (modelMetadata.Watermark != null)
                item.Watermark = () => modelMetadata.Watermark;

            item.HideSurroundingHtml = modelMetadata.HideSurroundingHtml;
            item.RequestValidationEnabled = modelMetadata.RequestValidationEnabled;
            item.IsRequired = modelMetadata.IsRequired;
            item.Order = modelMetadata.Order;
            item.ConvertEmptyStringToNull = modelMetadata.ConvertEmptyStringToNull;

            if (displayFormatAttribute != null)
                item.DisplayFormat = () => displayFormatAttribute.DataFormatString;
            else if (modelMetadata.DisplayFormatString != null)
                item.DisplayFormat = () => modelMetadata.DisplayFormatString;

            if (displayFormatAttribute != null && displayFormatAttribute.ApplyFormatInEditMode)
                item.EditFormat = () => modelMetadata.DisplayFormatString;
            else if (modelMetadata.EditFormatString != null)
                item.EditFormat = () => modelMetadata.EditFormatString;

            item.ApplyFormatInEditMode = item.EditFormat != null;

            return item;
        }
        public IUserGroup ResolveReference(string reference, IEnumerable<IUserGroup> userGroups)
        {
            if (!reference.StartsWith("u:"))
                return userGroups.OfType<UserGroup>().SingleOrDefault(g => g.Name == reference);

            reference = reference.SubstringAfter("u:");
            using (var md5 = MD5.Create()) {
                return userGroups.OfType<KnownUser>().SingleOrDefault(
                    u => md5.ComputeHashAsString(Encoding.UTF8.GetBytes(u.Email)) == reference
                );
            }
        }
示例#20
0
        /// <summary>
        /// Constructs a new instance of <see cref="BindingInfo"/> from the given <paramref name="attributes"/>.
        /// </summary>
        /// <param name="attributes">A collection of attributes which are used to construct <see cref="BindingInfo"/>
        /// </param>
        /// <returns>A new instance of <see cref="BindingInfo"/>.</returns>
        public static BindingInfo GetBindingInfo(IEnumerable<object> attributes)
        {
            var bindingInfo = new BindingInfo();
            var isBindingInfoPresent = false;

            // BinderModelName
            foreach (var binderModelNameAttribute in attributes.OfType<IModelNameProvider>())
            {
                isBindingInfoPresent = true;
                if (binderModelNameAttribute?.Name != null)
                {
                    bindingInfo.BinderModelName = binderModelNameAttribute.Name;
                    break;
                }
            }

            // BinderType
            foreach (var binderTypeAttribute in attributes.OfType<IBinderTypeProviderMetadata>())
            {
                isBindingInfoPresent = true;
                if (binderTypeAttribute.BinderType != null)
                {
                    bindingInfo.BinderType = binderTypeAttribute.BinderType;
                    break;
                }
            }

            // BindingSource
            foreach (var bindingSourceAttribute in attributes.OfType<IBindingSourceMetadata>())
            {
                isBindingInfoPresent = true;
                if (bindingSourceAttribute.BindingSource != null)
                {
                    bindingInfo.BindingSource = bindingSourceAttribute.BindingSource;
                    break;
                }
            }

            // PropertyFilterProvider
            var propertyFilterProviders = attributes.OfType<IPropertyFilterProvider>().ToArray();
            if (propertyFilterProviders.Length == 1)
            {
                isBindingInfoPresent = true;
                bindingInfo.PropertyFilterProvider = propertyFilterProviders[0];
            }
            else if (propertyFilterProviders.Length > 1)
            {
                isBindingInfoPresent = true;
                bindingInfo.PropertyFilterProvider = new CompositePropertyFilterProvider(propertyFilterProviders);
            }

            return isBindingInfoPresent ? bindingInfo : null;
        }
        /// <summary>Gets the metadata for the specified property.</summary>
        /// <param name="attributes"></param>
        /// <param name="containerType"></param>
        /// <param name="modelAccessor"></param>
        /// <param name="modelType"></param>
        /// <param name="propertyName"></param>
        /// <created author="laurentiu.macovei" date="Sun, 27 Mar 2011 00:07:08 GMT"/>
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var displayAttribute = attributes.OfType<global::DisplayNameAttribute>().FirstOrDefault();
            var attrs = attributes;
            var defaultValueAttribute = attributes.OfType<DefaultValueAttribute>().FirstOrDefault();
            //var eitherAttribute = attributes.OfType<EitherAttribute>().FirstOrDefault();
            var htmlEncodeAttribute = attributes.OfType<HtmlEncodeAttribute>().FirstOrDefault();
            //var pageAttribute = attributes.OfType<PageAttribute>().FirstOrDefault();
            var htmlPropertiesAttribute = attributes.OfType<HtmlPropertiesAttribute>().FirstOrDefault();

            if (displayAttribute != null)
            {
                if (!attrs.OfType<System.ComponentModel.DataAnnotations.DisplayAttribute>().Any())
                    attrs = attrs.Concat(new System.ComponentModel.DataAnnotations.DisplayAttribute
                        {
                            Description = GetString(displayAttribute.GetDescription()),
                            AutoGenerateField = displayAttribute.GetAutoGenerateField() ?? true,
                            AutoGenerateFilter = displayAttribute.GetAutoGenerateFilter() ?? true,
                            GroupName = GetString(displayAttribute.GetGroupName()),
                            Name = GetString(displayAttribute.GetName()),
                            Order = displayAttribute.GetOrder() ?? 0,
                            Prompt = GetString(displayAttribute.GetPrompt()),
                            ShortName = GetString(displayAttribute.GetShortName()),
                        }.ToEnumerable());
            }
            var modelData = base.CreateMetadata(attrs, containerType, modelAccessor, modelType, propertyName);
            if (htmlPropertiesAttribute != null)
                modelData.AdditionalValues.Add("HtmlAttributes", htmlPropertiesAttribute);

            if (htmlEncodeAttribute != null)
                modelData.AdditionalValues["HtmlEncodeAttribute"] = htmlEncodeAttribute;
            if (displayAttribute != null)
                modelData.AdditionalValues["DisplayAttribute"] = displayAttribute;
            if (defaultValueAttribute != null)
                modelData.AdditionalValues["DefaultValue"] = defaultValueAttribute.Value;
            //if (pageAttribute != null)
            //    modelData.AdditionalValues["PageAttribute"] = pageAttribute;

            //if (eitherAttribute != null)
            //{
            //    Dictionary<string, ModelMetadata> other;
            //    object otherValue;
            //    if (!modelData.AdditionalValues.TryGetValue("EitherAttribute", out otherValue) || (other = otherValue as Dictionary<string, ModelMetadata>) == null)
            //        modelData.AdditionalValues["EitherAttribute"] = other = new Dictionary<string, ModelMetadata>();
            //    var otherProperty = containerType.GetProperty(eitherAttribute.OtherProperty, Reflection.BindingFlags.Instance | Reflection.BindingFlags.Public | Reflection.BindingFlags.NonPublic);
            //    var eitherAttributes = otherProperty.GetCustomAttributes(true).OfType<Attribute>().ToArray();
            //    var otherPropertyModel = this.CreateMetadata(eitherAttributes, containerType, () => null, modelType, eitherAttribute.OtherProperty);
            //    other[eitherAttribute.OtherProperty] = otherPropertyModel;
            //    if (eitherAttribute.OtherPropertyName == null)
            //        eitherAttribute.OtherPropertyName = otherPropertyModel.GetDisplayName();
            //}
            return modelData;
        }
        protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            if (attributes.OfType<MetadataLocationAttribute>().Any())
            {
                var metadataType = attributes.OfType<MetadataLocationAttribute>().First().Type;

                if (attributes != null)
                    return base.CreateMetadata(attributes, metadataType, modelAccessor, modelType, propertyName);
            }

            return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        }
示例#23
0
 public override void Update(IEnumerable<Entity> entities)
 {
     if (!IsAvailable)
         return;
     UpdateGamePadStates();
     foreach (var button in entities.OfType<GamePadButtonTrigger>())
         if (GetButtonState(button.Button) == button.State)
             button.Invoke();
     foreach (var stick in entities.OfType<GamePadAnalogTrigger>())
         if (IsGamePadStickTriggered(stick))
             stick.Invoke();
 }
示例#24
0
 public void TransformMetadata(System.Web.Mvc.ModelMetadata metadata, IEnumerable<Attribute> attributes)
 {
     if (attributes.OfType<RenderModeAttribute>().Any())
     {
         switch (attributes.OfType<RenderModeAttribute>().First().RenderMode)
         {
             case RenderMode.None:
                 metadata.ShowForDisplay = false;
                 metadata.ShowForEdit = false;
                 break;
         }
     }
 }
    public override ScaffoldedMigration Generate(string migrationId, IEnumerable<MigrationOperation> operations, string sourceModel, string targetModel, string @namespace, string className)
    {
      _foreignKeys = (from tbl in operations.OfType<CreateTableOperation>()
                      from fk in operations.OfType<AddForeignKeyOperation>()
                      where tbl.Name.Equals(fk.DependentTable, StringComparison.InvariantCultureIgnoreCase)
                      select new KeyValuePair<CreateTableOperation, AddForeignKeyOperation>(tbl, fk)).ToList();

      _tableIndexes = (from tbl in operations.OfType<CreateTableOperation>()
                       from idx in operations.OfType<CreateIndexOperation>()
                       where tbl.Name.Equals(idx.Table, StringComparison.InvariantCultureIgnoreCase)
                       select new KeyValuePair<CreateTableOperation, CreateIndexOperation>(tbl, idx)).ToList();

      return base.Generate(migrationId, operations, sourceModel, targetModel, @namespace, className);
    }
        /// <summary>
        /// For each property that does not have it's LegacyProperty defined, this function creates a default LegacyProperty
        /// assuming that corresponding legacy tables's column has the same name as the property.
        /// </summary>
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var properties = existingConcepts.OfType<PropertyInfo>().Where(prop => prop.DataStructure == this).ToArray();
            var propertiesWithLegacyProperty = existingConcepts.OfType<LegacyPropertyInfo>().Where(lp => lp.Property.DataStructure == this).Select(lp => lp.Property).ToArray();

            var legacyIndex = new HashSet<PropertyInfo>(propertiesWithLegacyProperty);
            var propertiesWithoutLegacyPropertyInfo = properties.Where(p => !legacyIndex.Contains(p)).ToArray();

            var errorReference = propertiesWithoutLegacyPropertyInfo.OfType<ReferencePropertyInfo>().FirstOrDefault();
            if (errorReference != null)
                throw new DslSyntaxException("Legacy reference property '" + errorReference.GetKeyProperties() +"' must have explicitly defined LegacyProperty with source columns (comma separated), referenced table and referenced columns.");

            return propertiesWithoutLegacyPropertyInfo.Select(p => new LegacyPropertySimpleInfo { Property = p, Column = p.Name }).ToList();
        }
 public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
 {
     return existingConcepts.OfType<PropertyInfo>()
         .Where(p => p.DataStructure == EntityHistory.Entity)
         .Select(p => new EntityHistoryPropertyInfo { Property = p })
         .ToList();
 }
示例#28
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var extendsConcept = existingConcepts.OfType<DataStructureExtendsInfo>().Where(extends => extends.Extension == Computation).FirstOrDefault();

            if (extendsConcept == null)
                return null;
            // TODO: Implement and use gobal ConceptInfoMetadata to check if this concept is handled or not after evaluating all other concepts.
                //throw new DslSyntaxException("ChangesOnBaseItem is used on '" + Computation.GetUserDescription()
                //    + "' which does not extend another base data structure. Consider adding 'Extends' concept.");

            if (!typeof(EntityInfo).IsAssignableFrom(extendsConcept.Base.GetType()))
                throw new DslSyntaxException("ChangesOnBaseItem is used on '" + Computation.GetUserDescription()
                + "', but the base data structure '" + extendsConcept.Base.GetUserDescription()
                + "' is not Entity. Currently only entities are supported in automatic handling of dependencies.");

            return new[]
                       {
                           new ChangesOnChangedItemsInfo
                               {
                                   Computation = Computation,
                                   DependsOn = (EntityInfo)extendsConcept.Base,
                                   FilterType = "Guid[]",
                                   FilterFormula = "changedItems => changedItems.Select(item => item.ID).ToArray()"
                               }
                       };
        }
 public void AddEqualToDataAttr(IEnumerable<ValidationAttribute> propertyValidators, HtmlTag htmlTag, RequestData request)
 {
     var equal = propertyValidators.OfType<CompareAttribute>().FirstOrDefault();
     if (equal != null)
     {
         var formatErrorMessage = equal.FormatErrorMessage(request.Accessor.Name);
         if (_msUnobtrusive)
         {
             htmlTag.Data("val", true);
             htmlTag.Data("val-equalto", formatErrorMessage);
             if (request.Accessor.PropertyNames.Length > 1)
             {
                 htmlTag.Data("val-equalto-other", request.Id.Replace("_" + request.Accessor.Name, "") + "_" + equal.OtherProperty);
             }
             else
             {
                 htmlTag.Data("val-equalto-other", "*." + equal.OtherProperty);
             }
         }
         else
         {
             htmlTag.Data("msg-equalto", formatErrorMessage);
             if (request.Accessor.PropertyNames.Length > 1)
                 htmlTag.Data("rule-equalto", "#" + request.Id.Replace("_" + request.Accessor.Name, "") + "_" + equal.OtherProperty);
             else
                 htmlTag.Data("rule-equalto", "#" + equal.OtherProperty);
         }
     }
 }
示例#30
0
        static object GetMaxId(IEnumerable <dynamic> data,
                               string columnName)
        {
            var kvps = data?.OfType <IDictionary <string, object> >();

            return(kvps.Max(e => e[columnName]));
        }
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {
            _adaptersLock.EnterReadLock();

            try {
                List<ModelValidator> results = new List<ModelValidator>();

                if (AddImplicitRequiredAttributeForValueTypes &&
                        metadata.IsRequired &&
                        !attributes.Any(a => a is RequiredAttribute)) {
                    attributes = attributes.Concat(new[] { new RequiredAttribute() });
                }

                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
                    DataAnnotationsModelValidationFactory factory;
                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
                        factory = DefaultAttributeFactory;
                    }
                    results.Add(factory(metadata, context, attribute));
                }

                return results;
            }
            finally {
                _adaptersLock.ExitReadLock();
            }
        }
示例#32
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var extendsConcept = existingConcepts.OfType<DataStructureExtendsInfo>().Where(extends => extends.Extension == Computation).FirstOrDefault();
            if (extendsConcept == null)
                throw new DslSyntaxException("ChangesOnLinkedItems is used on '" + Computation.GetUserDescription()
                    + "' which does not extend another base data structure. Consider adding 'Extends' concept.");

            if (LinkedItemsReference.Referenced != extendsConcept.Base)
                throw new DslSyntaxException("ChangesOnLinkedItems used on '" + Computation.GetUserDescription()
                    + "' declares reference '" + LinkedItemsReference.GetKeyProperties()
                    + "'. The reference should point to computation's base data structure '" + extendsConcept.Base.GetUserDescription()
                    + "'. Instead it points to '" + LinkedItemsReference.Referenced.GetUserDescription() + "'.");

            if (!typeof(EntityInfo).IsAssignableFrom(LinkedItemsReference.DataStructure.GetType()))
                throw new DslSyntaxException("ChangesOnLinkedItems is used on '" + Computation.GetUserDescription()
                + "', but the data structure it depends on '" + LinkedItemsReference.DataStructure.GetUserDescription()
                + "' is not Entity. Currently only entities are supported in automatic handling of dependencies.");

            return new[]
                {
                    new ChangesOnChangedItemsInfo
                        {
                            Computation = Computation,
                            DependsOn = (EntityInfo)LinkedItemsReference.DataStructure,
                            FilterType = "Guid[]",
                            FilterFormula = @"changedItems => changedItems.Where(item => item." + LinkedItemsReference.Name + " != null).Select(item => item." + LinkedItemsReference.Name + ".ID).Distinct().ToArray()"
                        }
                };
        }
        /// <summary>Checks whether a type is nullable.</summary>
        /// <param name="type">The type.</param>
        /// <param name="parentAttributes">The parent attributes (e.g. property or parameter attributes).</param>
        /// <param name="defaultReferenceTypeNullHandling">The default reference type null handling used when no nullability information is available.</param>
        /// <returns>true if the type can be null.</returns>
        public virtual bool IsNullable(Type type, IEnumerable <Attribute> parentAttributes, ReferenceTypeNullHandling defaultReferenceTypeNullHandling)
        {
            var jsonPropertyAttribute = parentAttributes?.OfType <JsonPropertyAttribute>().SingleOrDefault();

            if (jsonPropertyAttribute != null && jsonPropertyAttribute.Required == Required.DisallowNull)
            {
                return(false);
            }

            if (parentAttributes.TryGetIfAssignableTo("NotNullAttribute", TypeNameStyle.Name) != null)
            {
                return(false);
            }

            if (parentAttributes.TryGetIfAssignableTo("CanBeNullAttribute", TypeNameStyle.Name) != null)
            {
                return(true);
            }

            if (type.Name == "Nullable`1")
            {
                return(true);
            }

            var isValueType = type != typeof(string) && type.GetTypeInfo().IsValueType;

            return(isValueType == false && defaultReferenceTypeNullHandling == ReferenceTypeNullHandling.Null);
        }
示例#34
0
        public static void AddRange(this IList <SelectListItem> listItems, IEnumerable items, IEnumerable selectedItems)
        {
            var selected = selectedItems?.OfType <object>();

            foreach (var item in items)
            {
                if (item == null)
                {
                    continue;
                }
                else if (item is IEntity)
                {
                    listItems.Add((IEntity)item);
                }
                else if (item is SelectListItem)
                {
                    listItems.Add((SelectListItem)item);
                }
                else
                {
                    listItems.Add(new SelectListItem {
                        Text = item.ToStringOrEmpty(), Value = item.ToStringOrEmpty()
                    });
                }

                if (selected != null && selected.Contains(item))
                {
                    listItems[listItems.Count - 1].Selected = true;
                }
            }
        }
示例#35
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="message">Required.</param>
 /// <param name="innerExceptions">Optional</param>
 public AggregateComposerException(string message, IEnumerable <ComposerException> innerExceptions)
     : base(
         message,
         innerExceptions?.OfType <Exception>()
         ?? new Exception[0])
 {
 }
示例#36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeData"/> class.
        /// </summary>
        /// <param name="declaration"><see cref="BaseTypeDeclarationSyntax"/> this <see cref="TypeData"/> represents.</param>
        /// <param name="compilation">Parent <see cref="ICompilationData"/> of this <see cref="TypeData"/>.</param>
        /// <param name="symbol"><see cref="INamedTypeSymbol"/> this <see cref="TypeData"/> represents.</param>
        /// <param name="semanticModel"><see cref="SemanticModel"/> of the <paramref name="declaration"/>.</param>
        /// <param name="partialDeclarations">A collection of <see cref="TypeDeclarationSyntax"/> that represent the partial declarations of the target <paramref name="symbol"/>.</param>
        /// <param name="modifiers">A collection of all modifiers applied to the <paramref name="symbol"/>.</param>
        /// <param name="containingTypes">A collection of <see cref="ITypeData"/>s the <paramref name="symbol"/> is contained within.</param>
        /// <param name="containingNamespaces">A collection of <see cref="INamespaceSymbol"/>s the <paramref name="symbol"/> is contained within.</param>
        /// <param name="attributes">A collection of <see cref="AttributeData"/>s representing the <paramref name="symbol"/> attributes.</param>
        protected internal TypeData(
            BaseTypeDeclarationSyntax declaration,
            ICompilationData compilation,
            INamedTypeSymbol symbol,
            SemanticModel semanticModel,
            IEnumerable <BaseTypeDeclarationSyntax>?partialDeclarations = null,
            IEnumerable <SyntaxToken>?modifiers                 = null,
            IEnumerable <ITypeData>?containingTypes             = null,
            IEnumerable <INamespaceSymbol>?containingNamespaces = null,
            IEnumerable <AttributeData>?attributes              = null
            ) : base(
                declaration,
                compilation,
                symbol,
                semanticModel,
                containingTypes,
                containingNamespaces,
                attributes
                )
        {
            _partialDeclarations = partialDeclarations?.OfType <TypeDeclarationSyntax>().ToArray();

            if (modifiers is not null)
            {
                _modifiers = modifiers.ToArray();
            }
        }
示例#37
0
        /// <summary>
        /// 現在のパラメータ一覧を取得する。
        /// </summary>
        /// <param name="targetParameterIds">
        /// 取得対象のパラメータID列挙。 null ならば存在する全パラメータを対象とする。
        /// </param>
        /// <returns>
        /// パラメータIDとその値のディクショナリ。取得できなかった場合は null 。
        /// </returns>
        Result <Dictionary <object, decimal> > ITalker.GetParameters(
            IEnumerable targetParameterIds)
        {
            var result = this.GetParameters(targetParameterIds?.OfType <TParameterId>());

            return(
                result.Value?.ToDictionary(kv => (object)kv.Key, kv => kv.Value),
                result.Message);
        }
        public CloudFoundrySecurityMiddleware(RequestDelegate next, ICloudFoundryOptions options, IEnumerable <IManagementOptions> mgmtOptions, ILogger <CloudFoundrySecurityMiddleware> logger = null)
        {
            _next        = next;
            _logger      = logger;
            _options     = options;
            _mgmtOptions = mgmtOptions?.OfType <CloudFoundryManagementOptions>().SingleOrDefault();

            _base = new SecurityBase(options, _mgmtOptions, logger);
        }
        private static bool IsTypeInQueryParameters(IEnumerable <IQueryParameter> parameters)
        {
            var typeFilterExists = parameters?
                                   .OfType <EqualsFilter>()
                                   .Any(filter => filter
                                        .ElementOrAttributePath
                                        .Equals("system.type", StringComparison.Ordinal));

            return(typeFilterExists ?? false);
        }
示例#40
0
        /// <summary>
        /// Gets the enumerable as list.
        /// If enumerable is an ICollectionView then it returns the SourceCollection as list.
        /// </summary>
        /// <param name="enumerable">The enumerable.</param>
        /// <returns>Returns a list.</returns>
        public static IList TryGetList(this IEnumerable enumerable)
        {
            if (enumerable is ICollectionView view)
            {
                return(view.SourceCollection as IList);
            }
            var list = enumerable as IList;

            return(list ?? enumerable?.OfType <object>().ToList());
        }
示例#41
0
        public IRenderTarget CreateRenderTarget(IEnumerable <object> surfaces)
        {
            var fb = surfaces?.OfType <IFramebufferPlatformSurface>().FirstOrDefault();

            if (fb == null)
            {
                throw new ArgumentException("Avalonia.Skia.Android is only capable of drawing on framebuffer");
            }
            return(new FramebufferRenderTarget(fb));
        }
        public virtual IRenderTarget CreateRenderTarget(IEnumerable <object> surfaces)
        {
            var fb = surfaces?.OfType <IFramebufferPlatformSurface>().FirstOrDefault();

            if (fb == null)
            {
                throw new Exception("Skia backend currently only supports framebuffer render target");
            }
            return(new FramebufferRenderTarget(fb));
        }
        public static async Task <Stream> LoadStreamAsync(string path, IEnumerable <IImageConstraint> constraints = null)
        {
            var sizeConstraint = constraints?.OfType <SizeConstraint>().FirstOrDefault();

            if (".xps".Equals(Path.GetExtension(path), StringComparison.InvariantCultureIgnoreCase))
            {
                return(GetXpsStream(path, CalculateRenderSize(sizeConstraint)));
            }

            return(await GetMagickStreamAsync(path, CalculateRenderSize(sizeConstraint)));
        }
示例#44
0
 internal DataContext(IEnumerable <IAuthor> authors, IEnumerable <IBook> books) : this()
 {
     foreach (Author author in authors?.OfType <Author>() ?? Enumerable.Empty <Author>())
     {
         _authors.Add(author);
     }
     foreach (Book book in books?.OfType <Book>() ?? Enumerable.Empty <Book>())
     {
         _books.Add(book);
     }
 }
示例#45
0
        public IRenderTarget CreateRenderTarget(IEnumerable <object> surfaces)
        {
            var accessor = surfaces?.OfType <Func <Gdk.Drawable> >().FirstOrDefault();

            if (accessor != null)
            {
                return(new RenderTarget(accessor));
            }

            throw new NotSupportedException(string.Format(
                                                "Don't know how to create a Cairo renderer from any of the provided surfaces."));
        }
示例#46
0
        public IRenderTarget CreateRenderTarget(IEnumerable <object> surfaces)
        {
            var nativeWindow = surfaces?.OfType <IPlatformHandle>().FirstOrDefault();

            if (nativeWindow != null)
            {
                if (nativeWindow.HandleDescriptor != "HWND")
                {
                    throw new NotSupportedException("Don't know how to create a Direct2D1 renderer from " + nativeWindow.HandleDescriptor);
                }
                return(new HwndRenderTarget(nativeWindow));
            }
            throw new NotSupportedException("Don't know how to create a Direct2D1 renderer from any of provided surfaces");
        }
示例#47
0
        /// <summary>
        /// A generic method that can find types of SyntaxNode, used to reduce the amount
        /// of boilerplate code in the rules.
        /// </summary>
        /// <typeparam name="T">
        /// The type of SyntaxNode to find.
        /// </typeparam>
        /// <param name="methodSyntax">
        /// A method declaration syntax for which we want to find SyntaxNode of type T.
        /// </param>
        /// <returns>
        /// A list of violations found for the type T.
        /// </returns>
        private List <T> GetListOfSyntaxNode <T>(MethodDeclarationSyntax methodSyntax)
        {
            Contract.Requires(methodSyntax != null);
            Contract.Ensures(Contract.Result <List <T> >() != null);

            IEnumerable <SyntaxNode> descendantNodes = methodSyntax.DescendantNodes();

            // The null checks are needed to satisfy Code Contracts. Descendant nodes
            // will never be null for methodSyntax, since a MethodDeclarationSyntax
            // instance will always have descendants if it itself is not null.
            List <T> returnList = descendantNodes?.OfType <T>().ToList() ?? new List <T>();

            return(returnList);
        }
示例#48
0
        public static void WriteOptions(this XmlWriter writer, IEnumerable <ITokenOption> options, string elementName)
        {
            var tagOptions = options?.OfType <PersistantTokenOption>().ToArray();

            if (tagOptions != null && tagOptions.Length > 0)
            {
                writer.WriteStartElement(elementName);

                foreach (var tokenOption in tagOptions)
                {
                    writer.WriteXml(tokenOption);
                }

                writer.WriteEndElement();                //elementName
            }
        }
示例#49
0
        public CloudFoundryEndpoint(ICloudFoundryOptions options, IEnumerable <IManagementOptions> mgmtOptions, ILogger <CloudFoundryEndpoint> logger = null)
            : base(options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _mgmtOption = mgmtOptions?.OfType <CloudFoundryManagementOptions>().SingleOrDefault();

            if (_mgmtOption == null)
            {
                throw new ArgumentNullException(nameof(mgmtOptions));
            }

            _logger = logger;
        }
示例#50
0
        public virtual async Task <IReadOnlyCollection <T> > Get()
        {
            var         item  = new T();
            IEnumerable items = null;

            switch (item)
            {
            case DAContractModels.Location _:
                await _context.Locations.LoadAsync().ConfigureAwait(false);

                items = _mapper.Map <IEnumerable <DAContractModels.Location> >(
                    await _context.Locations.ToListAsync().ConfigureAwait(false));
                break;

            case DAContractModels.Service _:
                await _context.Services.LoadAsync().ConfigureAwait(false);

                items = _mapper.Map <IEnumerable <DAContractModels.Service> >(
                    await _context.Services.ToListAsync().ConfigureAwait(false));
                break;

            case DAContractModels.Metric _:
                await _context.Metrics.LoadAsync().ConfigureAwait(false);

                items = _mapper.Map <IEnumerable <DAContractModels.Metric> >(
                    await _context.Metrics.ToListAsync().ConfigureAwait(false));
                break;

            case DAContractModels.Formula _:
                await _context.Formulas.LoadAsync().ConfigureAwait(false);

                items = _mapper.Map <IEnumerable <DAContractModels.Formula> >(
                    await _context.Formulas.ToListAsync().ConfigureAwait(false));
                break;

            case DAContractModels.Statistic _:
                await _context.Statistics.LoadAsync().ConfigureAwait(false);

                items = _mapper.Map <IEnumerable <DAContractModels.Statistic> >(
                    await _context.Statistics.ToListAsync().ConfigureAwait(false));
                break;
            }

            return(items?.OfType <T>().ToArray());
        }
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
        {
            _ = feature ?? throw new ArgumentNullException(nameof(feature));

            var appParts = parts?.OfType <IApplicationPartTypeProvider>() ?? throw new ArgumentNullException(nameof(parts));

            // inspect all but those parts coming from CoreXF.Framework (fails with an ReflectionTypeLoadException)
            foreach (var part in appParts.Where(x => (x as ApplicationPart)?.Name != Assembly.GetAssembly(typeof(Registry.ExtensionsLoader)).GetName().Name))
            {
                foreach (var type in part.Types.Where(t => ExtensionsHelper.IsController(t) && feature.Controllers.Contains(t) == false))
                {
                    if (ExtensionsHelper.IsExtension(type.Assembly, this.logger))
                    {
                        // should be one or more, First/OrDefault() doesn't work instead
                        var extensionAttribute = type.GetCustomAttributes().SingleOrDefault(a => a is ExportAttribute);
                        if (extensionAttribute != null)
                        {
                            var area = type.Assembly.GetName().Name;
                            if (this.Areas.ContainsKey(area) == false)
                            {
                                this.Areas.Add(area, new List <TypeInfo>());
                            }

                            this.Areas[area].Add(type);

                            feature.Controllers.Add(type);

                            this.registry.GetExtension(((AssemblyPart)part).Assembly).AddController(type);

                            this.logger.LogInformation($"Controller '{type.AsType().FullName}' has been registered and is accessible.");
                        }
                        else
                        {
                            this.logger.LogWarning($"Controller '{type.AsType().FullName}' is inaccessible. Decorate it with '{nameof(ExportAttribute)}' if you want to access it.");
                        }
                    }
                    else
                    {
                        feature.Controllers.Add(type);
                    }
                }
            }
        }
示例#52
0
        public static int GetTelecom(IEnumerable <IIfcAddress> addresses, out string email, out string phone)
        {
            email = null;
            phone = null;
            var filledCount = 0;
            var telecoms    = addresses?.OfType <IIfcTelecomAddress>();

            if (telecoms == null)
            {
                return(0);
            }
            foreach (var telecom in telecoms)
            {
                if (email == null && telecom.ElectronicMailAddresses != null)
                {
                    var ml = telecom.ElectronicMailAddresses
                             .FirstOrDefault(t => t != null && !string.IsNullOrWhiteSpace(t.ToString())).ToString();
                    if (!string.IsNullOrWhiteSpace(ml))
                    {
                        email = ml;
                        filledCount++;
                    }
                }

                if (phone == null && telecom.TelephoneNumbers != null)
                {
                    var phoneNum = telecom.TelephoneNumbers
                                   .FirstOrDefault(t => t != null && !string.IsNullOrWhiteSpace(t.ToString()))
                                   .ToString();
                    if (!string.IsNullOrWhiteSpace(phoneNum))
                    {
                        phone = phoneNum;
                        filledCount++;
                    }
                }
                // exit enum if no more fields needed.
                if (filledCount == 2)
                {
                    return(filledCount);
                }
            }
            return(filledCount);
        }
示例#53
0
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, TagHelperFeature feature)
        {
            if (feature == null)
            {
                throw new ArgumentNullException(nameof(feature));
            }

            var appParts = parts?.OfType <IApplicationPartTypeProvider>() ?? throw new ArgumentNullException(nameof(parts));

            foreach (var part in appParts)
            {
                var types = part.Types.Where(t => /*ExtensionsHelper.IsController(t) && */ feature.TagHelpers.Contains(t) == false);
                foreach (var type in types)
                {
                    if (ExtensionsHelper.IsExtension(type.Assembly, this.logger))
                    {
                        // should be one or more, First/OrDefault() doesn't work instead
                        var extensionAttribute = type.GetCustomAttributes().SingleOrDefault(a => a is ExportAttribute);
                        if (extensionAttribute != null)
                        {
                            var area = type.Assembly.GetName().Name;
                            if (this.Areas.ContainsKey(area) == false)
                            {
                                this.Areas.Add(area, new List <TypeInfo>());
                            }

                            this.Areas[area].Add(type);
                            feature.TagHelpers.Add(type);
                            this.logger.LogInformation($"Tag Helper '{type.AsType().FullName}' has been registered and is accessible.");
                        }
                        else
                        {
                            this.logger.LogWarning($"Tag Helper '{type.AsType().FullName}' is inaccessible. Decorate it with '{nameof(ExportAttribute)}' if you want to access it.");
                        }
                    }
                    else
                    {
                        feature.TagHelpers.Add(type);
                    }
                }
            }
        }
示例#54
0
        /// <summary>
        /// ソリューションにあるアクティブなKuin Projectのプロパティを取得する。
        /// WARN: 開いているドキュメントの所属プロジェクトとか、スタートアッププロジェクトは参照していない
        /// 複数のKuin Projectがあるslnだとうまく動かないような。
        /// </summary>
        /// <returns></returns>
        protected KuinProjectNodeProperties GetKuinProjectProperties()
        {
            var sln = (IVsSolution)_provider.GetService(typeof(SVsSolution));

            try
            {
                IEnumerable projects =
                    ((EnvDTE.DTE)_provider.GetService(typeof(EnvDTE.DTE)))
                    .ActiveSolutionProjects as IEnumerable;

                var project = projects?.OfType <EnvDTE.Project>()
                              .Select(p => p.GetCommonProject() as KuinProjectNode)
                              .FirstOrDefault(p => p != null);

                return(project?.NodeProperties as KuinProjectNodeProperties);
            }
            catch (COMException)
            {
                return(null);
            }
        }
        public async Task <Either <Error, IParser <T> > > GetParserAsync <T>(string key) where T : IStandardModel
        {
            return(await ShouldNotNullOrEmpty(key)
                   .MatchAsync(async k =>
            {
                // Get custom parser
                var parser = _customParsers?.OfType <ICustomParser <T> >().FirstOrDefault(p => p.Key == k);
                if (parser != null)
                {
                    return Right <Error, IParser <T> >(parser);
                }
                else
                {
                    var inputType = MapInputType <T>();
                    // Get beanio parser
                    var inputMapping = (await _inputMappingRepository
                                        .ListAsync(q => q.Where(e => e.Key == k && e.InputType == inputType)))
                                       .FirstOrDefault();

                    if (inputMapping == null)
                    {
                        return Left <Error, IParser <T> >($"No mapping by key: {k} & type: {inputType.ToString()}");
                    }
                    else if (inputMapping.XmlConfiguration.IsNullOrEmpty())
                    {
                        return Left <Error, IParser <T> >(
                            $"No xml configuration by key: {k} & type: {inputType.ToString()}");
                    }

                    var mapperSourceText = await _mstEntityRepository.GetAsync(inputMapping.MapperSourceTextId);
                    return Right <Error, IParser <T> >(new BeanParser <T>(
                                                           inputMapping.XmlConfiguration,
                                                           _fileLoaderServices.SingleOrDefault(fl => fl.Type == inputMapping.StreamType),
                                                           _beanMapperFactory.GetBeanMapper(inputMapping.Mapper),
                                                           mapperSourceText));
                }
            }, errors => errors.Join()));
        }
示例#56
0
 public CloudFoundryEndpointMiddleware(RequestDelegate next, CloudFoundryEndpoint endpoint, IEnumerable <IManagementOptions> mgmtOptions, ILogger <CloudFoundryEndpointMiddleware> logger = null)
     : base(endpoint, mgmtOptions?.OfType <CloudFoundryManagementOptions>(), logger: logger)
 {
     _next    = next;
     _options = endpoint.Options as ICloudFoundryOptions;
 }
示例#57
0
 private static TabControl GetTabControl(IEnumerable controls)
 {
     return(controls?.OfType <TabControl>()
            .Select(c => c)
            .FirstOrDefault());
 }
示例#58
0
 protected virtual IXAxis GetXAxis(IEnumerable <IAxis> axises)
 => axises?.OfType <IXAxis>().FirstOrDefault();
示例#59
0
 public CloudFoundryHandler(CloudFoundryEndpoint endpoint, IEnumerable <ISecurityService> securityServices, IEnumerable <IManagementOptions> mgmtOptions, ILogger <CloudFoundryHandler> logger = null)
     : base(endpoint, securityServices, mgmtOptions?.OfType <CloudFoundryManagementOptions>(), null, true, logger)
 {
 }
示例#60
0
 static public IEnumerable <KeyValuePair <DroneViewEntryGroup, IDroneViewEntryItem[]> > ListDroneViewEntryGrouped(
     this IEnumerable <IListEntry> list) =>
 list
 ?.OfType <DroneViewEntry>()
 ?.SequenceGroupByType <DroneViewEntry, DroneViewEntryGroup>()
 ?.Select(group => new KeyValuePair <DroneViewEntryGroup, IDroneViewEntryItem[]>(group.Key, group.Value?.OfType <DroneViewEntryItem>()?.ToArray()));