Beispiel #1
0
        public void IncludedResourceOnlyOnce()
        {
            var job    = new CompanyWithCustomers(id: "457", prefill: true);
            var person = new Person(true)
            {
                Friends = new List <Person>
                {
                    new Person(id: "124", prefill: true)
                    {
                        Job = job
                    },
                    new Person(id: "125", prefill: true)
                    {
                        Job = job
                    }
                }
            };

            var include = new IncludeContext(GetQuery("include", "friends.job"));
            var target  = new ResourceSerializer(person, DefaultResource,
                                                 GetUri(id: "123"), DefaultPathBuilder, null, include, null);
            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var included = result["included"] as JArray;

            Assert.Equal(3, included.Count);
        }
Beispiel #2
0
        public IncludeContext include()
        {
            IncludeContext _localctx = new IncludeContext(_ctx, State);

            EnterRule(_localctx, 14, RULE_include);
            try {
                EnterOuterAlt(_localctx, 1);
                {
                    State = 76; Match(COLON_SYM);
                    State = 77; Match(INCLUDE);
                    State = 78; Match(QUOTE_SYM);
                    State = 79; Match(IDENTIFIER);
                    State = 80; Match(QUOTE_SYM);
                    State = 81; Match(SEMICOLON_SYM);
                }
            }
            catch (RecognitionException re) {
                _localctx.exception = re;
                _errHandler.ReportError(this, re);
                _errHandler.Recover(this, re);
            }
            finally {
                ExitRule();
            }
            return(_localctx);
        }
Beispiel #3
0
        private static PackOptions GetPackOptions(JObject rawProject, Project project)
        {
            var rawPackOptions = rawProject.Value <JToken>("packOptions") as JObject;

            // Files to be packed along with the project
            IncludeContext packInclude = null;

            if (rawPackOptions != null && rawPackOptions.Value <JToken>("files") != null)
            {
                packInclude = new IncludeContext(
                    project.ProjectDirectory,
                    "files",
                    rawPackOptions,
                    defaultBuiltInInclude: null,
                    defaultBuiltInExclude: ProjectFilesCollection.DefaultBuiltInExcludePatterns);
            }

            var repository = GetPackOptionsValue <JToken>("repository", rawProject, rawPackOptions, project) as JObject;

            return(new PackOptions
            {
                ProjectUrl = GetPackOptionsValue <string>("projectUrl", rawProject, rawPackOptions, project),
                LicenseUrl = GetPackOptionsValue <string>("licenseUrl", rawProject, rawPackOptions, project),
                IconUrl = GetPackOptionsValue <string>("iconUrl", rawProject, rawPackOptions, project),
                Owners = GetPackOptionsValue <JToken>("owners", rawProject, rawPackOptions, project)?.Values <string>().ToArray() ?? EmptyArray <string> .Value,
                Tags = GetPackOptionsValue <JToken>("tags", rawProject, rawPackOptions, project)?.Values <string>().ToArray() ?? EmptyArray <string> .Value,
                ReleaseNotes = GetPackOptionsValue <string>("releaseNotes", rawProject, rawPackOptions, project),
                RequireLicenseAcceptance = GetPackOptionsValue <bool>("requireLicenseAcceptance", rawProject, rawPackOptions, project),
                Summary = GetPackOptionsValue <string>("summary", rawProject, rawPackOptions, project),
                RepositoryType = repository?.Value <string>("type"),
                RepositoryUrl = repository?.Value <string>("url"),
                PackInclude = packInclude
            });
        }
Beispiel #4
0
        private static bool IsEqual(IncludeContext first, IncludeContext second)
        {
            if (first == null || second == null)
            {
                return(first == second);
            }

            return(first.Equals(second));
        }
        private static bool IsEqual(IncludeContext first, IncludeContext second)
        {
            if (first == null || second == null)
            {
                return first == second;
            }

            return first.Equals(second);
        }
Beispiel #6
0
        private void PushIncludeContext(SourceFile file)
        {
            _currentFileSegmentAbsolutePosition = FileSegments.Sum(x => x.Length);

            var includeContext = new IncludeContext(file);

            _includeStack.Push(includeContext);
            _charReader = includeContext.CharReader;
            FileSegments.Add(new FileSegment(file, 0));
        }
Beispiel #7
0
        public static IEnumerable <string> ResolveFiles(this IncludeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            return(IncludeFilesResolver
                   .GetIncludeFiles(context, "/", diagnostics: null)
                   .Select(f => f.SourcePath));
        }
Beispiel #8
0
        private ResourceGraphPathSet IncludedGraphPathsFromContext(IncludeContext context)
        {
            if (context == null)
            {
                return(new ResourceGraphPathSet.All());
            }

            if (context.Includes != null && context.Includes.Any())
            {
                return(new ResourceGraphPathSet(_includeContext.Includes.Select(i => i.Name)));
            }

            return(new ResourceGraphPathSet.All());
        }
Beispiel #9
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = base.GetHashCode();
         result = (result * 397) ^ (W != null ? W.GetHashCode() : 0);
         result = (result * 397) ^ (PW != null ? PW.GetHashCode() : 0);
         result = (result * 397) ^ (DW != null ? DW.GetHashCode() : 0);
         result = (result * 397) ^ ReturnBody.GetHashCode();
         result = (result * 397) ^ Context.GetHashCode();
         result = (result * 397) ^ IncludeContext.GetHashCode();
         return(result);
     }
 }
Beispiel #10
0
        private void ExecuteTransformation(
            IncludeContextTransform transform,
            IncludeContext includeContext,
            ProjectItemGroupElement itemGroup)
        {
            var transformResult = transform.Transform(includeContext);

            if (transformResult != null && transformResult.Any())
            {
                _transformApplicator.Execute(
                    transformResult,
                    itemGroup,
                    mergeExisting: true);
            }
        }
 public ResourceSerializer(
     object value,
     ApiResource type,
     Uri baseUrl,
     IUrlPathBuilder urlBuilder,
     PaginationContext paginationContext,
     IncludeContext includeContext)
 {
     _urlBuilder         = urlBuilder;
     _resource           = type;
     _value              = value;
     _baseUrl            = baseUrl;
     _paginationContext  = paginationContext;
     _includeContext     = includeContext;
     _includedGraphPaths = IncludedGraphPathsFromContext(includeContext);
 }
Beispiel #12
0
        public void NoIncludedRelationshipData()
        {
            var includes = new IncludeContext();

            includes.DisableDefaultIncluded = true;
            var target = new ResourceSerializer(DefaultObject, DefaultResource,
                                                GetUri(id: "123"), DefaultPathBuilder, null, includes, null);

            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var included = result["included"] as JArray;

            Assert.Null(included);
        }
        private void ExecuteTransformation(
            IncludeContextTransform transform,
            IncludeContext includeContext,
            MigrationRuleInputs migrationRuleInputs)
        {
            var transformResult = transform.Transform(includeContext);

            if (transformResult != null && transformResult.Any())
            {
                var itemGroup = migrationRuleInputs.CommonItemGroup;
                _transformApplicator.Execute(
                    transformResult,
                    itemGroup,
                    mergeExisting: true);
            }
        }
Beispiel #14
0
        public void OmitRelationshipIdentifierObjectsWithoutProperty()
        {
            var includes = new IncludeContext();

            includes.DisableDefaultIncluded = true;
            var target = new ResourceSerializer(DefaultObject, DefaultResource,
                                                GetUri(id: "123"), DefaultPathBuilder, null, includes, null);

            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var relationships = result["data"]["relationships"];
            var secretFriends = relationships["secret-friends"];

            Assert.Null(secretFriends["data"]);
        }
Beispiel #15
0
        public void IncludedRelationshipIdentifierObjects()
        {
            var includes = new IncludeContext();

            includes.DisableDefaultIncluded = true;
            var target = new ResourceSerializer(DefaultObject, DefaultResource,
                                                GetUri(id: "123"), DefaultPathBuilder, null, includes, null);

            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var relationships = result["data"]["relationships"];
            var job           = relationships["job"];

            Assert.NotNull(job["data"]);
        }
        private IncludeContext GetCompileRemoveContext(
            CommonCompilerOptions compilerOptions,
            string projectDirectory)
        {
            var includeContext = compilerOptions.CompileInclude;

            if (includeContext == null && ContainsCompilerResources(projectDirectory))
            {
                includeContext = new IncludeContext(
                    projectDirectory,
                    "compile",
                    new JObject(),
                    null,
                    null);
                includeContext.CustomRemovePatterns.Add(BuiltInCompilerResourcesPattern);
            }
            return(includeContext);
        }
Beispiel #17
0
 public ResourceSerializer(
     object value,
     ApiResource type,
     Uri baseUrl,
     IUrlPathBuilder urlBuilder,
     PaginationContext paginationContext,
     IncludeContext includeContext,
     IPropertyNameConverter propertyNameConverter = null)
 {
     _propertyNameConverter = propertyNameConverter ?? new DefaultPropertyNameConverter();
     _urlBuilder            = urlBuilder;
     _resource           = type;
     _value              = value;
     _baseUrl            = baseUrl;
     _paginationContext  = paginationContext;
     _includeContext     = includeContext;
     _includedGraphPaths = IncludedGraphPathsFromContext(includeContext);
 }
Beispiel #18
0
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Content.Expression != null)
            {
                targetCommand.AddParameter("Content", Content.Get(context));
            }

            if (EventLogRecord.Expression != null)
            {
                targetCommand.AddParameter("EventLogRecord", EventLogRecord.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (IncludeContext.Expression != null)
            {
                targetCommand.AddParameter("IncludeContext", IncludeContext.Get(context));
            }

            if (To.Expression != null)
            {
                targetCommand.AddParameter("To", To.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
        private IncludeContext GetEmbedIncludeContext(
            CommonCompilerOptions compilerOptions,
            string projectDirectory)
        {
            var embedIncludeContext = compilerOptions.EmbedInclude;

            embedIncludeContext?.BuiltInsExclude.Add("@(EmbeddedResource)");

            if (embedIncludeContext == null && ContainsCompilerResources(projectDirectory))
            {
                embedIncludeContext = new IncludeContext(
                    projectDirectory,
                    "embed",
                    new JObject(),
                    null,
                    null);
                embedIncludeContext.CustomIncludePatterns.Add(BuiltInCompilerResourcesPattern);
            }

            return(embedIncludeContext);
        }
Beispiel #20
0
        public void OnlyIncludedRelationshipData()
        {
            var includes = new IncludeContext();

            includes.DisableDefaultIncluded = true;
            var includeParam = new KeyValuePair <string, string>("include", "job");

            includes.SetIncludes(new List <KeyValuePair <string, string> >()
            {
                includeParam
            });
            var target = new ResourceSerializer(DefaultObject, DefaultResource,
                                                GetUri(id: "123"), DefaultPathBuilder, null, includes, null);

            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var included = result["included"] as JArray;

            Assert.Equal(1, included.Count());
        }
        public void AlwaysIncludeRelationshipIdentifierObjects()
        {
            var includes = new IncludeContext();

            includes.DisableDefaultIncluded = true;
            var includeParam = new KeyValuePair <string, string>("include", "job");

            includes.SetIncludes(new List <KeyValuePair <string, string> >()
            {
                includeParam
            });
            var target = new ResourceSerializer(DefaultObject, DefaultResource,
                                                GetUri(id: "123"), DefaultPathBuilder, null, includes, null);

            var result = target.Serialize();

            _output.WriteLine(result.ToString());

            var relationships = result["data"]["relationships"];

            Assert.True(relationships["car"]["data"].HasValues);
            Assert.True(relationships["friends"]["data"] is JArray);
        }
 public static IEnumerable<IncludeEntry> GetIncludeFiles(IncludeContext context, string targetBasePath, IList<DiagnosticMessage> diagnostics)
 {
     return GetIncludeFiles(context, targetBasePath, diagnostics, flatten: false);
 }
Beispiel #23
0
 private IEnumerable <IncludeEntry> GetIncludeFiles(IncludeContext context, string targetBasePath)
 {
     return(IncludeFilesResolver.GetIncludeFiles(context, targetBasePath, null));
 }
Beispiel #24
0
        public override IEnumerable <ProjectItemElement> ConditionallyTransform(IncludeContext source)
        {
            var transformSet = CreateTransformSet(source);

            return(transformSet.Select(t => t.Item1.Transform(t.Item2)));
        }
Beispiel #25
0
        private IEnumerable <Tuple <AddItemTransform <IncludeContext>, IncludeContext> > CreateTransformSet(IncludeContext source)
        {
            var transformSet = new List <Tuple <AddItemTransform <IncludeContext>, IncludeContext> >
            {
                Tuple.Create(IncludeFilesExcludeFilesTransformGetter(_itemName), source),
                Tuple.Create(IncludeExcludeTransformGetter(_itemName), source)
            };

            if (source == null)
            {
                return(transformSet);
            }

            // Mappings must be executed before the transform set to prevent a the
            // non-mapped items that will merge with mapped items from being encompassed
            foreach (var mappingEntry in source.Mappings.OrEmptyIfNull())
            {
                var targetPath     = mappingEntry.Key;
                var includeContext = mappingEntry.Value;

                transformSet.Insert(0,
                                    Tuple.Create(
                                        MappingsIncludeExcludeTransformGetter(_itemName, targetPath),
                                        includeContext));

                transformSet.Insert(0,
                                    Tuple.Create(
                                        MappingsIncludeFilesExcludeFilesTransformGetter(_itemName, targetPath),
                                        includeContext));
            }

            foreach (var metadataElement in _metadata)
            {
                foreach (var transform in transformSet)
                {
                    transform.Item1.WithMetadata(metadataElement);
                }
            }

            return(transformSet);
        }
Beispiel #26
0
	public IncludeContext include() {
		IncludeContext _localctx = new IncludeContext(Context, State);
		EnterRule(_localctx, 28, RULE_include);
		try {
			EnterOuterAlt(_localctx, 1);
			{
			State = 132; Match(INCLUDE);
			State = 133; string_data();
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}
Beispiel #27
0
        public override IEnumerable <ProjectItemElement> ConditionallyTransform(IncludeContext source)
        {
            CreateTransformSet();

            return(_transformSet.Select(t => t.Transform(source)));
        }
Beispiel #28
0
        private void PushIncludeContext(SourceText text)
        {
            _currentFileSegmentAbsolutePosition = FileSegments.Sum(x => x.Length);

            var includeContext = new IncludeContext(text);
            _includeStack.Push(includeContext);
            _charReader = includeContext.CharReader;
            FileSegments.Add(new FileSegment(text, 0));
        }
 private IEnumerable<IncludeEntry> GetIncludeFiles(IncludeContext context, string targetBasePath)
 {
     return IncludeFilesResolver.GetIncludeFiles(context, targetBasePath, null);
 }
        public static IEnumerable<IncludeEntry> GetIncludeFiles(
            IncludeContext context,
            string targetBasePath,
            IList<DiagnosticMessage> diagnostics,
            bool flatten)
        {
            var sourceBasePath = PathUtility.EnsureTrailingSlash(context.SourceBasePath);
            targetBasePath = PathUtility.GetPathWithDirectorySeparator(targetBasePath);

            var includeEntries = new HashSet<IncludeEntry>();

            // Check for illegal characters in target path
            if (string.IsNullOrEmpty(targetBasePath))
            {
                diagnostics?.Add(new DiagnosticMessage(
                    ErrorCodes.NU1003,
                    $"Invalid '{context.Option}' section. The target '{targetBasePath}' is invalid, " +
                    "targets must either be a file name or a directory suffixed with '/'. " +
                    "The root directory of the package can be specified by using a single '/' character.",
                    sourceBasePath,
                    DiagnosticMessageSeverity.Error));
            }
            else if (targetBasePath.Split(Path.DirectorySeparatorChar).Any(s => s.Equals(".") || s.Equals("..")))
            {
                diagnostics?.Add(new DiagnosticMessage(
                    ErrorCodes.NU1004,
                    $"Invalid '{context.Option}' section. " +
                    $"The target '{targetBasePath}' contains path-traversal characters ('.' or '..'). " +
                    "These characters are not permitted in target paths.",
                    sourceBasePath,
                    DiagnosticMessageSeverity.Error));
            }
            else
            {
                var files = GetIncludeFilesCore(
                    sourceBasePath,
                    context.IncludePatterns,
                    context.ExcludePatterns,
                    context.IncludeFiles,
                    context.BuiltInsInclude,
                    context.BuiltInsExclude).ToList();

                var isFile = targetBasePath[targetBasePath.Length - 1] != Path.DirectorySeparatorChar;
                if (isFile && files.Count > 1)
                {
                    // It's a file. But the glob matched multiple things
                    diagnostics?.Add(new DiagnosticMessage(
                        ErrorCodes.NU1005,
                        $"Invalid '{ProjectFilesCollection.PackIncludePropertyName}' section. " +
                        $"The target '{targetBasePath}' refers to a single file, but the corresponding pattern " +
                        "produces multiple files. To mark the target as a directory, suffix it with '/'.",
                        sourceBasePath,
                        DiagnosticMessageSeverity.Error));
                }
                else if (isFile && files.Count > 0)
                {
                    var filePath = Path.GetFullPath(
                        Path.Combine(sourceBasePath, PathUtility.GetPathWithDirectorySeparator(files[0].Path)));

                    includeEntries.Add(new IncludeEntry(targetBasePath, filePath));
                }
                else if (!isFile)
                {
                    targetBasePath = targetBasePath.Substring(0, targetBasePath.Length - 1);

                    foreach (var file in files)
                    {
                        var fullPath = Path.GetFullPath(
                            Path.Combine(sourceBasePath, PathUtility.GetPathWithDirectorySeparator(file.Path)));
                        string targetPath;

                        if (flatten)
                        {
                            targetPath = Path.Combine(targetBasePath, PathUtility.GetPathWithDirectorySeparator(file.Stem));
                        }
                        else
                        {
                            targetPath = Path.Combine(
                                targetBasePath,
                                PathUtility.GetRelativePathIgnoringDirectoryTraversals(sourceBasePath, fullPath));
                        }

                        includeEntries.Add(new IncludeEntry(targetPath, fullPath));
                    }
                }

                if (context.IncludeFiles != null)
                {
                    foreach (var literalRelativePath in context.IncludeFiles)
                    {
                        var fullPath = Path.GetFullPath(Path.Combine(sourceBasePath, literalRelativePath));
                        string targetPath;

                        if (isFile)
                        {
                            targetPath = targetBasePath;
                        }
                        else if (flatten)
                        {
                            targetPath =  Path.Combine(targetBasePath, Path.GetFileName(fullPath));
                        }
                        else
                        {
                            targetPath = Path.Combine(targetBasePath, PathUtility.GetRelativePath(sourceBasePath, fullPath));
                        }

                        includeEntries.Add(new IncludeEntry(targetPath, fullPath));
                    }
                }

                if (context.ExcludeFiles != null)
                {
                    var literalExcludedFiles = new HashSet<string>(
                        context.ExcludeFiles.Select(file => Path.GetFullPath(Path.Combine(sourceBasePath, file))),
                        StringComparer.Ordinal);

                    includeEntries.RemoveWhere(entry => literalExcludedFiles.Contains(entry.SourcePath));
                }
            }
            
            if (context.Mappings != null)
            {
                // Finally add all the mappings
                foreach (var map in context.Mappings)
                {
                    var targetPath = Path.Combine(targetBasePath, PathUtility.GetPathWithDirectorySeparator(map.Key));

                    foreach (var file in GetIncludeFiles(map.Value, targetPath, diagnostics, flatten: true))
                    {
                        file.IsCustomTarget = true;

                        // Prefer named targets over default ones
                        includeEntries.RemoveWhere(f => string.Equals(f.SourcePath, file.SourcePath) && !f.IsCustomTarget);
                        includeEntries.Add(file);
                    }
                }
            }

            return includeEntries;
        }