Ejemplo n.º 1
0
		public TypeMetric(
			bool isAbstract,
			TypeMetricKind kind,
			AccessModifierKind accessModifier,
			IEnumerable<IMemberMetric> memberMetrics,
			int linesOfCode,
			int cyclomaticComplexity,
			double maintainabilityIndex,
			int depthOfInheritance,
			IEnumerable<ITypeCoupling> classCouplings,
			string name,
			int afferentCoupling,
			int efferentCoupling,
			double instability,
			ITypeDocumentation documentation)
		{
			IsAbstract = isAbstract;
			Kind = kind;
			AccessModifier = accessModifier;
			MemberMetrics = memberMetrics;
			LinesOfCode = linesOfCode;
			CyclomaticComplexity = cyclomaticComplexity;
			MaintainabilityIndex = maintainabilityIndex;
			DepthOfInheritance = depthOfInheritance;
			ClassCouplings = classCouplings.AsArray();
			Name = name;
			AfferentCoupling = afferentCoupling;
			EfferentCoupling = efferentCoupling;
			Instability = instability;
			Documentation = documentation;
		}
		public INamespaceMetric CalculateFrom(NamespaceDeclarationSyntaxInfo namespaceNode, IEnumerable<ITypeMetric> metrics)
		{
			const string DocumentationTypeName = "NamespaceDoc";
			var typeMetrics = metrics.AsArray();
			var documentationType = typeMetrics.FirstOrDefault(x => x.Name == DocumentationTypeName);
			IDocumentation documentation = null;
			if (documentationType != null)
			{
				documentation = documentationType.Documentation;
				typeMetrics = typeMetrics.Where(x => x.Name != DocumentationTypeName).AsArray();
			}

			var linesOfCode = typeMetrics.Sum(x => x.LinesOfCode);
			var source = typeMetrics.SelectMany(x => x.ClassCouplings)
						  .GroupBy(x => x.ToString())
						  .Select(x => new TypeCoupling(x.First().TypeName, x.First().Namespace, x.First().Assembly, x.SelectMany(y => y.UsedMethods), x.SelectMany(y => y.UsedProperties), x.SelectMany(y => y.UsedEvents)))
						  .Where(x => x.Namespace != namespaceNode.Name)
						  .OrderBy(x => x.Assembly + x.Namespace + x.TypeName)
						  .AsArray();
			var maintainabilitySource = typeMetrics.Select(x => new Tuple<int, double>(x.LinesOfCode, x.MaintainabilityIndex)).AsArray();
			var maintainabilityIndex = linesOfCode > 0 && maintainabilitySource.Any() ? maintainabilitySource.Sum(x => x.Item1 * x.Item2) / linesOfCode : 100.0;
			var cyclomaticComplexity = typeMetrics.Sum(x => x.CyclomaticComplexity);
			var depthOfInheritance = typeMetrics.Any() ? typeMetrics.Max(x => x.DepthOfInheritance) : 0;
			return new NamespaceMetric(
				maintainabilityIndex,
				cyclomaticComplexity,
				linesOfCode,
				source,
				depthOfInheritance,
				namespaceNode.Name,
				typeMetrics,
				documentation);
		}
Ejemplo n.º 3
0
		public MemberMetric(
			string codeFile,
			AccessModifierKind accessModifier,
			IHalsteadMetrics halstead,
			int lineNumber,
			int linesOfCode,
			double maintainabilityIndex,
			int cyclomaticComplexity,
			string name,
			IEnumerable<ITypeCoupling> classCouplings,
			int numberOfParameters,
			int numberOfLocalVariables,
			int afferentCoupling,
			IMemberDocumentation documentation)
		{
			_halstead = halstead;
			CodeFile = codeFile;
			AccessModifier = accessModifier;
			LineNumber = lineNumber;
			LinesOfCode = linesOfCode;
			MaintainabilityIndex = maintainabilityIndex;
			CyclomaticComplexity = cyclomaticComplexity;
			Name = name;
			ClassCouplings = classCouplings.AsArray();
			NumberOfParameters = numberOfParameters;
			NumberOfLocalVariables = numberOfLocalVariables;
			AfferentCoupling = afferentCoupling;
			Documentation = documentation;
		}
Ejemplo n.º 4
0
		public async Task<ITypeMetric> CalculateFrom(TypeDeclarationSyntaxInfo typeNode, IEnumerable<IMemberMetric> metrics)
		{
			var memberMetrics = metrics.AsArray();
			var type = typeNode.Syntax;
			var symbol = Model.GetDeclaredSymbol(type);
			var documentation = await _documentationFactory.Create(symbol, CancellationToken.None);
			var metricKind = GetMetricKind(type);
			var source = CalculateClassCoupling(type, memberMetrics);
			var depthOfInheritance = CalculateDepthOfInheritance(type);
			var cyclomaticComplexity = memberMetrics.Sum(x => x.CyclomaticComplexity);
			var linesOfCode = memberMetrics.Sum(x => x.LinesOfCode);
			var maintainabilityIndex = CalculateAveMaintainabilityIndex(memberMetrics);
			var afferentCoupling = await CalculateAfferentCoupling(type);
			var efferentCoupling = GetEfferentCoupling(type, symbol);
			var instability = (double)efferentCoupling / (efferentCoupling + afferentCoupling);
			var modifier = GetAccessModifier(type.Modifiers);
			return new TypeMetric(
				symbol.IsAbstract,
				metricKind,
				modifier,
				memberMetrics,
				linesOfCode,
				cyclomaticComplexity,
				maintainabilityIndex,
				depthOfInheritance,
				source,
				type.GetName(),
				afferentCoupling,
				efferentCoupling,
				instability,
				documentation);
		}
Ejemplo n.º 5
0
 public virtual bool CanResolve(Type type, object context, IEnumerable <object> args)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     return(Mappings.CanResolve(this, type, args?.AsArray()));
 }
Ejemplo n.º 6
0
		public TypeDocumentation(string summary, string code, string example, string remarks, string returns, IEnumerable<TypeParameterDocumentation> typeParameters)
		{
			Summary = summary;
			Code = code;
			Example = example;
			Remarks = remarks;
			Returns = returns;
			TypeParameters = typeParameters.AsArray();
		}
        /// <summary>
        ///     Initializes a new instance of the <see cref="ComposablePartCatalogChangeEventArgs"/>.
        /// </summary>
        /// <param name="addedDefinitions">
        ///     An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that 
        ///     are being added to the <see cref="ComposablePartCatalog"/>.
        /// </param>
        /// <param name="removedDefinitions">
        ///     An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that 
        ///     are being removed from the <see cref="ComposablePartCatalog"/>.
        /// </param>
        /// <param name="atomicComposition">
        ///     A <see cref="AtomicComposition"/> representing all tentative changes that will
        ///     be completed if the change is successful, or discarded if it is not. 
        ///     <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/> 
        ///     or during a <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="addedDefinitions"/> or <paramref name="removedDefinitions"/> is <see langword="null"/>.
        /// </exception>
        public ComposablePartCatalogChangeEventArgs(IEnumerable<ComposablePartDefinition> addedDefinitions,
            IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition atomicComposition)
        {
            Requires.NotNull(addedDefinitions, "addedDefinitions");
            Requires.NotNull(removedDefinitions, "removedDefinitions");

            this.AddedDefinitions = addedDefinitions.AsArray();
            this.RemovedDefinitions = removedDefinitions.AsArray();
            this.AtomicComposition = atomicComposition;
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="ExportsChangeEventArgs"/> class with 
        ///     the specified changed export definitions.
        /// </summary>
        /// <param name="addedExports">
        ///     An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports
        ///     that have been added.
        /// </param>
        /// <param name="removedExports">
        ///     An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports
        ///     that have been removed.
        /// </param>
        /// <param name="atomicComposition">
        ///     A <see cref="AtomicComposition"/> representing all tentative changes that will
        ///     be completed if the change is successful, or discarded if it is not. 
        ///     <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/> 
        ///     or during a <see cref="ExportProvider.ExportsChanged"/> event.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="addedExports"/> or <paramref name="removedExports"/> is <see langword="null"/>.
        /// </exception>
        public ExportsChangeEventArgs(IEnumerable<ExportDefinition> addedExports,
                IEnumerable<ExportDefinition> removedExports, AtomicComposition atomicComposition)
        {
            Requires.NotNull(addedExports, "addedExports");
            Requires.NotNull(removedExports, "removedExports");

            this.AddedExports = addedExports.AsArray();
            this.RemovedExports = removedExports.AsArray();
            this.AtomicComposition = atomicComposition;
        }
Ejemplo n.º 9
0
		public async Task<IEnumerable<INamespaceMetric>> Calculate(IEnumerable<SyntaxTree> syntaxTrees, params Assembly[] references)
		{
			var trees = syntaxTrees.AsArray();
			var declarations = _syntaxCollector.GetDeclarations(trees);
			var statementMembers = declarations.Statements.Select(s =>
				s is StatementSyntax
				? SyntaxFactory.MethodDeclaration(
					SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
					Guid.NewGuid().ToString("N"))
					.WithBody(SyntaxFactory.Block((StatementSyntax)s))
					: s);
			var members = declarations.MemberDeclarations.Concat(statementMembers).AsArray();
			var anonClass = members.Any()
								? new[]
                                  {
                                      SyntaxFactory.ClassDeclaration(
                                          "UnnamedClass")
                                          .WithModifiers(
                                              SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                                          .WithMembers(SyntaxFactory.List(members))
                                  }
								: new TypeDeclarationSyntax[0];
			var array = declarations.TypeDeclarations
				.Concat(anonClass)
				.Cast<MemberDeclarationSyntax>()
				.AsArray();
			var anonNs = array.Any()
				? new[]
                          {
                              SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("Unnamed"))
                                  .WithMembers(SyntaxFactory.List(array))
                          }
				: new NamespaceDeclarationSyntax[0];
			var namespaceDeclarations = declarations
				.NamespaceDeclarations
				.Concat(anonNs)
				.Select(x => new NamespaceDeclarationSyntaxInfo
				{
					Name = x.GetName(x),
					Syntax = x
				})
				.GroupBy(x => x.Name)
				.Select(g => new NamespaceDeclaration
				{
					Name = g.Key,
					SyntaxNodes = g.AsArray()
				})
				.AsArray();

			var metadataReferences =
				(references.Any() ? references : new[] { typeof(object).Assembly }).Select(a => MetadataReference.CreateFromFile(a.Location)).ToArray();
			var commonCompilation = CSharpCompilation.Create("x", syntaxTrees: trees, references: metadataReferences);
			var namespaceMetrics = await CalculateNamespaceMetrics(namespaceDeclarations, commonCompilation, null).ConfigureAwait(false);
			return namespaceMetrics;
		}
Ejemplo n.º 10
0
		public MemberDocumentation(string summary, string code, string example, string remarks, string returns, IEnumerable<TypeParameterDocumentation> typeParameters, IEnumerable<ParameterDocumentation> parameters, IEnumerable<ExceptionDocumentation> exceptions)
		{
			Summary = summary;
			Code = code;
			Example = example;
			Remarks = remarks;
			Returns = returns;
			TypeParameters = typeParameters.AsArray();
			Parameters = parameters.AsArray();
			Exceptions = exceptions.AsArray();
		}
Ejemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpDirectRoute" /> class.
 /// </summary>
 /// <param name="routeTemplate">The route template.</param>
 /// <param name="defaults">The default values.</param>
 /// <param name="constraints">The route constraints.</param>
 /// <param name="actions">The actions that are reachable via this route.</param>
 public HttpDirectRoute(
     string routeTemplate,
     HttpRouteValueDictionary defaults,
     HttpRouteValueDictionary constraints,
     IEnumerable<ReflectedHttpActionDescriptor> actions)
     : base(routeTemplate, defaults: defaults, constraints: constraints, dataTokens: null, handler: null)
 {
     if (actions != null)
     {
         Actions = actions.AsArray();
         DataTokens[RouteKeys.ActionsDataTokenKey] = Actions;
     }
 }
Ejemplo n.º 12
0
		public Task<IEnumerable<IModelNode>> Transform(IEnumerable<IModelNode> source, IEnumerable<TransformRule> rules, CancellationToken cancellationToken)
		{
			return Task.Factory.StartNew(
				() =>
				{
					var allRules = rules.AsArray();
					var transformedVertices = from vertex in source
											  select TransformVertexRecursive(vertex, allRules);

					return transformedVertices.AsArray().AsEnumerable();
				}, 
				cancellationToken);
		}
Ejemplo n.º 13
0
		public ProjectMetric(string name, IEnumerable<INamespaceMetric> namespaceMetrics, IEnumerable<string> referencedProjects, double relationalCohesion)
		{
			Name = name;
			RelationalCohesion = relationalCohesion;
			Dependencies = referencedProjects.AsArray();
			EfferentCoupling = Dependencies.Count();
			NamespaceMetrics = namespaceMetrics.AsArray();
			LinesOfCode = NamespaceMetrics.Sum(x => x.LinesOfCode);
			MaintainabilityIndex = LinesOfCode == 0 ? 100 : NamespaceMetrics.Sum(x => x.MaintainabilityIndex * x.LinesOfCode) / LinesOfCode;
			CyclomaticComplexity = LinesOfCode == 0 ? 0 : NamespaceMetrics.Sum(x => x.CyclomaticComplexity * x.LinesOfCode) / LinesOfCode;
			ClassCouplings = NamespaceMetrics.SelectMany(x => x.ClassCouplings).Where(x => x.Assembly != Name).Distinct(Comparer).AsArray();
			Dependendants = ClassCouplings.Select(x => x.Assembly)
				.Distinct()
				.AsArray();
			AfferentCoupling = Dependendants.Count();
			var typeMetrics = NamespaceMetrics.SelectMany(x => x.TypeMetrics).AsArray();
			Abstractness = typeMetrics.Count(x => x.IsAbstract) / (double)typeMetrics.Count();
		}
Ejemplo n.º 14
0
		public SyntaxDeclarations GetDeclarations(IEnumerable<SyntaxTree> trees)
		{
			var syntaxTrees = trees.AsArray();

			foreach (var root in syntaxTrees.Select(syntaxTree => syntaxTree.GetRoot()))
			{
				Visit(root);
				CheckStatementSyntax(root);
			}

			return new SyntaxDeclarations
			{
				MemberDeclarations = _members.AsArray(),
				NamespaceDeclarations = _namespaces.AsArray(),
				Statements = _statements.AsArray(),
				TypeDeclarations = _types.AsArray()
			};
		}
Ejemplo n.º 15
0
		public NamespaceMetric(
			double maintainabilityIndex,
			int cyclomaticComplexity,
			int linesOfCode,
			IEnumerable<ITypeCoupling> classCouplings,
			int depthOfInheritance,
			string name,
			IEnumerable<ITypeMetric> typeMetrics,
			IDocumentation documentation)
		{
			MaintainabilityIndex = maintainabilityIndex;
			CyclomaticComplexity = cyclomaticComplexity;
			LinesOfCode = linesOfCode;
			ClassCouplings = classCouplings;
			DepthOfInheritance = depthOfInheritance;
			Name = name;
			Documentation = documentation;
			TypeMetrics = typeMetrics.AsArray();
			Abstractness = TypeMetrics.Count(x => x.IsAbstract) / (double)TypeMetrics.Count();
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Builds an <see cref="IHttpRoute"/> for a particular action.
        /// </summary>
        /// <param name="routeTemplate">The tokenized route template for the route.</param>
        /// <param name="httpMethods">The HTTP methods supported by the route.</param>
        /// <param name="actions">The actions to invoke for the route.</param>
        /// <returns>The generated <see cref="IHttpRoute"/>.</returns>
        public virtual IHttpRoute BuildHttpRoute(
            string routeTemplate,
            IEnumerable<HttpMethod> httpMethods,
            IEnumerable<ReflectedHttpActionDescriptor> actions)
        {
            if (routeTemplate == null)
            {
                throw Error.ArgumentNull("routeTemplate");
            }

            HttpRouteValueDictionary defaults = new HttpRouteValueDictionary();
            HttpRouteValueDictionary constraints = new HttpRouteValueDictionary();
            if (httpMethods != null)
            {
                // Current method constraint implementation is inefficient since it matches before running the constraint.
                // Consider checking the HTTP method first in a custom route as a performance optimization.
                constraints["httpMethod"] = new HttpMethodConstraint(httpMethods.AsArray());
            }

            string detokenizedRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(routeTemplate, defaults, constraints, ConstraintResolver);

            return BuildHttpRoute(detokenizedRouteTemplate, defaults, constraints, actions);
        }
Ejemplo n.º 17
0
        public static ReadOnlyCollection <T> ToReadOnlyCollection <T>(this IEnumerable <T> source)
        {
            Assumes.NotNull(source);

            return(new ReadOnlyCollection <T>(source.AsArray()));
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
 /// </summary>
 /// <param name="providers">The prioritized list of export providers. The providers are consulted in order in which they are supplied.</param>
 /// <remarks>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when 
 ///         executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>. 
 ///     </para>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers. 
 ///         That is, it will not try to dispose of any of them when it gets disposed.
 ///     </para>
 /// </remarks>
 public AggregateExportProvider(IEnumerable<ExportProvider> providers)
     : this((providers!= null) ? providers.AsArray() : null)
 {
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
 /// </summary>
 /// <param name="providers">The prioritized list of export providers. The providers are consulted in order in which they are supplied.</param>
 /// <remarks>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
 ///         executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
 ///     </para>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
 ///         That is, it will not try to dispose of any of them when it gets disposed.
 ///     </para>
 /// </remarks>
 public AggregateExportProvider(IEnumerable <ExportProvider>?providers)
     : this(providers?.AsArray())
 {
 }
Ejemplo n.º 20
0
 public virtual LangElement New(Span span, TypeRef classNameRef, IEnumerable <ActualParam> argsOpt, Span argsPosition)
 {
     return(new NewEx(span, classNameRef, argsOpt.AsArray(), argsPosition));
 }
Ejemplo n.º 21
0
		public ComparisonResult(ComparisonResultKind kind, IModelNode pattern, IEnumerable<IModelNode> matches)
		{
			Kind = kind;
			Pattern = pattern;
			Matches = matches == null ? null : matches.AsArray();
		}
 private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
 {
     genericTypeParameters = genericParameters as Type[];
     if (genericTypeParameters == null)
     {
         object[] genericParametersAsArray = genericParameters.AsArray();
         genericTypeParameters = new Type[genericParametersAsArray.Length];
         for (int i = 0; i < genericParametersAsArray.Length; i++)
         {
             genericTypeParameters[i] = genericParametersAsArray[i] as Type;
             if (genericTypeParameters[i] == null)
             {
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 23
0
        public virtual LangElement NewArray(Span span, IEnumerable <Item> itemsOpt, bool isOldNotation)
        {
            var items = itemsOpt.AsArray();

            return(ArrayEx.CreateArray(span, IsAllNull(items) ? null : items, !isOldNotation));
        }
 public void ShouldCheckEnumerableToArrayConversion(IEnumerable <int> source, int[] expected)
 {
     Assert.Equal(expected, source.AsArray());
 }
Ejemplo n.º 25
0
 public static ushort FromBe(IEnumerable <byte> b)
 {
     return(BitConverter.ToUInt16(BitConverter.IsLittleEndian ? b.Reverse().AsArray() : b.AsArray(), 0));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
 /// </summary>
 /// <param name="providers">The prioritized list of export providers. The providers are consulted in order in which they are supplied.</param>
 /// <remarks>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
 ///         executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
 ///     </para>
 ///     <para>
 ///         The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
 ///         That is, it will not try to dispose of any of them when it gets disposed.
 ///     </para>
 /// </remarks>
 public AggregateExportProvider(IEnumerable <ExportProvider> providers)
     : this((providers != null) ? providers.AsArray() : null)
 {
 }
Ejemplo n.º 27
0
 private static MediaTypeFormatter[] GetWritingFormatters(IEnumerable <MediaTypeFormatter> formatters)
 {
     Debug.Assert(formatters != null);
     return(formatters.AsArray());
 }
Ejemplo n.º 28
0
 public void HandleDisplayedItemsChanged(IEnumerable <ILookupItem> displayedItems)
 {
     _lastDisplayedItems = displayedItems.AsArray();
 }
Ejemplo n.º 29
0
        private IChangeSet <TObject, TKey> ProcessResult(IEnumerable <UpdateWithFilter> source)
        {
            var result = source.AsArray();

            //Have to process one item at a time as an item can be included multiple
            //times in any batch

            foreach (var item in result)
            {
                var matches = item.IsMatch;
                var key     = item.Change.Key;
                var u       = item.Change;

                switch (item.Change.Reason)
                {
                case ChangeReason.Add:
                {
                    if (matches)
                    {
                        _cache.AddOrUpdate(u.Current, u.Key);
                    }
                }
                break;

                case ChangeReason.Update:
                {
                    if (matches)
                    {
                        _cache.AddOrUpdate(u.Current, u.Key);
                    }
                    else
                    {
                        _cache.Remove(u.Key);
                    }
                }
                break;

                case ChangeReason.Remove:
                    _cache.Remove(u.Key);
                    break;

                case ChangeReason.Evaluate:
                {
                    var exisiting = _cache.Lookup(key);
                    if (matches)
                    {
                        if (!exisiting.HasValue)
                        {
                            _cache.AddOrUpdate(u.Current, u.Key);
                        }
                        else
                        {
                            _cache.Evaluate();
                        }
                    }
                    else
                    {
                        if (exisiting.HasValue)
                        {
                            _cache.Remove(u.Key);
                        }
                    }
                }
                break;
                }
            }
            return(_cache.CaptureChanges());
        }
Ejemplo n.º 30
0
        public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source)
        {
            ArgumentNullException.ThrowIfNull(source);

            return new ReadOnlyCollection<T>(source.AsArray());
        }
Ejemplo n.º 31
0
 public virtual TypeRef AnonymousTypeReference(Span span, Span headingSpan, bool conditional, PhpMemberAttributes attributes, IEnumerable <FormalTypeParam> typeParamsOpt, INamedTypeRef baseClassOpt, IEnumerable <INamedTypeRef> implements, IEnumerable <LangElement> members, Span bodySpan)
 {
     Debug.Assert(members != null && implements != null);
     return(new AnonymousTypeRef(span, new AnonymousTypeDecl(span, headingSpan,
                                                             conditional, attributes, false, typeParamsOpt.AsArray(),
                                                             baseClassOpt, implements.AsArray(), members.CastToArray <TypeMemberDecl>(),
                                                             bodySpan)));
 }
Ejemplo n.º 32
0
 public static int FromBeToInt(IEnumerable <byte> b)
 {
     return(BitConverter.ToInt32(BitConverter.IsLittleEndian ? b.Reverse().AsArray() : b.AsArray(), 0));
 }
Ejemplo n.º 33
0
 public virtual LangElement TraitAdaptationPrecedence(Span span, Tuple <TypeRef, NameRef> name, IEnumerable <TypeRef> precedences)
 {
     Debug.Assert(precedences != null);
     return(new TraitsUse.TraitAdaptationPrecedence(span, name, precedences.AsArray()));
 }
 private static MediaTypeFormatter[] GetWritingFormatters(IEnumerable<MediaTypeFormatter> formatters)
 {
     Contract.Assert(formatters != null);
     MediaTypeFormatterCollection formatterCollection = formatters as MediaTypeFormatterCollection;
     if (formatterCollection != null)
     {
         return formatterCollection.WritingFormatters;
     }
     return formatters.AsArray();
 }
Ejemplo n.º 35
0
 public virtual LangElement TraitUse(Span span, IEnumerable <TypeRef> traits, LangElement adaptationsBlock)
 {
     Debug.Assert(traits != null);
     return(new TraitsUse(span, traits.AsArray(), (TraitAdaptationBlock)adaptationsBlock));
 }
        private void UpdateTurnaroundThresholds(FractionViewModel fraction, IEnumerable <BuildingViewModel> buildings)
        {
            if (fraction == null)
            {
                return;
            }

            if (buildings == null)
            {
                return;
            }

            var componentArray = buildings.AsArray();

            var allProductionChains = componentArray
                                      .Select(x => x.ProductionChain).Where(x => x != null)
                                      .Distinct(new ExpressionComparer <ProductionChainViewModel>(x => x.Model))
                                      .ToArray();

            var factionGroups = fraction.Items.ToDictionary(x => x.Model);
            var chainCounts   = allProductionChains.ToDictionary(x => x.Model, x => x.Count);

            var capacities =
                from populationGroup in mRepository.GetAll <PopulationGroup>()
                where populationGroup.Fraction == fraction.Model

                let groupChains =
                    from chain in allProductionChains

                    let consumable = chain.OutputGood as ConsumableGood
                                     where consumable != null
                                     let consumingGroups = consumable.ProvisionCapacities

                                                           let orderedConsumerGroups =
                        from consumingGroup in consumingGroups
                        where consumingGroup.PopulationGroup.Fraction == fraction.Model
                        orderby consumingGroup.PopulationGroup.Tier
                        select consumingGroup.PopulationGroup

                        let principalGroup = orderedConsumerGroups.FirstOrDefault()
                                             where principalGroup != null
                                             where principalGroup == populationGroup
                                             select chain

                                             let provisionCapacities =
                            from chain in groupChains

                            let consumable = chain.OutputGood as ConsumableGood
                                             where consumable != null
                                             let provisionCapacities = consumable.ProvisionCapacities

                                                                       from provisionCapacity in provisionCapacities
                                                                       select new
            {
                provisionCapacity.PopulationGroup,
                Count = provisionCapacity.Count * chainCounts.GetValueByKeyOrDefault(chain.Model)
            }

            select new
            {
                PopulationGroup = populationGroup,
                Capacity        = provisionCapacities.OrderBy(x => x.Count).FirstOrDefault()?.Count ?? 0
            };

            var capacityToCount = capacities.ToDictionary(x => x.PopulationGroup);

            foreach (var group in capacityToCount.Keys)
            {
                var viewModel = factionGroups.GetValueByKeyOrDefault(group);
                if (viewModel == null)
                {
                    continue;
                }

                viewModel.TurnaroundThreshold = capacityToCount[group].Capacity;
            }
        }
Ejemplo n.º 37
0
 private static MediaTypeFormatter[] GetWritingFormatters(IEnumerable<MediaTypeFormatter> formatters)
 {
     Debug.Assert(formatters != null);
     return formatters.AsArray();
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpRoute" /> class.
        /// </summary>
        /// <param name="routeTemplate">The route template.</param>
        /// <param name="order">The subroute order.</param>
        /// <param name="defaults">The default values.</param>
        /// <param name="constraints">The route constraints.</param>
        /// <param name="actions">The actions that are reachable via this route.</param>
        public static HttpRoute BuildDirectRoute(
            string routeTemplate,
            int order,
            HttpRouteValueDictionary defaults,
            HttpRouteValueDictionary constraints,
            IEnumerable<ReflectedHttpActionDescriptor> actions)
        {
            HttpRoute route = new HttpRoute(routeTemplate, defaults: defaults, constraints: constraints, dataTokens: null, handler: null);

            if (actions != null)
            {
                route.DataTokens[RouteKeys.OrderDataTokenKey] = order;
                route.DataTokens[RouteKeys.PrecedenceDataTokenKey] = route.ParsedRoute.GetPrecedence(constraints);
                route.DataTokens[RouteKeys.ActionsDataTokenKey] = actions.AsArray();
            }
            
            return route;
        }
Ejemplo n.º 39
0
 public virtual LangElement Use(Span span, IEnumerable <UseBase> uses, AliasKind kind)
 {
     return(new UseStatement(span, uses.AsArray(), kind));
 }
Ejemplo n.º 40
0
        private void ValidateThis(HttpActionContext actionContext, ModelValidationNode parentNode)
        {
            ModelStateDictionary modelState = actionContext.ModelState;
            if (!modelState.IsValidField(ModelStateKey))
            {
                return; // short-circuit
            }

            // If 'this' is null and there is no parent, we cannot validate, and
            // the DataAnnotationsModelValidator will throw.   So we intercept here
            // to provide a catch-all value-required validation error
            if (parentNode == null && ModelMetadata.Model == null)
            {
                string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, ModelMetadata.GetDisplayName());
                modelState.AddModelError(trueModelStateKey, SRResources.Validation_ValueNotFound);
                return;
            }

            _validators = actionContext.GetValidators(ModelMetadata);

            object container = TryConvertContainerToMetadataType(parentNode);
            // Optimize for the common case where the validators are in an array
            ModelValidator[] validators = _validators.AsArray();
            for (int i = 0; i < validators.Length; i++)
            {
                ModelValidator validator = validators[i];
                foreach (ModelValidationResult validationResult in validator.Validate(ModelMetadata, container))
                {
                    string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, validationResult.MemberName);
                    modelState.AddModelError(trueModelStateKey, validationResult.Message);
                }
            }
        }
Ejemplo n.º 41
0
        public virtual LangElement List(Span span, IEnumerable <Item> targets, bool isOldNotation)
        {
            var items = targets.AsArray();

            return(ArrayEx.CreateList(span, IsAllNull(items) ? null : items, !isOldNotation));
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Sets the value for the <see cref="RecordBase.Content" /> property.
 /// </summary>
 /// <param name="newData">The new data.</param>
 /// <exception cref="ArgumentOutOfRangeException">The new data is too big.</exception>
 protected void SetContentProperty(IEnumerable <byte> newData)
 {
     base.Content = newData.AsArray();
 }
Ejemplo n.º 43
0
 public ComparisonResult(ComparisonResultKind kind, IModelNode pattern, IEnumerable <IModelNode> matches)
 {
     Kind    = kind;
     Pattern = pattern;
     Matches = matches == null ? null : matches.AsArray();
 }
Ejemplo n.º 44
0
		public ReferencedSymbol(ISymbol symbol, IEnumerable<ReferenceLocation> locations)
		{
			Symbol = symbol;
			Locations = locations.AsArray();
		}
        /// <summary>
        /// Creates a <see cref="string"/> from the specified sequence of Unicode characters.
        /// </summary>
        /// <param name="chars">The sequence of Unicode characters from which to create the string.</param>
        /// <returns>A string that corresponds to <paramref name="chars"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="chars"/> is <see langword="null"/>.</exception>
        public static string AsString(this IEnumerable <char> chars)
        {
            ArgumentValidate.NotNull(chars, nameof(chars));

            return(chars as string ?? new string(chars.AsArray()));
        }
Ejemplo n.º 46
0
 public ReferencedSymbol(ISymbol symbol, IEnumerable <ReferenceLocation> locations)
 {
     Symbol    = symbol;
     Locations = locations.AsArray();
 }