예제 #1
0
 public void Pop()
 {
     if (Sources.Any())
     {
         _sources.RemoveAt(0);
     }
 }
예제 #2
0
        /// <summary>
        /// Check proper properties initialization, depending on selected mode.
        /// @see IInitializationPostOperations#AfterPropertiesSet()
        /// </summary>
        public void AfterPropertiesSet()
        {
            Assert.NotNull(Mode, "Mode should be specified");
            switch (Mode)
            {
            case FileUtilsMode.Copy:
            case FileUtilsMode.Merge:
            case FileUtilsMode.MergeCopy:
                Assert.State(Targets != null && Targets.Count == 1, "one and only one target must be specified.");
                if (Strict)
                {
                    Assert.NotEmpty(Sources, "STRICT MODE : at least one source must be specified.");
                }
                else if (!Sources.Any())
                {
                    Logger.Warn("no sources specified.");
                }
                break;

            case FileUtilsMode.Delete:
            case FileUtilsMode.Reset:
                if (Strict)
                {
                    Assert.NotEmpty(Targets, "STRICT MODE : at least one target must be specified.");
                }
                else if (!Targets.Any())
                {
                    Logger.Warn("no targets specified.");
                }
                break;

            default:
                throw new InvalidOperationException("This mode is not supported :[" + Mode + "]");
            }
        }
예제 #3
0
        public bool CanAddSource()
        {
            if (string.IsNullOrWhiteSpace(NewSourceName))
            {
                return(false);
            }

            if (Sources.Any(s => String.Compare(s.Name, NewSourceName, StringComparison.InvariantCultureIgnoreCase) == 0))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(NewSourceUrl))
            {
                return(false);
            }

            if (Sources.Any(s => String.Compare(s.Url, NewSourceUrl, StringComparison.InvariantCultureIgnoreCase) == 0))
            {
                return(false);
            }

            Uri url;

            if (!Uri.TryCreate(NewSourceUrl, UriKind.Absolute, out url))
            {
                return(false);
            }

            return(true);
        }
예제 #4
0
 private bool SetCertificatePresent()
 {
     return(Sources.Any(fs =>
     {
         return (FactType.Equals(Fact.BIRTH) && fs.isBirthCert()) ||
         (FactType.Equals(Fact.DEATH) && fs.isDeathCert()) ||
         (FactType.Equals(Fact.MARRIAGE) && fs.isMarriageCert()) ||
         (FactType.Equals(Fact.CENSUS) && fs.isCensusCert());
     }));
 }
예제 #5
0
        /// <summary>
        /// Check proper properties initialization, depending on selected mode.
        /// @see IInitializationPostOperations#AfterPropertiesSet()
        /// </summary>
        public void AfterPropertiesSet()
        {
            Assert.NotNull(Mode, "Mode should be specified");
            switch (Mode)
            {
            case FileUtilsMode.Copy:
            case FileUtilsMode.Merge:
            case FileUtilsMode.MergeCopy:
                Assert.State(Targets != null && Targets.Count == 1, "one and only one target must be specified.");
                if (Strict)
                {
                    Assert.NotEmpty(Sources, "STRICT MODE : at least one source must be specified.");
                }
                else if (!Sources.Any())
                {
                    Logger.Warn("no sources specified.");
                }
                break;

            case FileUtilsMode.Delete:
            case FileUtilsMode.Reset:
                if (Strict)
                {
                    Assert.NotEmpty(Targets, "STRICT MODE : at least one target must be specified.");
                }
                else if (!Targets.Any())
                {
                    Logger.Warn("no targets specified.");
                }
                break;

            case FileUtilsMode.Compare:
                //=> we need at least 2 file resources to compare...
                Assert.State(Sources != null && Sources.Count == 2, "Files Compare operation requires that 2 files must be specified.");

                //=> now lets make sure resources exist and are files...
                foreach (IResource source in Sources)
                {
                    //=> make sure source exists...
                    Assert.State(source.Exists(), source.GetDescription() + " does not exist.");

                    //=> source should be a file (NOT Directory)...
                    Assert.State(!source.GetFileInfo().Attributes.HasFlag(FileAttributes.Directory), source.GetDescription() + " should be a file, NOT Directory.");
                }
                break;

            default:
                throw new InvalidOperationException("This mode is not supported :[" + Mode + "]");
            }
        }
예제 #6
0
        public async void AddSource()
        {
            if (string.IsNullOrWhiteSpace(NewSourceName))
            {
                _progressService.ShowMessageAsync("New Source", "Source must have a name.");
                return;
            }

            if (Sources.Any(s => String.Compare(s.Name, NewSourceName, StringComparison.InvariantCultureIgnoreCase) == 0))
            {
                _progressService.ShowMessageAsync("New Source", "There's already a source with that name.");
                return;
            }

            if (string.IsNullOrWhiteSpace(NewSourceUrl))
            {
                _progressService.ShowMessageAsync("New Source", "Source must have a Url.");
                return;
            }

            if (Sources.Any(s => String.Compare(s.Url, NewSourceUrl, StringComparison.InvariantCultureIgnoreCase) == 0))
            {
                _progressService.ShowMessageAsync("New Source", "There's already a source with that url.");
                return;
            }

            Uri url;

            if (!Uri.TryCreate(NewSourceUrl, UriKind.Absolute, out url))
            {
                _progressService.ShowMessageAsync("New Source", "Source url is malformed.");
                return;
            }

            if (!(await _packageService.Value.TestSourceUrl(url)))
            {
                _progressService.ShowMessageAsync("New Source", "Failed to query source.");
                return;
            }

            _sourceService.AddSource(new SourceViewModel {
                Name = NewSourceName, Url = NewSourceUrl
            });
            NewSourceName = "";
            NewSourceUrl  = "";
        }
        /// <summary>
        /// Find's a template by its name (with prefix) and returns it if found
        /// </summary>
        /// <param name="name">The name of the template</param>
        /// <returns></returns>
        public LiveDataSourceTemplate FindTemplate(string name)
        {
            // If there is no known prefix...
            if (name.IndexOf('.') <= 0 ||
                // Or the text before the first . is not a known prefix....
                Sources?.Any(source => source.Prefix.EqualsIgnoreCase(name.Substring(0, name.IndexOf('.')))) != true)
            {
                // Add default prefix
                name = $"{DnaSettings.LiveDataDefaultPrefix}.{name}";
            }

            // Get a variable that has the matching prefix.name
            var foundTemplate = Sources?.Where(source => source.Templates.Any(template => $"{source.Prefix}.{template.Name}".EqualsIgnoreCase(name)))
                                .Select(source => source.Templates.First(template => $"{source.Prefix}.{template.Name}".EqualsIgnoreCase(name)))
                                .FirstOrDefault();

            // Return result
            return(foundTemplate);
        }
예제 #8
0
        public string GenerateQueryString()
        {
            var filters = new List <string>();

            if (LogLevels != null && LogLevels.Any())
            {
                var levelsString = String.Join(" OR ", LogLevels.Select(x => string.Format("{0}:{1}", LuceneLoggerBackend.TypeFiledName, x)));
                filters.Add(levelsString);
            }

            if (Sources != null && Sources.Any())
            {
                var sourcesString = String.Join(" OR ", Sources.Select(x => string.Format("{0}:{1}", LuceneLoggerBackend.SourceFieldName, x)));
                filters.Add(sourcesString);
            }

            if (!string.IsNullOrEmpty(CustomFilter))
            {
                filters.Add(CustomFilter);
            }

            return(string.Join(" AND ", filters.Select(x => string.Format("({0})", x))));
        }
예제 #9
0
        public string this[[NotNull] string key]
        {
            get
            {
                if (string.IsNullOrEmpty(key))
                {
                    throw new InvalidOperationException(Resources.Error_EmptyKey);
                }

                // If a key in the newly added configuration source is identical to a key in a
                // formerly added configuration source, the new one overrides the former one.
                // So we search in reverse order, starting with latest configuration source.
                foreach (var src in _sources.Reverse())
                {
                    string value = null;

                    if (src.TryGet(GetPrefix() + key, out value))
                    {
                        return(value);
                    }
                }

                return(null);
            }
            set
            {
                if (!Sources.Any())
                {
                    throw new InvalidOperationException(Resources.Error_NoSources);
                }

                foreach (var src in Sources)
                {
                    src.Set(GetPrefix() + key, value);
                }
            }
        }
예제 #10
0
        private async Task <bool> RestoreForProject(LocalPackageRepository localRepository, string projectJsonPath, string rootDirectory, string packagesDirectory)
        {
            var success = true;

            Reports.Information.WriteLine(string.Format("Restoring packages for {0}", projectJsonPath.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            Project project;

            if (!Project.TryGetProject(projectJsonPath, out project))
            {
                throw new Exception("TODO: project.json parse error");
            }

            Func <string, string> getVariable = key =>
            {
                return(null);
            };

            ScriptExecutor.Execute(project, "prerestore", getVariable);

            var projectDirectory  = project.ProjectDirectory;
            var restoreOperations = new RestoreOperations {
                Report = Reports.Information
            };
            var projectProviders = new List <IWalkProvider>();
            var localProviders   = new List <IWalkProvider>();
            var remoteProviders  = new List <IWalkProvider>();
            var contexts         = new List <RestoreContext>();

            projectProviders.Add(
                new LocalWalkProvider(
                    new ProjectReferenceDependencyProvider(
                        new ProjectResolver(
                            projectDirectory,
                            rootDirectory))));

            localProviders.Add(
                new LocalWalkProvider(
                    new NuGetDependencyResolver(
                        packagesDirectory,
                        new EmptyFrameworkResolver())));

            var allSources = SourceProvider.LoadPackageSources();

            var enabledSources = Sources.Any() ?
                                 Enumerable.Empty <PackageSource>() :
                                 allSources.Where(s => s.IsEnabled);

            var addedSources = Sources.Concat(FallbackSources).Select(
                value => allSources.FirstOrDefault(source => CorrectName(value, source)) ?? new PackageSource(value));

            var effectiveSources = enabledSources.Concat(addedSources).Distinct().ToList();

            foreach (var source in effectiveSources)
            {
                if (new Uri(source.Source).IsFile)
                {
                    remoteProviders.Add(
                        new RemoteWalkProvider(
                            new PackageFolder(
                                source.Source,
                                Reports.Verbose)));
                }
                else
                {
                    remoteProviders.Add(
                        new RemoteWalkProvider(
                            new PackageFeed(
                                source.Source,
                                source.UserName,
                                source.Password,
                                NoCache,
                                Reports.Verbose)));
                }
            }

            foreach (var configuration in project.GetTargetFrameworks())
            {
                var context = new RestoreContext
                {
                    FrameworkName           = configuration.FrameworkName,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                };
                contexts.Add(context);
            }
            if (!contexts.Any())
            {
                contexts.Add(new RestoreContext
                {
                    FrameworkName           = ApplicationEnvironment.TargetFramework,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                });
            }

            var tasks = new List <Task <GraphNode> >();

            foreach (var context in contexts)
            {
                tasks.Add(restoreOperations.CreateGraphNode(context, new Library {
                    Name = project.Name, Version = project.Version
                }, _ => true));
            }
            var graphs = await Task.WhenAll(tasks);

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Resolving complete".Green(), sw.ElapsedMilliseconds));

            var installItems = new List <GraphItem>();
            var missingItems = new List <Library>();

            ForEach(graphs, node =>
            {
                if (node == null || node.Library == null)
                {
                    return;
                }
                if (node.Item == null || node.Item.Match == null)
                {
                    if (node.Library.Version != null && !missingItems.Contains(node.Library))
                    {
                        missingItems.Add(node.Library);
                        Reports.Information.WriteLine(string.Format("Unable to locate {0} >= {1}", node.Library.Name.Red().Bold(), node.Library.Version));
                        success = false;
                    }
                    return;
                }
                var isRemote = remoteProviders.Contains(node.Item.Match.Provider);
                var isAdded  = installItems.Any(item => item.Match.Library == node.Item.Match.Library);
                if (!isAdded && isRemote)
                {
                    installItems.Add(node.Item);
                }
            });

            var dependencies = new Dictionary <Library, string>();

            // If there is a global.json file specified, we should do SHA value verification
            var    globalJsonFileSpecified = !string.IsNullOrEmpty(GlobalJsonFile);
            JToken dependenciesNode        = null;

            if (globalJsonFileSpecified)
            {
                var globalJson = JObject.Parse(File.ReadAllText(GlobalJsonFile));
                dependenciesNode = globalJson["dependencies"];
                if (dependenciesNode != null)
                {
                    dependencies = dependenciesNode
                                   .OfType <JProperty>()
                                   .ToDictionary(d => new Library()
                    {
                        Name    = d.Name,
                        Version = SemanticVersion.Parse(d.Value.Value <string>("version"))
                    },
                                                 d => d.Value.Value <string>("sha"));
                }
            }

            var packagePathResolver = new DefaultPackagePathResolver(packagesDirectory);

            using (var sha512 = SHA512.Create())
            {
                foreach (var item in installItems)
                {
                    var library = item.Match.Library;

                    var memStream = new MemoryStream();
                    await item.Match.Provider.CopyToAsync(item.Match, memStream);

                    memStream.Seek(0, SeekOrigin.Begin);
                    var nupkgSHA = Convert.ToBase64String(sha512.ComputeHash(memStream));

                    string expectedSHA;
                    if (dependencies.TryGetValue(library, out expectedSHA))
                    {
                        if (!string.Equals(expectedSHA, nupkgSHA, StringComparison.Ordinal))
                        {
                            Reports.Information.WriteLine(
                                string.Format("SHA of downloaded package {0} doesn't match expected value.".Red().Bold(),
                                              library.ToString()));
                            success = false;
                            continue;
                        }
                    }
                    else
                    {
                        // Report warnings only when given global.json contains "dependencies"
                        if (globalJsonFileSpecified && dependenciesNode != null)
                        {
                            Reports.Information.WriteLine(
                                string.Format("Expected SHA of package {0} doesn't exist in given global.json file.".Yellow().Bold(),
                                              library.ToString()));
                        }
                    }

                    Reports.Information.WriteLine(string.Format("Installing {0} {1}", library.Name.Bold(), library.Version));

                    var targetPath  = packagePathResolver.GetInstallPath(library.Name, library.Version);
                    var targetNupkg = packagePathResolver.GetPackageFilePath(library.Name, library.Version);
                    var hashPath    = packagePathResolver.GetHashPath(library.Name, library.Version);

                    // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple
                    // processes are extracting to the same destination simultaneously
                    await ConcurrencyUtilities.ExecuteWithFileLocked(targetNupkg, async createdNewLock =>
                    {
                        // If this is the first process trying to install the target nupkg, go ahead
                        // After this process successfully installs the package, all other processes
                        // waiting on this lock don't need to install it again
                        if (createdNewLock)
                        {
                            Directory.CreateDirectory(targetPath);
                            using (var stream = new FileStream(targetNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete))
                            {
                                await item.Match.Provider.CopyToAsync(item.Match, stream);
                                stream.Seek(0, SeekOrigin.Begin);

                                ExtractPackage(targetPath, stream);
                            }

                            File.WriteAllText(hashPath, nupkgSHA);
                        }

                        return(0);
                    });
                }
            }

            ScriptExecutor.Execute(project, "postrestore", getVariable);

            ScriptExecutor.Execute(project, "prepare", getVariable);

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Restore complete".Green().Bold(), sw.ElapsedMilliseconds));

            // Print the dependency graph
            if (success)
            {
                var graphNum = contexts.Count;
                for (int i = 0; i < graphNum; i++)
                {
                    PrintDependencyGraph(graphs[i], contexts[i].FrameworkName);
                }
            }

            return(success);
        }
예제 #11
0
        private void OnSourcesPropertyChanged()
        {
            if (Source != null)
            {
                return;
            }

            // If there are no SuperImageSources, do nothing
            if (!Sources.Any())
            {
                return;
            }

            // Get the current application's scale
            var scale = ApplicationSpace.ScaleFactor();

            // Get the first SuperImageSource whose min/max scales best match the current application's scale
            var items = Sources.Where(
                x =>
                (scale >= x.MinScale && 0 == x.MaxScale) ||
                (0 == x.MinScale && scale <= x.MaxScale) ||
                (scale >= x.MinScale && scale <= x.MaxScale)
                ).ToArray();

            SuperImageSource selectedImageSource;

            if (items.Any())
            {
                selectedImageSource = items.FirstOrDefault(x => x.IsDefault);

                // If there isn't a default SuperImageSource, then do nothing
                if (selectedImageSource == default(SuperImageSource))
                {
                    selectedImageSource = items.FirstOrDefault();
                }
            }
            else
            // If no best match exists for the current application scale, then we need to check for a default SuperImageSource
            {
                selectedImageSource = Sources.FirstOrDefault(x => x.IsDefault);

                // If there isn't a default SuperImageSource, then do nothing
                if (selectedImageSource == default(SuperImageSource))
                {
                    selectedImageSource = Sources.FirstOrDefault();
                }

                // If there isn't a default SuperImageSource, then do nothing
                if (selectedImageSource == default(SuperImageSource))
                {
                    return;
                }
            }

            // Create the bitmap image, this will check whether the SuperImageSource's uri is looking in isolatedstorage
            // if not, it will create the bitmap image from the uri provided
            if (selectedImageSource != null)
            {
                // Set the SuperImage's image's source
                _primaryImage.Source = selectedImageSource.Source.ToBitmapImage();
            }
        }
예제 #12
0
        public string this[string propertyName]
        {
            get
            {
                try
                {
                    string validationResult = String.Empty;
                    if (ValidationEnabled)
                    {
                        switch (propertyName)
                        {
                        case "TaskConveyor":
                            if (TaskConveyor != EnumSimpleCommandConveyorTask.Move &&
                                TaskConveyor != EnumSimpleCommandConveyorTask.Create &&
                                TaskConveyor != EnumSimpleCommandConveyorTask.Delete)
                            {
                                validationResult = ResourceReader.GetString("ERR_TASK");
                            }
                            RaisePropertyChanged("Source");
                            break;

                        case "MaterialStr":
                            if (TaskConveyor == EnumSimpleCommandConveyorTask.Create)
                            {
                                if (Material.HasValue && _warehouse.DBService.FindMaterial(Material.Value) != null)
                                {
                                    validationResult = ResourceReader.GetString("ERR_MATERIALEXISTS");
                                }
                            }
                            else
                            {
                                if (!Material.HasValue || Material <= 0)
                                {
                                    validationResult = ResourceReader.GetString("ERR_MATERIALNOTVALID");
                                }
                                else if (_warehouse.DBService.FindMaterial(Material.Value) == null)
                                {
                                    validationResult = ResourceReader.GetString("ERR_MATERIALUNKNOWN");
                                }
                            }
                            break;

                        case "Source":
                            if (Sources != null && !Sources.Any(p => p == Source))
                            {
                                validationResult = ResourceReader.GetString("ERR_LOCATION");
                            }
                            if (TaskConveyor == EnumSimpleCommandConveyorTask.Create ||
                                TaskConveyor == EnumSimpleCommandConveyorTask.Delete)
                            {
                                Target = Source;
                            }
                            break;

                        case "Target":
                            if (Targets != null && !Targets.Any(p => p == Target))
                            {
                                validationResult = ResourceReader.GetString("ERR_LOCATION");
                            }
                            if (TaskConveyor == EnumSimpleCommandConveyorTask.Create ||
                                TaskConveyor == EnumSimpleCommandConveyorTask.Delete)
                            {
                                Source = Target;
                            }
                            break;
                        }
                    }
                    Validator.AddOrUpdate(propertyName, validationResult == String.Empty);
                    AllPropertiesValid = Validator.IsValid();
                    return(validationResult);
                }
                catch (Exception e)
                {
                    _warehouse.AddEvent(Database.Event.EnumSeverity.Error, Database.Event.EnumType.Exception,
                                        string.Format("{0}.{1}: {2}", this.GetType().Name, (new StackTrace()).GetFrame(0).GetMethod().Name, e.Message));
                    Validator.AddOrUpdate(propertyName, false);
                    AllPropertiesValid = Validator.IsValid();
                    return(ResourceReader.GetString("ERR_EXCEPTION"));
                }
            }
        }
예제 #13
0
        protected IEnumerable <SoftwareIdentity> CheckMatchedDuplicates()
        {
            // if there are overmatched packages we need to know why:
            // are they found across multiple providers?
            // are they found accross multiple sources?
            // are they all from the same source?

            foreach (var list in _resultsPerName.Values.Where(each => each != null && each.Any()))
            {
                if (list.Count == 1)
                {
                    //no overmatched
                    yield return(list.FirstOrDefault());
                }
                else
                {
                    //process the overmatched case
                    SoftwareIdentity selectedPackage = null;

                    var providers = list.Select(each => each.ProviderName).Distinct().ToArray();
                    var sources   = list.Select(each => each.Source).Distinct().ToArray();

                    //case: a user specifies -Source and multiple packages are found. In this case to determine which one should be installed,
                    //      We treat the user's package source array is in a priority order, i.e. the first package source has the highest priority.
                    //      Of course, these packages should not be from a single source with the same provider.
                    //      Example: install-package -Source @('src1', 'src2')
                    //               install-package -Source @('src1', 'src2') -Provider @('p1', 'p2')
                    if (Sources.Any() && (providers.Length != 1 || sources.Length != 1))
                    {
                        // let's use the first source as our priority.As long as we find a package, we exit the 'for' loop righ away
                        foreach (var source in Sources)
                        {
                            //select all packages matched source
                            var pkgs = list.Where(package => source.EqualsIgnoreCase(package.Source) || (UserSpecifiedSourcesList.Keys.ContainsIgnoreCase(package.Source) && source.EqualsIgnoreCase(UserSpecifiedSourcesList[package.Source]))).ToArray();
                            if (pkgs.Length == 0)
                            {
                                continue;
                            }
                            if (pkgs.Length == 1)
                            {
                                //only one provider found the package
                                selectedPackage = pkgs[0];
                                break;
                            }
                            if (ProviderName == null)
                            {
                                //user does not specify '-providerName' but we found multiple packages with a source, can not determine which one
                                //will error out
                                break;
                            }
                            if (pkgs.Length > 1)
                            {
                                //case: multiple providers matched the same source.
                                //need to process provider's priority order
                                var pkg = ProviderName.Select(p => pkgs.FirstOrDefault(each => each.ProviderName.EqualsIgnoreCase(p))).FirstOrDefault();
                                if (pkg != null)
                                {
                                    selectedPackage = pkg;
                                    break;
                                }
                            }
                        }//inner foreach

                        //case: a user specifies -Provider array but no -Source and multiple packages are found. In this case to determine which one should be installed,
                        //      We treat the user's package provider array is in a priority order, i.e. the first provider in the array has the highest priority.
                        //      Of course, these packages should not be from a single source with the same provider.
                        //      Example: install-package -Provider @('p1', 'p2')
                    }
                    else if (ProviderName != null && ProviderName.Any() && (providers.Length != 1 || sources.Length != 1))
                    {
                        foreach (var providerName in ProviderName)
                        {
                            //select all packages matched with the provider name
                            var packages = list.Where(each => providerName.EqualsIgnoreCase(each.ProviderName)).ToArray();
                            if (packages.Length == 0)
                            {
                                continue;
                            }
                            if (packages.Length == 1)
                            {
                                //only one provider found the package, that's good
                                selectedPackage = packages[0];
                                break;
                            }
                            else
                            {
                                //user does not specify '-source' but we found multiple packages with one provider, we can not determine which one
                                //will error out
                                break;
                            }
                        }
                    }

                    if (selectedPackage != null)
                    {
                        yield return(selectedPackage);
                    }
                    else
                    {
                        //error out for the overmatched case
                        var suggestion = "";
                        if (providers.Length == 1)
                        {
                            // it's matching this package multiple times in the same provider.
                            if (sources.Length == 1)
                            {
                                // matching it from a single source.
                                // be more exact on matching name? or version?
                                suggestion = Resources.Messages.SuggestRequiredVersion;
                            }
                            else
                            {
                                // it's matching the same package from multiple sources
                                // tell them to use -source
                                suggestion = Resources.Messages.SuggestSingleSource;
                            }
                        }
                        else
                        {
                            // found across multiple providers
                            // must specify -provider
                            suggestion = Resources.Messages.SuggestSingleProviderName;
                        }

                        string searchKey = null;

                        foreach (var pkg in list)
                        {
                            Warning(Constants.Messages.MatchesMultiplePackages, pkg.SearchKey, pkg.ProviderName, pkg.Name, pkg.Version, GetPackageSourceNameOrLocation(pkg));
                            searchKey = pkg.SearchKey;
                        }
                        Error(Constants.Errors.DisambiguateForInstall, searchKey, GetMessageString(suggestion, suggestion));
                    }
                }
            }
        }
 public virtual bool IsSource(MethodDefinition methodDefinition)
 {
     return(methodDefinition.GetAllDocuments()
            .Any(d => Sources.Any(s => s.FullName == d.Url)));
 }
예제 #15
0
        public override bool Execute()
        {
            if (String.IsNullOrEmpty(GCCToolCompilerPath))
            {
                GCCToolCompilerPath = "";
            }
            if (String.IsNullOrEmpty(IntPath))
            {
                IntPath = "";
            }

            if (!Sources.Any())
            {
                return(true);
            }

            GCCToolCompilerPathCombined = GCCToolCompilerPath;

            shellApp = new ShellAppConversion(GCCBuild_SubSystem, GCCBuild_ShellApp, GCCBuild_PreRunApp, GCCBuild_ConvertPath, GCCBuild_ConvertPath_mntFolder, IntPath);

            if (OS.Equals("Windows_NT") && String.IsNullOrWhiteSpace(shellApp.shellapp))
            {
                GCCToolCompilerPathCombined = FixAppPath(GCCToolCompilerPathCombined, GCCToolCompilerExe);
            }
            else
            {
                GCCToolCompilerPathCombined = Path.Combine(GCCToolCompilerPath, GCCToolCompilerExe);
            }


            Logger.Instance = new XBuildLogProvider(Log); // TODO: maybe initialise statically

            // load or create tracker file
            string trackerFile = Path.Combine(IntPath, Path.GetFileNameWithoutExtension(ProjectFile) + ".tracker");

            try
            {
                if (File.Exists(trackerFile))
                {
                    XElement rootElement = XElement.Parse(File.ReadAllText(trackerFile));
                    foreach (var el in rootElement.Elements())
                    {
                        dependencyDict.TryAdd(el.Attribute("Object").Value, el.Value.Split(';').ToList());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage($"Accessing .tracker file caused an exception! {ex}");
                //just ignore it is ok!
            }

            var objectFiles       = new List <string>();
            var compilationResult = System.Threading.Tasks.Parallel.ForEach(Sources.Select(x => x),
                                                                            new System.Threading.Tasks.ParallelOptions {
                MaxDegreeOfParallelism = Parallel ? -1 : 1
            }, (source, loopState) =>
            {
                string objectFile;

                if (!Compile(source, out objectFile))
                {
                    loopState.Break();
                }

                lock (objectFiles)
                {
                    objectFiles.Add(objectFile);
                }
            });

            if (dependencyDict.Count > 0)
            {
                try
                {
                    XElement el = new XElement("root",
                                               dependencyDict.Select(kv =>
                    {
                        var x = new XElement("File", String.Join(";", kv.Value));
                        x.Add(new XAttribute("Object", kv.Key));
                        return(x);
                    }));
                    File.WriteAllText(trackerFile, el.ToString());
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogMessage($"Writing to .tracker file caused an exception! {ex}");
                }
            }

            if (compilationResult.LowestBreakIteration != null)
            {
                return(false);
            }

            ObjectFiles = objectFiles.Any() ? objectFiles.Select(x => new TaskItem(Utilities.MakeRelative(x, Environment.CurrentDirectory + Path.DirectorySeparatorChar))).ToArray() : new TaskItem[0];

            return(true);
        }
예제 #16
0
 public virtual bool IsSource(string file)
 {
     return(Sources.Any(s => s.FullName == file));
 }
예제 #17
0
        /// <summary>
        /// Returns the collection of argument strings defined by this instance.
        /// </summary>
        public IEnumerable <string> GetArguments()
        {
            if (string.IsNullOrEmpty(ProjectPath))
            {
                throw new ArgumentNullException(nameof(ProjectPath), "ProjectPath must be specified!");
            }

            yield return("restore");

            yield return($"\"{ProjectPath}\"");

            if (!string.IsNullOrEmpty(ConfigFile))
            {
                yield return($"-ConfigFile \"{ConfigFile}\"");
            }

            if (DirectDownload)
            {
                yield return("-DirectDownload");
            }

            if (DisableParallelProcessing)
            {
                yield return("-DisableParallelProcessing");
            }

            if (FallbackSources?.Any() ?? false)
            {
                yield return($"-FallbackSource \"{string.Join(";", FallbackSources)}\"");
            }

            if (ForceEnglishOutput)
            {
                yield return("-ForceEnglishOutput");
            }

            if (!string.IsNullOrEmpty(MSBuildPath))
            {
                yield return($"-MSBuildPath \"{MSBuildPath}\"");
            }

            if (!string.IsNullOrEmpty(MSBuildVersion))
            {
                yield return($"-MSBuildVersion \"{MSBuildVersion}\"");
            }

            if (NoCache)
            {
                yield return("-NoCache");
            }

            if (NonInteractive)
            {
                yield return("-NonInteractive");
            }

            if (!string.IsNullOrEmpty(OutputDirectory))
            {
                yield return($"-OutputDirectory \"{OutputDirectory}\"");
            }

            if (PackageSaveMode != PackageSaveModes.Nupkg)
            {
                yield return($"-PackageSaveMode \"{GetPackageSaveMode()}\"");
            }

            if (!string.IsNullOrEmpty(PackagesDirectory))
            {
                yield return($"-PackagesDirectory \"{PackagesDirectory}\"");
            }

            if (Project2ProjectTimeOut > 0)
            {
                yield return($"-Project2ProjectTimeOut {Project2ProjectTimeOut}");
            }

            if (Recursive)
            {
                yield return("-Recursive");
            }

            if (RequireConsent)
            {
                yield return("-RequireConsent");
            }

            if (!string.IsNullOrEmpty(SolutionDirectory))
            {
                yield return($"-SolutionDirectory \"{SolutionDirectory}\"");
            }

            if (Sources?.Any() ?? false)
            {
                yield return($"-Source \"{string.Join(";", Sources)}\"");
            }

            if (Verbosity != NuGetVerbosity.Normal)
            {
                yield return($"-Verbosity \"{GetVerbosityString()}\"");
            }

            foreach (var arg in AdditionalArguments)
            {
                yield return(arg);
            }
        }