Пример #1
0
        /// <summary>
        ///     Adds the assembly reference.
        /// </summary>
        /// <param name="assemblyPath">The assembly path.</param>
        public void AddAssemblyReference(string assemblyPath)
        {
            Guard.ArgumentNotNullOrEmptyString(assemblyPath, "assemblyPath");

            if (VsProject != null)
            {
                if (VsProject.Object is VSProject project)
                {
                    References references = project.References;
                    references?.Add(assemblyPath);
                }
                else
                {
                    AssemblyReferences references = (VsProject.Object as VSWebSite)?.References;

                    if (references != null)
                    {
                        if (System.IO.Path.IsPathRooted(assemblyPath))
                        {
                            references.AddFromFile(assemblyPath);
                        }
                        else
                        {
                            references.AddFromGAC(assemblyPath);
                        }
                    }
                }
            }
        }
Пример #2
0
        private void ReadDirStream()
        {
            byte[]            dir           = CompoundDocument.DecompressPart(Document.Storage.SubStorage["VBA"].DataStreams["dir"]);
            MemoryStream      ms            = new MemoryStream(dir);
            BinaryReader      br            = new BinaryReader(ms);
            ExcelVbaReference currentRef    = null;
            string            referenceName = "";
            ExcelVBAModule    currentModule = null;
            bool terminate = false;

            while (br.BaseStream.Position < br.BaseStream.Length && terminate == false)
            {
                ushort id   = br.ReadUInt16();
                uint   size = br.ReadUInt32();
                switch (id)
                {
                case 0x01:
                    SystemKind = (eSyskind)br.ReadUInt32();
                    break;

                case 0x02:
                    Lcid = (int)br.ReadUInt32();
                    break;

                case 0x03:
                    CodePage = (int)br.ReadUInt16();
                    break;

                case 0x04:
                    Name = GetString(br, size);
                    break;

                case 0x05:
                    Description = GetUnicodeString(br, size);
                    break;

                case 0x06:
                    HelpFile1 = GetString(br, size);
                    break;

                case 0x3D:
                    HelpFile2 = GetString(br, size);
                    break;

                case 0x07:
                    HelpContextID = (int)br.ReadUInt32();
                    break;

                case 0x08:
                    LibFlags = (int)br.ReadUInt32();
                    break;

                case 0x09:
                    MajorVersion = (int)br.ReadUInt32();
                    MinorVersion = (int)br.ReadUInt16();
                    break;

                case 0x0C:
                    Constants = GetUnicodeString(br, size);
                    break;

                case 0x0D:
                    uint sizeLibID = br.ReadUInt32();
                    var  regRef    = new ExcelVbaReference();
                    regRef.Name = referenceName;
                    regRef.ReferenceRecordID = id;
                    regRef.Libid             = GetString(br, sizeLibID);
                    uint   reserved1 = br.ReadUInt32();
                    ushort reserved2 = br.ReadUInt16();
                    References.Add(regRef);
                    break;

                case 0x0E:
                    var projRef = new ExcelVbaReferenceProject();
                    projRef.ReferenceRecordID = id;
                    projRef.Name          = referenceName;
                    sizeLibID             = br.ReadUInt32();
                    projRef.Libid         = GetString(br, sizeLibID);
                    sizeLibID             = br.ReadUInt32();
                    projRef.LibIdRelative = GetString(br, sizeLibID);
                    projRef.MajorVersion  = br.ReadUInt32();
                    projRef.MinorVersion  = br.ReadUInt16();
                    References.Add(projRef);
                    break;

                case 0x0F:
                    ushort modualCount = br.ReadUInt16();
                    break;

                case 0x13:
                    ushort cookie = br.ReadUInt16();
                    break;

                case 0x14:
                    LcidInvoke = (int)br.ReadUInt32();
                    break;

                case 0x16:
                    referenceName = GetUnicodeString(br, size);
                    break;

                case 0x19:
                    currentModule      = new ExcelVBAModule();
                    currentModule.Name = GetUnicodeString(br, size);
                    Modules.Add(currentModule);
                    break;

                case 0x1A:
                    currentModule.streamName = GetUnicodeString(br, size);
                    break;

                case 0x1C:
                    currentModule.Description = GetUnicodeString(br, size);
                    break;

                case 0x1E:
                    currentModule.HelpContext = (int)br.ReadUInt32();
                    break;

                case 0x21:
                case 0x22:
                    break;

                case 0x2B:          //Modul Terminator
                    break;

                case 0x2C:
                    currentModule.Cookie = br.ReadUInt16();
                    break;

                case 0x31:
                    currentModule.ModuleOffset = br.ReadUInt32();
                    break;

                case 0x10:
                    terminate = true;
                    break;

                case 0x30:
                    var extRef  = (ExcelVbaReferenceControl)currentRef;
                    var sizeExt = br.ReadUInt32();
                    extRef.LibIdExternal = GetString(br, sizeExt);

                    uint   reserved4 = br.ReadUInt32();
                    ushort reserved5 = br.ReadUInt16();
                    extRef.OriginalTypeLib = new Guid(br.ReadBytes(16));
                    extRef.Cookie          = br.ReadUInt32();
                    break;

                case 0x33:
                    currentRef = new ExcelVbaReferenceControl();
                    currentRef.ReferenceRecordID = id;
                    currentRef.Name  = referenceName;
                    currentRef.Libid = GetString(br, size);
                    References.Add(currentRef);
                    break;

                case 0x2F:
                    var contrRef = (ExcelVbaReferenceControl)currentRef;
                    contrRef.ReferenceRecordID = id;

                    var sizeTwiddled = br.ReadUInt32();
                    contrRef.LibIdTwiddled = GetString(br, sizeTwiddled);
                    var r1 = br.ReadUInt32();
                    var r2 = br.ReadUInt16();

                    break;

                case 0x25:
                    currentModule.ReadOnly = true;
                    break;

                case 0x28:
                    currentModule.Private = true;
                    break;

                default:
                    break;
                }
            }
        }
Пример #3
0
 public void Connect(IConnectable target)
 {
     References.Add((ITransformable)target);
 }
 virtual public void Awake()
 {
     references = GameObject.Find("References").GetComponent <References>() as References;
     references.Add(this.GetType().Name, this);
 }
Пример #5
0
        private void Load()
        {
            var projectPath = LocalPath;
            var projectDir  = Path.GetDirectoryName(projectPath);

            var splitOptions     = StringSplitOptions.RemoveEmptyEntries;
            var setupInformation = AppDomain.CurrentDomain.SetupInformation;

            // Always null, why? probing path is set in vvvv.exe.config
            // var searchPath = AppDomain.CurrentDomain.RelativeSearchPath;
            ReferencePaths = new List <string>()
            {
                Path.GetFullPath(Path.Combine(setupInformation.ApplicationBase, "lib", "core")),
                Path.GetFullPath(Path.Combine(setupInformation.ApplicationBase, "lib", "nodes", "plugins"))
            };

            try
            {
                var msBuildProject        = MsProject;
                var referencePathProperty = msBuildProject.GetPropertyValue("ReferencePath");
                if (!string.IsNullOrEmpty(referencePathProperty))
                {
                    foreach (var refPath in referencePathProperty.Split(FSplitChars, splitOptions))
                    {
                        var trimmedRefPath = refPath.Trim();
                        trimmedRefPath = refPath.TrimEnd(Path.DirectorySeparatorChar);
                        var absoluteRefPath = Path.IsPathRooted(trimmedRefPath)
                            ? trimmedRefPath
                            : Path.Combine(projectDir, trimmedRefPath);
                        try
                        {
                            absoluteRefPath = Path.GetFullPath(absoluteRefPath);
                            if (!ReferencePaths.Contains(absoluteRefPath) && Directory.Exists(absoluteRefPath))
                            {
                                ReferencePaths.Add(absoluteRefPath);
                            }
                        }
                        catch (NotSupportedException)
                        {
                            // Ignore
                        }
                    }
                }

                // Iterate through the various itemgroups
                // and subsequently through the items
                foreach (var projectItem in msBuildProject.Items)
                {
                    switch (projectItem.ItemType)
                    {
                    case "Reference":
                        IReference reference = null;

                        var include = projectItem.EvaluatedInclude;
                        if (include == "System.ComponentModel.Composition")
                        {
                            include = "System.ComponentModel.Composition.Codeplex";
                        }

                        if (projectItem.HasMetadata("HintPath"))
                        {
                            var hintPath         = projectItem.GetMetadataValue("HintPath");
                            var assemblyLocation = hintPath;
                            if (!Path.IsPathRooted(assemblyLocation))
                            {
                                assemblyLocation = projectDir.ConcatPath(hintPath);
                            }

                            if (!File.Exists(assemblyLocation))
                            {
                                //search in reference paths
                                assemblyLocation = TryAddReferencePath(assemblyLocation, include);
                            }

                            if (File.Exists(assemblyLocation))
                            {
                                assemblyLocation = Path.GetFullPath(assemblyLocation);
                            }

                            reference = new AssemblyReference(assemblyLocation);
                        }
                        else
                        {
                            var assemblyLocation = TryAddReferencePath("", include);
                            if (File.Exists(assemblyLocation))
                            {
                                reference = new AssemblyReference(assemblyLocation, true);
                            }
                        }


                        // Reference couldn't be found, try GAC
                        if (reference == null)
                        {
                            try
                            {
                                var assemblyLocation = AssemblyCache.QueryAssemblyInfo(include);
                                reference = new AssemblyReference(assemblyLocation, true);
                            }
                            catch (Exception)
                            {
                                reference = new AssemblyReference(string.Format("{0}.dll", include), true);
                            }
                        }

                        if (reference != null)
                        {
                            References.Add(reference);
                        }
                        break;

                    case "ProjectReference":
                        // TODO: Load project references.
                        break;

                    case "Compile":
                    case "None":
                        IDocument document      = null;
                        var       canBeCompiled = projectItem.ItemType == "Compile";
                        var       documentPath  = projectDir.ConcatPath(projectItem.EvaluatedInclude);
                        if (!File.Exists(documentPath))
                        {
                            document = new MissingDocument(documentPath, documentPath, canBeCompiled);
                        }
                        else
                        {
                            FDocumentConverter.Convert(documentPath, out document);
                        }
                        if (document != null)
                        {
                            Documents.Add(document);
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Shell.Instance.Logger.Log(e);
            }
        }
Пример #6
0
        /// <summary>
        /// 외부 참조를 추가합니다.
        /// </summary>
        /// <param name="path">외부 참조 파일의 경로입니다.</param>
        public void LoadReference(string path)
        {
            if (!IsNameContains(References, path))
            {
                // 참조 추가
                References.Add(path);
                LoadedReferences.Add(path);

                // 참조의 종속성 검사
                foreach (AssemblyName assembly in Assembly.LoadFrom(path).GetReferencedAssemblies())
                {
                    // 참조 종속성 검사
                    string referencesName = null;
                    string dllPath        = string.Format(@"{0}\{1}.dll", Path.GetDirectoryName(path), assembly.Name);
                    if (File.Exists(dllPath))
                    {
                        // 동일 경로에 존재
                        referencesName = dllPath;
                    }
                    else
                    {
                        // 동일 경로에 없음
                        // 외부 종속성 중복 검사
                        if ((from callingAssembly
                             in Assembly.GetCallingAssembly().GetReferencedAssemblies()
                             select callingAssembly.Name).Contains(assembly.Name))
                        {
                            continue;
                        }

                        // 글로벌 캐시에 존재 여부 검사
                        string[] dllGAC =
                            Directory.GetFiles
                            (
                                Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\assembly", assembly.Name + ".dll",
                                SearchOption.AllDirectories
                            );
                        dllGAC = dllGAC.Where(dll => dll.IndexOf(GetPublicKeyToken(assembly)) != -1).ToArray();

                        if (dllGAC.Length > 0)
                        {
                            // 글로벌 캐시에 존재
                            // 시스템에 맞는 파일 검색
                            if (dllGAC.Length == 1)
                            {
                                referencesName = dllGAC.First();
                            }
                            else
                            {
                                referencesName = dllGAC.Where(dll => dll.IndexOf(Environment.Is64BitOperatingSystem ? "GAC_64" : "GAC_32") != -1).First();
                            }
                        }
                        else
                        {
                            referencesName = assembly.Name + ".dll";
                        }
                    }

                    // 참조의 종속성을 추가
                    if (!IsNameContains(References, referencesName))
                    {
                        References.Add(referencesName);
                    }
                }
            }
        }
Пример #7
0
        public Unit(XDocument xdoc, World world)
            : base(xdoc, world)
        {
            foreach (var element in xdoc.Root.Elements())
            {
                var val = element.Value.Trim();
                int valI;
                int.TryParse(val, out valI);
                switch (element.Name.LocalName)
                {
                case "id":
                    break;

                case "name":
                    Name = val;
                    break;

                case "name2":
                    AltName = val;
                    break;

                case "profession":
                    if (!JobTypes.Contains(val))
                    {
                        JobTypes.Add(val);
                    }
                    ProfessionId = JobTypes.IndexOf(val);
                    break;

                case "profession2":
                    if (!JobTypes.Contains(val))
                    {
                        JobTypes.Add(val);
                    }
                    Profession2Id = JobTypes.IndexOf(val);
                    break;

                case "race":
                    if (valI != -1)
                    {
                        Race = World.GetAddRace(val);
                    }
                    break;

                case "caste":
                    if (valI != -1)
                    {
                        if (!HistoricalFigure.Castes.Contains(val))
                        {
                            HistoricalFigure.Castes.Add(val);
                        }
                        CasteID = HistoricalFigure.Castes.IndexOf(val);
                    }
                    break;

                case "coords":
                    Coords = new Point3(
                        Convert.ToInt32(val.Split(',')[0]),
                        Convert.ToInt32(val.Split(',')[1]),
                        Convert.ToInt32(val.Split(',')[2]));
                    break;

                case "sex":
                    Sex = valI;
                    break;

                case "civ_id":
                    if (valI != -1)
                    {
                        CivID = valI;
                    }
                    break;

                case "population_id":
                    if (valI != -1)
                    {
                        PopID = valI;
                    }
                    break;

                case "squad_id":
                    if (valI != -1)
                    {
                        SquadID = valI;
                    }
                    break;

                case "opponent_id":
                    if (valI != -1)
                    {
                        OpponentID = valI;
                    }
                    break;

                case "mood":
                    Mood = valI;
                    break;

                case "hist_figure_id":
                    if (valI != -1)
                    {
                        HistFigureID = valI;
                    }
                    break;

                case "hist_figure_id2":
                    if (valI != -1)
                    {
                        HistFigureID2 = valI;
                    }
                    break;

                case "labors":
                    var labors = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var labor in labors)
                    {
                        if (!Labors.Contains(labor))
                        {
                            Labors.Add(labor);
                        }
                        if (Labor == null)
                        {
                            Labor = new List <short>();
                        }
                        Labor.Add((short)Labors.IndexOf(labor));
                    }
                    break;

                case "flags":
                    var flags = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var flag in flags)
                    {
                        if (!Flags.Contains(flag))
                        {
                            Flags.Add(flag);
                        }
                        if (Flag == null)
                        {
                            Flag = new List <short>();
                        }
                        Flag.Add((short)Flags.IndexOf(flag));
                    }
                    break;

                case "health":
                    var healthflags = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var healthflag in healthflags)
                    {
                        if (!HealthFlags.Contains(healthflag))
                        {
                            HealthFlags.Add(healthflag);
                        }
                        if (HealthFlag == null)
                        {
                            HealthFlag = new List <short>();
                        }
                        HealthFlag.Add((short)HealthFlags.IndexOf(healthflag));
                    }
                    break;

                case "used_items":
                    UsedItemIds = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    break;

                case "owned_items":
                    OwnedItemIds = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    break;

                case "owned_buildings":
                    OwnedBuildingIds = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    break;

                case "traded_items":
                    TradedItemIds = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    break;

                case "inventory":
                    foreach (var inv in element.Elements())
                    {
                        if (InventoryItems == null)
                        {
                            InventoryItems = new List <UnitInventoryItem>();
                        }
                        InventoryItems.Add(new UnitInventoryItem(new XDocument(inv), world));
                    }
                    break;

                case "reference":
                    if (References == null)
                    {
                        References = new List <Reference>();
                    }
                    References.Add(new Reference(element, this));
                    break;

                case "in_item_id":
                case "nestbox_id":
                case "civzone_id":
                    break;

                case "nemesis_id":     // Relations with HFs
                case "pregnancy_spouse":
                case "following_unit":
                case "pet_owner_id":
                case "spouse_id":
                case "mother_id":
                case "father_id":
                case "last_attacker_id":
                case "group_leader_id":
                case "draggee_id":
                case "dragger_id":
                case "rider_mount_id":
                case "lover_id":
                    if (valI != -1)
                    {
                        if (RelationIDs == null)
                        {
                            RelationIDs = new Dictionary <string, int>();
                        }
                        RelationIDs.Add(string.Join(" ", element.Name.LocalName.Split('_').Reverse().Skip(1).Reverse().ToArray()), valI);
                    }
                    break;

                case "pregnancy_timer":
                case "pregnancy_caste":
                case "mood_copy":
                case "anon_1":
                case "birth_year":
                case "birth_time":
                case "curse_year":
                case "curse_time":
                case "birth_year_bias":
                case "birth_time_bias":
                case "old_year":
                case "old_time":
                case "unk_238":
                case "mount_type":
                    break;

                default:
                    DFXMLParser.UnexpectedXmlElement(xdoc.Root.Name.LocalName, element, xdoc.Root.ToString());
                    break;
                }
            }
        }
Пример #8
0
    public AsmDefCSharpProgram(AsmDefDescription asmDefDescription)
        : base(asmDefDescription.Directory,
               asmDefDescription.IncludedAsmRefs.Select(asmref => asmref.Path.Parent),
               deferConstruction: true)
    {
        AsmDefDescription = asmDefDescription;

        var asmDefReferences = AsmDefDescription.References.Select(asmDefDescription1 => BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(asmDefDescription1)).ToList();
        var isExe            = asmDefDescription.DefineConstraints.Contains("UNITY_DOTS_ENTRYPOINT") || asmDefDescription.Name.EndsWith(".Tests");

        Construct(asmDefDescription.Name, isExe);

        ProjectFile.AdditionalFiles.Add(asmDefDescription.Path);

        IncludePlatforms = AsmDefDescription.IncludePlatforms;
        ExcludePlatforms = AsmDefDescription.ExcludePlatforms;
        Unsafe           = AsmDefDescription.AllowUnsafeCode;
        References.Add(config =>
        {
            if (config is DotsRuntimeCSharpProgramConfiguration dotsConfig)
            {
                if (dotsConfig.TargetFramework == TargetFramework.Tiny)
                {
                    return(asmDefReferences.Where(rp => rp.IsSupportedFor(dotsConfig) && !IncompatibleTinyBCLAsmDefs.Contains(rp.FileName)));
                }
                else
                {
                    return(asmDefReferences.Where(rp => rp.IsSupportedFor(dotsConfig)));
                }
            }

            //this codepath will be hit for the bindgem invocation
            return(asmDefReferences);
        });

        if (AsmDefDescription.IsTinyRoot || isExe)
        {
            AsmDefCSharpProgramCustomizer.RunAllAddPlatformImplementationReferences(this);
        }

        if (BuildProgram.UnityTinyBurst != null)
        {
            References.Add(BuildProgram.UnityTinyBurst);
        }
        if (BuildProgram.ZeroJobs != null)
        {
            References.Add(BuildProgram.ZeroJobs);
        }
        if (BuildProgram.UnityLowLevel != null)
        {
            References.Add(BuildProgram.UnityLowLevel);
        }
        if (BuildProgram.TinyIO != null)
        {
            References.Add(BuildProgram.TinyIO);
        }

        // Add in any precompiled references found in the asmdef directory or sub-directory
        foreach (var pcr in asmDefDescription.PrecompiledReferences)
        {
            var files = asmDefDescription.Path.Parent.Files(pcr, true);
            if (files.Any())
            {
                References.Add(files);
            }
        }

        if (IsTestAssembly)
        {
            var nunitLiteMain = BuildProgram.BeeRoot.Combine("CSharpSupport/NUnitLiteMain.cs");
            Sources.Add(nunitLiteMain);

            // Setup for IL2CPP
            var tinyTestFramework = BuildProgram.BeeRoot.Parent.Combine("TinyTestFramework");
            Sources.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.TinyIl2cpp || ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework == TargetFramework.Tiny, tinyTestFramework);
            Defines.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.TinyIl2cpp || ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework == TargetFramework.Tiny, "UNITY_PORTABLE_TEST_RUNNER");

            // Setup for dotnet
            References.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.Dotnet && ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework != TargetFramework.Tiny, BuildProgram.NUnitFramework);
            ProjectFile.AddCustomLinkRoot(nunitLiteMain.Parent, "TestRunner");
            References.Add(c => ((DotsRuntimeCSharpProgramConfiguration)c).ScriptingBackend == ScriptingBackend.Dotnet && ((DotsRuntimeCSharpProgramConfiguration)c).TargetFramework != TargetFramework.Tiny, BuildProgram.NUnitLite);

            // General setup
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Entities")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Tiny.Core")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Tiny.UnityInstance")));
            References.Add(BuildProgram.GetOrMakeDotsRuntimeCSharpProgramFor(AsmDefConfigFile.AsmDefDescriptionFor("Unity.Collections")));
        }
        else if (IsILPostProcessorAssembly)
        {
            References.Add(BuildProgram.UnityCompilationPipeline);
            References.Add(MonoCecil.Paths);
            References.Add(Il2Cpp.Distribution.Path.Combine("build/deploy/net471/Unity.Cecil.Awesome.dll"));
        }
    }
Пример #9
0
 public void AddReference(YumlClass @class)
 {
     References.Add(@class);
 }
Пример #10
0
        public void AddReference(string path)
        {
            Guard.AgainstNullArgument("path", path);

            References.Add(path);
        }
Пример #11
0
        private void ParseProjectOutput()
        {
            ProjectOutputList           items          = ProjectOutput;
            SortedFileList <bool>       localCopyItems = new SortedFileList <bool>();
            SortedFileList <TargetType> keys           = new SortedFileList <TargetType>();

            ProjectOutput.BaseDirectory  = ProjectPath;
            localCopyItems.BaseDirectory = ProjectPath;
            keys.BaseDirectory           = ProjectPath;

            SortedList <string, bool> copyKeys = new SortedList <string, bool>();

            foreach (string v in GetParameters("SharedItems", Parameters.SharedItems, ""))
            {
                if (!keys.ContainsKey(v))
                {
                    keys.Add(v, TargetType.SharedItem);
                }
            }

            foreach (string v in GetParameters("LocalItems", Parameters.LocalItems, ""))
            {
                if (!keys.ContainsKey(v))
                {
                    keys.Add(v, TargetType.Item);
                }
            }

            foreach (string v in GetParameters("CopyItems", Parameters.LocalItems, "None;Compile;Content;EmbeddedResource"))
            {
                if (!copyKeys.ContainsKey(v))
                {
                    copyKeys.Add(v, true);
                }
            }

            string primaryTarget = QQnPath.Combine(OutputPath, TargetName + TargetExt);
            string itemTarget    = primaryTarget;

            items.Add(new TargetItem(itemTarget, QQnPath.Combine(IntermediateOutputPath, TargetName + TargetExt), TargetType.Item));

            if (BuildProperties.ContainsKey("_SGenDllCreated") && GetProperty("_SGenDllCreated") == "true" && BuildProperties.ContainsKey("_SGenDllName"))
            {
                string dllName = GetProperty("_SGenDllName");
                itemTarget = QQnPath.Combine(OutputPath, dllName);
                items.Add(new TargetItem(itemTarget, QQnPath.Combine(IntermediateOutputPath, dllName), TargetType.Item));
            }

            if (BuildProperties.ContainsKey("_DebugSymbolsProduced") && GetProperty("_DebugSymbolsProduced") == "true")
            {
                string pdbName = GetProperty("TargetName") + ".pdb";
                DebugSrc   = pdbName;
                itemTarget = QQnPath.Combine(OutputPath, pdbName);
                items.Add(new TargetItem(itemTarget, QQnPath.Combine(IntermediateOutputPath, pdbName), TargetType.Item));
            }

            foreach (ProjectItem pi in BuildItems)
            {
                if (string.IsNullOrEmpty(pi.Include))
                {
                    continue;
                }

                TargetType type = TargetType.None;
                switch (pi.Name)
                {
                // TODO: Rewrite to a per-language infrastructure
                case "IntermediateAssembly":
                case "AddModules":
                case "DocFileItem":
                case "IntermediateSatelliteAssembliesWithTargetPath":
                    type = TargetType.Item;

                    break;

                case "ContentWithTargetPath":
                case "AllItemsFullPathWithTargetPath":
                case "ReferenceCopyLocal":
                    string condition;
                    if (pi.TryGetMetaData("CopyToOutputDirectory", out condition))
                    {
                        switch (condition)
                        {
                        case "Always":
                        case "PreserveNewest":
                            type = TargetType.SharedCopy;
                            break;

                        default:
                            break;
                        }
                    }
                    if (type == TargetType.None)
                    {
                        goto default;
                    }
                    break;

                case "ReferenceComWrappersToCopyLocal":
                case "ResolvedIsolatedComModules":
                case "_DeploymentLooseManifestFile":
                case "ReferenceCopyLocalPaths":
                case "NativeReferenceFile":
                    string fusionName = pi.GetMetadata("FusionName");
                    if (!string.IsNullOrEmpty(fusionName))
                    {
                        References.Add(new AssemblyReference(fusionName, pi, this));
                    }

                    type = TargetType.SharedItem;
                    break;

                default:
                    if (!keys.TryGetValue(pi.Name, out type))
                    {
                        type = TargetType.None;
                    }
                    break;
                }

                if (type != TargetType.None)
                {
                    string target = CalculateTarget(pi);

                    if (!items.ContainsKey(target))
                    {
                        items.Add(new TargetItem(EnsureRelativePath(target), EnsureRelativePath(pi.Include), type, pi));
                    }
                }

                if (copyKeys.ContainsKey(pi.Name))
                {
                    string copyCondition;
                    if (pi.TryGetMetaData("CopyToOutputDirectory", out copyCondition))
                    {
                        switch (copyCondition)
                        {
                        case "Always":
                        case "PreserveNewest":
                        {
                            localCopyItems[pi.Include] = true;
                        }
                        break;
                        }
                    }
                }
            }

            foreach (TargetItem ti in items.Values)
            {
                if (ti.Type == TargetType.SharedCopy)
                {
                    if (localCopyItems.ContainsKey(ti.Include))
                    {
                        ti.Type = TargetType.Copy;
                    }
                }
            }
        }
Пример #12
0
 public void AddReference(IAssemblyReference reference)
 {
     References.Add(reference);
     ProjectContent.AddAssemblyReferences(new[] { reference });
 }
Пример #13
0
        protected void ResolveAdditionalOutput(Assembly asm)
        {
            List <string> searchPaths = new List <string>();

            searchPaths.Add(GetFullPath(TargetPath));
            List <string> candidates = new List <string>();

            List <ITaskItem>            assemblyFiles = new List <ITaskItem>();
            SortedList <string, string> refAssemblies = new SortedList <string, string>(StringComparer.Ordinal);

            foreach (AssemblyName a in asm.GetReferencedAssemblies())
            {
                refAssemblies.Add(a.Name, a.FullName);
            }

            ITaskItem targetItem = new SimpleTaskItem(GetFullPath(TargetPath));

            assemblyFiles.Add(targetItem);

            foreach (ProjectItem pi in BuildItems)
            {
                string include = GetFullPath(pi.Include);

                if (File.Exists(include))
                {
                    string path = Path.GetDirectoryName(include);

                    if (!searchPaths.Contains(path))
                    {
                        searchPaths.Add(path);
                    }

                    if (!candidates.Contains(include))
                    {
                        candidates.Add(include);
                    }

                    string name = Path.GetFileNameWithoutExtension(include);
                    if (refAssemblies.ContainsKey(name))
                    {
                        AssemblyName aname    = AssemblyName.GetAssemblyName(include);
                        string       fullName = refAssemblies[name];

                        if (aname.FullName == fullName)
                        {
                            SimpleTaskItem sti = new SimpleTaskItem(include);
                            sti.SetMetadata("Private", "true");                             // Set as Copy local, see Microsoft.Common.targets
                            sti.SetMetadata("FusionName", fullName);                        // Used by writing ResolvedDependencyFiles
                            assemblyFiles.Add(sti);
                            refAssemblies.Remove(name);
                            References.Add(new AssemblyReference(fullName, pi, this));
                        }
                    }
                }

                string origSpec = pi.GetMetadata("OriginalItemSpec");
                if (!string.IsNullOrEmpty(origSpec))
                {
                    ProjectReferences.AddUnique(EnsureRelativePath(origSpec));
                }
            }

            foreach (KeyValuePair <string, string> k in refAssemblies)
            {
                References.Add(new AssemblyReference(k.Value, null, this));
            }

            /*foreach (AssemblyName a in refAssemblies)
             * {
             *      string fileName = a.Name;
             *
             *      string dllPath = GetFullPath(Path.Combine(OutputPath, fileName + ".dll"));
             *      if (File.Exists(dllPath))
             *      {
             *              SimpleTaskItem sti = new SimpleTaskItem(dllPath);
             *              sti.SetMetadata("Private", "true"); // Is a copy local item
             *      }
             * }*/

            if (candidates.Count > 0)
            {
                searchPaths.Clear();
                SetTaskParameter(ResolveReferencesTask, "CandidateAssemblyFiles", candidates.ToArray());
            }

            searchPaths.Insert(0, "{CandidateAssemblyFiles}");
            searchPaths.Add("{HintPathFromItem}");
            searchPaths.Add("{RawFileName}");

            SetTaskParameter(ResolveReferencesTask, "SearchPaths", searchPaths.ToArray());
            SetTaskParameter(ResolveReferencesTask, "FindRelatedFiles", true);
            SetTaskParameter(ResolveReferencesTask, "FindSatellites", true);
            SetTaskParameter(ResolveReferencesTask, "FindSerializationAssemblies", true);

            SetTaskParameter(ResolveReferencesTask, "Silent", true);

            for (int i = 0; i < 2; i++)
            {
                bool local = (i == 0);

                SetTaskParameter(ResolveReferencesTask, "AssemblyFiles", local ? new ITaskItem[] { targetItem } : assemblyFiles.ToArray());
                SetTaskParameter(ResolveReferencesTask, "FindDependencies", !local);

                if (!ResolveReferencesTask.Execute())
                {
                    return;
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "ResolvedFiles"))
                {
                    AddItem(local, TargetType.Item, item);
                }

                if (!local)
                {
                    foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "ResolvedDependencyFiles"))
                    {
                        References.Add(new AssemblyReference(item.GetMetadata("FusionName"), item, this));
                        AddItem(local, TargetType.Item, item);
                    }
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "SatelliteFiles"))
                {
                    AddItem(local, TargetType.Item, item);
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "ScatterFiles"))
                {
                    AddItem(local, TargetType.Item, item);
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "SerializationAssemblyFiles"))
                {
                    AddItem(local, TargetType.Item, item);
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "RelatedFiles"))
                {
                    AddItem(local, TargetType.Item, item);
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "CopyLocalFiles"))
                {
                    AddItem(local, TargetType.Copy, item);
                }

                foreach (ITaskItem item in GetTaskParameter <ITaskItem[]>(ResolveReferencesTask, "FilesWritten"))
                {
                    AddItem(local, TargetType.Copy, item);
                }
            }
        }
Пример #14
0
        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            // Try list of references
            foreach (var reference in References)
            {
                if (string.Compare(Path.GetFileNameWithoutExtension(reference), name.Name, StringComparison.OrdinalIgnoreCase) == 0 &&
                    File.Exists(reference))
                {
                    return(GetAssembly(reference, parameters));
                }
            }

            // Try list of reference paths
            foreach (var referencePath in referencePaths)
            {
                foreach (var extension in assemblyExtensions)
                {
                    var assemblyFile = Path.Combine(referencePath, name.Name + extension);
                    if (File.Exists(assemblyFile))
                    {
                        // Add it as a new reference
                        References.Add(assemblyFile);

                        return(GetAssembly(assemblyFile, parameters));
                    }
                }
            }

            if (WindowsKitsReferenceDirectory != null)
            {
                if (existingWindowsKitsReferenceAssemblies == null)
                {
                    // First time, make list of existing assemblies in windows kits directory
                    existingWindowsKitsReferenceAssemblies = new HashSet <string>();

                    try
                    {
                        foreach (var directory in Directory.EnumerateDirectories(WindowsKitsReferenceDirectory))
                        {
                            existingWindowsKitsReferenceAssemblies.Add(Path.GetFileName(directory));
                        }
                    }
                    catch (Exception) { }
                }

                // Look for this assembly in the Windows SDK directory
                if (existingWindowsKitsReferenceAssemblies.Contains(name.Name))
                {
                    var assemblyFile = Path.Combine(WindowsKitsReferenceDirectory, name.Name, name.Version.ToString(), name.Name + ".winmd");
                    if (File.Exists(assemblyFile))
                    {
                        if (parameters.AssemblyResolver == null)
                        {
                            parameters.AssemblyResolver = this;
                        }

                        return(ModuleDefinition.ReadModule(assemblyFile, parameters).Assembly);
                    }
                }
            }

            if (parameters == null)
            {
                parameters = new ReaderParameters();
            }

            try
            {
                // Check .winmd files as well
                var assembly = SearchDirectoryExtra(name, GetSearchDirectories(), parameters);
                if (assembly != null)
                {
                    return(assembly);
                }

                return(base.Resolve(name, parameters));
            }
            catch (AssemblyResolutionException)
            {
                // Check cache again, ignoring version numbers this time
                foreach (var assembly in assemblyCache)
                {
                    if (assembly.Value.Name.Name == name.Name)
                    {
                        return(assembly.Value);
                    }
                }
                throw;
            }
        }
Пример #15
0
 public void RegisterReference(string path)
 {
     References.Add(path);
     referencePaths.Add(Path.GetDirectoryName(path));
 }
Пример #16
0
 public void AddReference(string reference)
 {
     References.Add(new FakeAssembly(reference));
 }
Пример #17
0
 public void AddReference(IAssemblyReference reference)
 {
     References.Add(reference);
     ProjectContent = ProjectContent.AddAssemblyReferences(References);
 }
Пример #18
0
 public void Reference(ScopeOptions options)
 {
     Thedef !.References.Add(this);
     MarkEnclosed(options);
 }
Пример #19
0
        /// <summary>
        /// Load the project settings for a specific transform file and return it
        /// </summary>
        /// <param name="sourceFile">The full path to the data file</param>
        /// <param name="baseDirectory">The path for the base directory (with a trailing \)</param>
        /// <param name="arguments">Argument list to pass to the returned transform</param>
        /// <param name="project">The context project</param>
        /// <param name="automationObjectName">The name of an automation object supported by the live document. Used
        /// to get a live version of the file stream.</param>
        /// <returns>The transform file name. Existence will have been verified.</returns>
        private string LoadProjectSettings(string sourceFile, string baseDirectory, XsltArgumentList arguments, EnvDTE.Project project, out string automationObjectName)
        {
            Debug.Assert(arguments != null);             // Allocate before call
            string transformFile = null;

            automationObjectName = null;
            string plixProjectSettingsFile = baseDirectory + PlixProjectSettingsFile;

            if (File.Exists(plixProjectSettingsFile))
            {
                // Use the text from the live document if possible
                string          liveText    = null;
                EnvDTE.Document settingsDoc = null;
                try
                {
                    settingsDoc = project.DTE.Documents.Item(plixProjectSettingsFile);
                }
                catch (ArgumentException)
                {
                    // swallow
                }
                catch (InvalidCastException)
                {
                    // swallow
                }
                if (settingsDoc != null)
                {
                    EnvDTE.TextDocument textDoc = settingsDoc.Object("TextDocument") as EnvDTE.TextDocument;
                    if (textDoc != null)
                    {
                        liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                    }
                }
                string sourceFileIdentifier = sourceFile.Substring(baseDirectory.Length);
                PlixLoaderNameTable names   = PlixLoaderSchema.Names;
                using (FileStream plixSettingsStream = (liveText == null) ? new FileStream(plixProjectSettingsFile, FileMode.Open, FileAccess.Read) : null)
                {
                    using (XmlTextReader settingsReader = new XmlTextReader((liveText == null) ? new StreamReader(plixSettingsStream) as TextReader : new StringReader(liveText), names))
                    {
                        using (XmlReader reader = XmlReader.Create(settingsReader, PlixLoaderSchema.ReaderSettings))
                        {
                            References references = null;
                            bool       finished   = false;
                            while (!finished && reader.Read())
                            {
                                if (reader.NodeType == XmlNodeType.Element)
                                {
                                    if (!reader.IsEmptyElement)
                                    {
                                        while (reader.Read())
                                        {
                                            XmlNodeType nodeType = reader.NodeType;
                                            if (nodeType == XmlNodeType.Element)
                                            {
                                                Debug.Assert(XmlUtility.TestElementName(reader.LocalName, names.SourceFileElement));                                                 // Only value allowed by the validating loader
                                                string testFileName = reader.GetAttribute(names.FileAttribute);
                                                if (0 == string.Compare(testFileName, sourceFileIdentifier, true, CultureInfo.CurrentCulture))
                                                {
                                                    finished = true;                                                     // Stop looking
                                                    string attrValue = reader.GetAttribute(names.TransformFileAttribute);
                                                    if (attrValue != null && attrValue.Length != 0)
                                                    {
                                                        transformFile = baseDirectory + attrValue;
                                                    }
                                                    attrValue = reader.GetAttribute(names.LiveDocumentObjectAttribute);
                                                    if (attrValue != null && attrValue.Length != 0)
                                                    {
                                                        automationObjectName = attrValue;
                                                    }
                                                    if (!reader.IsEmptyElement)
                                                    {
                                                        while (reader.Read())
                                                        {
                                                            nodeType = reader.NodeType;
                                                            if (nodeType == XmlNodeType.Element)
                                                            {
                                                                string localName = reader.LocalName;
                                                                if (XmlUtility.TestElementName(localName, names.TransformParameterElement))
                                                                {
                                                                    // Add an argument for the transform
                                                                    arguments.AddParam(reader.GetAttribute(names.NameAttribute), "", reader.GetAttribute(names.ValueAttribute));
                                                                }
                                                                else if (XmlUtility.TestElementName(localName, names.ExtensionClassElement))
                                                                {
                                                                    // Load an extension class and associate it with an extension namespace
                                                                    // used by the transform
                                                                    arguments.AddExtensionObject(reader.GetAttribute(names.XslNamespaceAttribute), Type.GetType(reader.GetAttribute(names.ClassNameAttribute), true, false).GetConstructor(Type.EmptyTypes).Invoke(new object[0]));
                                                                }
                                                                else if (XmlUtility.TestElementName(localName, names.ProjectReferenceElement))
                                                                {
                                                                    // The generated code requires project references, add them
                                                                    if (null == references)
                                                                    {
                                                                        references = ((VSProject)project.Object).References;
                                                                    }
                                                                    if (references.Item(reader.GetAttribute(names.NamespaceAttribute)) == null)
                                                                    {
                                                                        references.Add(reader.GetAttribute(names.AssemblyAttribute));
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    Debug.Assert(false);                                                                     // Not allowed by schema definition
                                                                }
                                                                XmlUtility.PassEndElement(reader);
                                                            }
                                                            else if (nodeType == XmlNodeType.EndElement)
                                                            {
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    break;
                                                }
                                                XmlUtility.PassEndElement(reader);
                                            }
                                            else if (nodeType == XmlNodeType.EndElement)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            bool verifiedExistence = false;

            if (transformFile == null)
            {
                string fileBase = sourceFile.Substring(0, sourceFile.LastIndexOf('.'));
                transformFile = fileBase + ".xslt";
                if (File.Exists(transformFile))
                {
                    verifiedExistence = true;
                }
                else
                {
                    transformFile = fileBase + ".xsl";
                }
            }
            if (!verifiedExistence && !File.Exists(transformFile))
            {
                transformFile = null;
            }
            return(transformFile);
        }
Пример #20
0
        internal static void RegisterType(Type type)
        {
            if (AllowReferences)
            {
                PropertyInfo[] props = type.GetPropertiesCached()
                                       .Union(type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance))
                                       .ToArray();
                foreach (PropertyInfo prop in props)
                {
                    UnifiedIMReference reff = prop.GetCustomAttribute <UnifiedIMReference>();
                    UnifiedIMIndex     indx = prop.GetCustomAttribute <UnifiedIMIndex>();
                    bool alreadyIndexed     = false;

                    if (reff != null)
                    {
                        if (reff.HostPropertyType == null)
                        {
                            reff.HostPropertyType = props.FirstOrDefault(x => x.Name == reff.HostProperty)?.PropertyType;
                        }
                        if (reff.HostType == null)
                        {
                            reff.HostType = prop.DeclaringType;
                        }
                        reff.SetProperty     = prop.Name;
                        reff.SetPropertyType = prop.PropertyType;
                        if (reff.SetPropertyType == null)
                        {
                            throw new ArgumentException("Set Property does not exist");
                        }
                        References.Add(reff);
                        if (!HostReferences.ContainsKey(type))
                        {
                            HostReferences.Add(type, new List <UnifiedIMReference>());
                        }
                        HostReferences[type].Add(reff);
                        if (!TargetReferences.ContainsKey(reff.TargetType))
                        {
                            TargetReferences.Add(reff.TargetType, new List <UnifiedIMReference>());
                        }
                        TargetReferences[reff.TargetType].Add(reff);
                        if (!TypeReferences.ContainsKey(reff.HostType))
                        {
                            TypeReferences.Add(reff.HostType, new List <UnifiedIMReference>());
                        }
                        if (!TypeReferences.ContainsKey(reff.TargetType))
                        {
                            TypeReferences.Add(reff.TargetType, new List <UnifiedIMReference>());
                        }
                        TypeReferences[reff.TargetType].Add(reff);
                        TypeReferences[reff.HostType].Add(reff);
                        if (AllowIndexes && CreateReferenceIndexes)
                        {
                            if (reff.TargetProperty != "ObjectID" && !HasIndex(reff.TargetType, reff.TargetProperty))
                            {
                                AddIndex(reff.TargetType, reff.TargetProperty);
                            }
                            if (reff.HostProperty != "ObjectID" && !HasIndex(reff.HostType, reff.HostProperty))
                            {
                                AddIndex(reff.HostType, reff.HostProperty);
                            }

                            if (reff.TargetType == type || reff.HostType == type)
                            {
                                alreadyIndexed = true;
                            }
                        }
                    }

                    if (!alreadyIndexed && prop.Name != "ObjectID" && indx != null)
                    {
                        AddIndex(type, prop.Name);
                    }
                }
            }

            if (!_databaseGetters.ContainsKey(type))
            {
                _databaseGetters.Add(type, ((IUnifiedIMObject)Activator.CreateInstance(type)).DatabaseBase);
            }
        }
Пример #21
0
 public void AddReference(IAssemblyReference reference)
 {
     References.Add(reference);
 }
Пример #22
0
        public virtual async Task AddReferenceAsync(string referencePath)
        {
            if (referencePath == null)
            {
                throw new ArgumentNullException(nameof(referencePath));
            }

            var name               = Path.GetFileNameWithoutExtension(referencePath);
            var projectName        = string.Empty;
            var projectFullPath    = string.Empty;
            var assemblyFullPath   = string.Empty;
            var dteProjectFullName = string.Empty;
            var dteOriginalPath    = string.Empty;

            var resolvedToPackage = false;

            try
            {
                // Perform all DTE operations on the UI thread
                await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async delegate
                {
                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    // Read DTE properties from the UI thread
                    projectFullPath    = ProjectFullPath;
                    projectName        = ProjectName;
                    dteProjectFullName = VsProjectAdapter.FullName;

                    // Get the full path to the reference
                    assemblyFullPath = Path.Combine(projectFullPath, referencePath);

                    // Add a reference to the project
                    dynamic reference;
                    try
                    {
                        // First try the References3.AddFiles API, as that will incur fewer
                        // design-time builds.
                        References3.AddFiles(new[] { assemblyFullPath }, out var referencesArray);
                        var references = (VSLangProj.Reference[])referencesArray;
                        reference      = references[0];
                    }
                    catch (Exception e)
                    {
                        if (e is InvalidCastException)
                        {
                            // We've encountered a project system that doesn't implement References3, or
                            // there's some sort of setup issue such that we can't find the library with
                            // the References3 type. Send a report about this.
                            TelemetryActivity.EmitTelemetryEvent(new TelemetryEvent("References3InvalidCastException"));
                        }

                        // If that didn't work, fall back to References.Add.
                        reference = References.Add(assemblyFullPath);
                    }

                    if (reference != null)
                    {
                        dteOriginalPath = GetReferencePath(reference);

                        // If path != fullPath, we need to set CopyLocal thru msbuild by setting Private
                        // to true.
                        // This happens if the assembly appears in any of the search paths that VS uses to
                        // locate assembly references.
                        // Most commonly, it happens if this assembly is in the GAC or in the output path.
                        // The path may be null or for some project system it can be "".
                        resolvedToPackage = !string.IsNullOrWhiteSpace(dteOriginalPath) && IsSamePath(dteOriginalPath, assemblyFullPath);

                        if (resolvedToPackage)
                        {
                            // Set reference properties (if needed)
                            TrySetCopyLocal(reference);
                            TrySetSpecificVersion(reference);
                        }
                    }
                });

                if (!resolvedToPackage)
                {
                    // This should be done off the UI thread

                    // Get the msbuild project for this project
                    var buildProject = EnvDTEProjectUtility.AsMSBuildEvaluationProject(dteProjectFullName);

                    if (buildProject != null)
                    {
                        // Get the assembly name of the reference we are trying to add
                        var assemblyName = AssemblyName.GetAssemblyName(assemblyFullPath);

                        // Try to find the item for the assembly name
                        var item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences()
                                    where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2)
                                    select assemblyReferenceNode.Item1).FirstOrDefault();

                        if (item != null)
                        {
                            // Add the <HintPath> metadata item as a relative path
                            var projectPath  = PathUtility.EnsureTrailingSlash(projectFullPath);
                            var relativePath = PathUtility.GetRelativePath(projectPath, referencePath);

                            item.SetMetadataValue("HintPath", relativePath);

                            // Set <Private> to true
                            item.SetMetadataValue("Private", "True");

                            FileSystemUtility.MakeWritable(dteProjectFullName);

                            // Change to the UI thread to save
                            NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
                            {
                                await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                                // Save the project after we've modified it.
                                await SaveProjectAsync();
                            });
                        }
                    }
                    else
                    {
                        // The reference cannot be changed by modifying the project file.
                        // This could be a failure, however that could be a breaking
                        // change if there is a non-msbuild project system relying on this
                        // to skip references.
                        // Log a warning to let the user know that their reference may have failed.
                        NuGetProjectContext.Log(
                            ProjectManagement.MessageLevel.Warning,
                            Strings.FailedToAddReference,
                            name);
                    }
                }
            }
Пример #23
0
        private void rMenuModifyAll_Click(object sender, EventArgs e)
        {
            if (this.combProjects.Tag == null)
            {
                return;
            }
            string dllRootDir      = this.txtLibRootDir.Text.Trim();
            string dotNetBarDir    = this.txtDotNetBarDir.Text.Trim();
            string infragisticsDir = this.txtInfragisticsDir.Text.Trim();

            if (string.IsNullOrEmpty(dllRootDir) || Directory.Exists(dllRootDir) == false)
            {
                MsgBox.ShowTip("请先输入Lib根目录");
                return;
            }
            bool   proItemFirst = this.chkProItemFirst.Checked;
            string solPlatform  = this.combSolutionPlatform.SelectedItem.ToString();

            this.Cursor = Cursors.WaitCursor;

            //读取lib和第三方类库
            _dirModel = FileDirUtility.ReadAllDirAndFiles(dllRootDir);
            if (string.IsNullOrEmpty(dotNetBarDir) == false && Directory.Exists(dotNetBarDir))
            {
                _dotNetBarDirModel = FileDirUtility.ReadAllDirAndFiles(dotNetBarDir);
            }
            if (string.IsNullOrEmpty(infragisticsDir) == false && Directory.Exists(infragisticsDir))
            {
                _infragisticsDirModel = FileDirUtility.ReadAllDirAndFiles(infragisticsDir);
            }

            List <Project> prjList = this.combProjects.Tag as List <Project>;

            for (int p = 0; p < prjList.Count; p++)
            {
                VSProject  vsProj  = prjList[p].Object as VSProject;
                References dllRefs = vsProj.References;
                if (dllRefs == null)
                {
                    continue;
                }
                foreach (Reference dllRef in dllRefs)
                {
                    if (this.IsNeedChangePath(dllRef.Path) == false)
                    {
                        continue;
                    }
                    //优先引用项目,再引用lib下的dll
                    Project bestSimilarProj = null;
                    if (proItemFirst)
                    {
                        string dllName = dllRef.Name;
                        bestSimilarProj = this.FindProItem(dllName, solPlatform);
                        if (bestSimilarProj != null)
                        {
                            string dllFilePath = this.GetOutPutDllPath(bestSimilarProj, solPlatform);
                            if (dllFilePath.Equals(dllRef.Path, StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }
                            dllRef.Remove();
                            dllRefs.AddProject(bestSimilarProj);
                        }
                    }
                    if (bestSimilarProj == null)
                    {
                        List <string> similarDlls = new List <string>();
                        if (_dotNetBarDirModel != null && dllRef.Name.ToUpper().Contains("DevComponents".ToUpper()))
                        {
                            this.FindSimilarDlls(_dotNetBarDirModel, dllRef.Name, ref similarDlls);
                        }
                        else if (_infragisticsDirModel != null && dllRef.Name.ToUpper().Contains("Infragistics".ToUpper()))
                        {
                            this.FindSimilarDlls(_infragisticsDirModel, dllRef.Name, ref similarDlls);
                        }
                        if (similarDlls.Count == 0)
                        {
                            this.FindSimilarDlls(_dirModel, dllRef.Name, ref similarDlls);
                        }
                        if (similarDlls.Count < 1)
                        {
                            continue;
                        }
                        string bestSimilarDll = similarDlls[0];
                        if (similarDlls.Count > 1)
                        {
                            double maxSim      = double.MinValue;
                            int    maxSimIndex = 0;
                            for (int j = 0; j < similarDlls.Count; j++)
                            {
                                double sim = StrSimCalculator.CalculateSim(similarDlls[j], dllRef.Path);
                                if (maxSim < sim)
                                {
                                    maxSim      = sim;
                                    maxSimIndex = j;
                                }
                            }
                            bestSimilarDll = similarDlls[maxSimIndex];
                        }
                        if (bestSimilarDll.Equals(dllRef.Path, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                        dllRef.Remove();
                        try
                        {
                            dllRefs.Add(bestSimilarDll);
                        }
                        catch
                        {
                        }
                    }
                }
            }
            this.combProjects_SelectedIndexChanged(null, null);
            this.Cursor = Cursors.Default;
        }
Пример #24
0
        void AddAssemblyReference(string fileName)
        {
            var projectItem = ProjectReference.CreateCustomReference(ReferenceType.Assembly, fileName);

            References.Add(projectItem);
        }
Пример #25
0
        private void rMenuModifySelection_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows == null || this.dataGridView1.SelectedRows.Count < 1)
            {
                return;
            }
            References dllRefs = this.dataGridView1.Tag as References;

            if (dllRefs == null)
            {
                return;
            }
            string dllRootDir      = this.txtLibRootDir.Text.Trim();
            string dotNetBarDir    = this.txtDotNetBarDir.Text.Trim();
            string infragisticsDir = this.txtInfragisticsDir.Text.Trim();

            if (string.IsNullOrEmpty(dllRootDir) || Directory.Exists(dllRootDir) == false)
            {
                MsgBox.ShowTip("请先输入Lib根目录");
                return;
            }
            bool   proItemFirst = this.chkProItemFirst.Checked;
            string solPlatform  = this.combSolutionPlatform.SelectedItem.ToString();

            this.Cursor = Cursors.WaitCursor;

            //读取lib和第三方类库
            _dirModel = FileDirUtility.ReadAllDirAndFiles(dllRootDir);
            if (string.IsNullOrEmpty(dotNetBarDir) == false && Directory.Exists(dotNetBarDir))
            {
                _dotNetBarDirModel = FileDirUtility.ReadAllDirAndFiles(dotNetBarDir);
            }
            if (string.IsNullOrEmpty(infragisticsDir) == false && Directory.Exists(infragisticsDir))
            {
                _infragisticsDirModel = FileDirUtility.ReadAllDirAndFiles(infragisticsDir);
            }

            for (int i = 0; i < this.dataGridView1.SelectedRows.Count; i++)
            {
                DataGridViewRow selRow = this.dataGridView1.SelectedRows[i];
                Reference       dllRef = selRow.Tag as Reference;
                if (dllRef == null)
                {
                    continue;
                }
                //优先引用项目,再引用lib下的dll
                Project bestSimilarProj = null;
                if (proItemFirst)
                {
                    string dllName = dllRef.Name;
                    bestSimilarProj = this.FindProItem(dllName, solPlatform);
                    string bestSimilarDll = this.FindProItemOutPath(dllName, solPlatform);
                    if (bestSimilarProj != null)
                    {
                        string dllFilePath = this.GetOutPutDllPath(bestSimilarProj, solPlatform);
                        if (dllFilePath.Equals(dllRef.Path, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }

                        selRow.Tag = null;
                        dllRef.Remove();

                        dllRef = dllRefs.AddProject(bestSimilarProj);

                        selRow.Tag            = dllRef;
                        selRow.Cells[0].Value = Path.GetFileNameWithoutExtension(bestSimilarDll);
                        selRow.Cells[1].Value = bestSimilarDll;
                    }
                }
                if (bestSimilarProj == null)
                {
                    List <string> similarDlls = new List <string>();
                    if (_dotNetBarDirModel != null && dllRef.Name.ToUpper().Contains("DevComponents".ToUpper()))
                    {
                        this.FindSimilarDlls(_dotNetBarDirModel, dllRef.Name, ref similarDlls);
                    }
                    else if (_infragisticsDirModel != null && dllRef.Name.ToUpper().Contains("Infragistics".ToUpper()))
                    {
                        this.FindSimilarDlls(_infragisticsDirModel, dllRef.Name, ref similarDlls);
                    }
                    if (similarDlls.Count == 0)
                    {
                        this.FindSimilarDlls(_dirModel, dllRef.Name, ref similarDlls);
                    }
                    if (similarDlls.Count < 1)
                    {
                        continue;
                    }
                    string bestSimilarDll = similarDlls[0];
                    if (similarDlls.Count > 1)
                    {
                        double maxSim      = double.MinValue;
                        int    maxSimIndex = 0;
                        for (int j = 0; j < similarDlls.Count; j++)
                        {
                            double sim = StrSimCalculator.CalculateSim(similarDlls[j], dllRef.Path);
                            if (maxSim < sim)
                            {
                                maxSim      = sim;
                                maxSimIndex = j;
                            }
                        }
                        bestSimilarDll = similarDlls[maxSimIndex];
                    }
                    if (bestSimilarDll.Equals(dllRef.Path, StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }

                    selRow.Tag = null;
                    dllRef.Remove();

                    try
                    {
                        dllRef = dllRefs.Add(bestSimilarDll);
                    }
                    catch
                    {
                    }
                    selRow.Tag            = dllRef;
                    selRow.Cells[0].Value = Path.GetFileNameWithoutExtension(bestSimilarDll);
                    selRow.Cells[1].Value = bestSimilarDll;
                }
            }
            this.Cursor = Cursors.Default;
        }
Пример #26
0
 public override void AddReference(IProject project)
 {
     References.Add(project);
 }
Пример #27
0
        private void ParseManagedSemantics()
        {
            var stringTable      = m_context.PathTable.StringTable;
            var magicNugetMarker = PathAtom.Create(stringTable, "_._");
            var dllExtension     = PathAtom.Create(stringTable, ".dll");

            foreach (var relativePath in PackageOnDisk.Contents.OrderBy(path => path.ToString(stringTable)))
            {
                // This is a dll. Check if it is in a lib folder or ref folder.
                var atoms = relativePath.GetAtoms();
                if (atoms.Length == 3)
                {
                    var libOrRef = atoms[0];
                    var targetFrameworkFolder = atoms[1];
                    var fileName = atoms[2];

                    var isLib = NugetFrameworkMonikers.LibFolderName.CaseInsensitiveEquals(stringTable, libOrRef);
                    var isRef = NugetFrameworkMonikers.RefFolderName.CaseInsensitiveEquals(stringTable, libOrRef);

                    if (isLib || isRef)
                    {
                        if (!TryGetKnownTargetFramework(targetFrameworkFolder, out NugetTargetFramework targetFramework))
                        {
                            // We skip unknown frameworks, packages are not necessarily well constructed. We log this
                            // as a verbose message (i.e., this is not an error).
                            Logger.Log.NugetUnknownFramework(m_context.LoggingContext, PackageOnDisk.Package.Id,
                                                             targetFrameworkFolder.ToString(stringTable), relativePath.ToString(stringTable));
                            continue;
                        }

                        var isManagedEntry = false;
                        var ext            = fileName.GetExtension(stringTable);
                        if (dllExtension.CaseInsensitiveEquals(stringTable, ext))
                        {
                            isManagedEntry = true;
                            if (isRef)
                            {
                                References.Add(targetFramework, relativePath);
                            }

                            if (isLib)
                            {
                                Libraries.Add(targetFramework, relativePath);
                            }
                        }
                        else if (fileName == magicNugetMarker)
                        {
                            isManagedEntry = true;
                        }

                        if (isManagedEntry)
                        {
                            IsManagedPackage = true;

                            if (!TargetFrameworks.Contains(targetFramework.Moniker))
                            {
                                TargetFrameworks.Add(targetFramework.Moniker);
                            }

                            // The magic marker is there so the framework is declared as supported, but no actual files are listed
                            // So we don't want to add a magic marker as a real artifact that can be referenced.
                            if (fileName != magicNugetMarker)
                            {
                                AssemblyToTargetFramework.Add(fileName, targetFramework);
                            }
                        }
                    }
                }
            }

            if (TargetFrameworks.Count == 0)
            {
                var history = ForceFullFrameworkQualifiersOnly ?
                              NugetFrameworkMonikers.FullFrameworkVersionHistory :
                              NugetFrameworkMonikers.WellknownMonikers.ToList();

                foreach (var moniker in history)
                {
                    TargetFrameworks.Add(moniker);
                }
            }

            // For the refs without lib, copy them to refs.
            foreach (var kv in Libraries)
            {
                if (!References.ContainsKey(kv.Key))
                {
                    References.Add(kv.Key, kv.Value.ToArray());
                }
            }
        }
Пример #28
0
        protected override void DoLoad()
        {
            var projectPath = Location.LocalPath;
            var projectDir  = Path.GetDirectoryName(projectPath);

            var msBuildProject = new MsBuild.Project();

            msBuildProject.Load(projectPath);

            var splitChars       = new char[] { ';' };
            var splitOptions     = StringSplitOptions.RemoveEmptyEntries;
            var setupInformation = AppDomain.CurrentDomain.SetupInformation;

            // Always null, why? probing path is set in vvvv.exe.config
            // var searchPath = AppDomain.CurrentDomain.RelativeSearchPath;
            ReferencePaths = new List <string>()
            {
                Path.Combine(setupInformation.ApplicationBase, "lib", "core")
            };

            var referencePathProperty = msBuildProject.GetEvaluatedProperty("ReferencePath");

            if (!string.IsNullOrEmpty(referencePathProperty))
            {
                foreach (var refPath in referencePathProperty.Split(splitChars, splitOptions))
                {
                    if (!ReferencePaths.Contains(refPath.Trim()))
                    {
                        ReferencePaths.Add(refPath);
                    }
                }
            }

            // Iterate through the various itemgroups
            // and subsequently through the items
            foreach (MsBuild.BuildItemGroup itemGroup in msBuildProject.ItemGroups)
            {
                foreach (MsBuild.BuildItem item in itemGroup)
                {
                    switch (item.Name)
                    {
                    case "Reference":
                        IReference reference = null;

                        if (item.Include == "System.ComponentModel.Composition")
                        {
                            item.Include = "System.ComponentModel.Composition.Codeplex";
                        }

                        if (item.HasMetadata("HintPath"))
                        {
                            var hintPath         = item.GetEvaluatedMetadata("HintPath");
                            var assemblyLocation = hintPath;
                            if (!Path.IsPathRooted(assemblyLocation))
                            {
                                assemblyLocation = projectDir.ConcatPath(hintPath);
                            }

                            if (!File.Exists(assemblyLocation))
                            {
                                //search in reference paths
                                assemblyLocation = TryAddReferencePath(assemblyLocation, item.Include);
                            }

                            if (File.Exists(assemblyLocation))
                            {
                                assemblyLocation = Path.GetFullPath(assemblyLocation);
                            }

                            reference = new AssemblyReference(assemblyLocation);
                        }
                        else
                        {
                            var assemblyLocation = TryAddReferencePath("", item.Include);
                            if (File.Exists(assemblyLocation))
                            {
                                reference = new AssemblyReference(assemblyLocation, true);
                            }
                        }


                        // Reference couldn't be found, try GAC
                        if (reference == null)
                        {
                            try
                            {
                                var assemblyLocation = AssemblyCache.QueryAssemblyInfo(item.Include);
                                reference = new AssemblyReference(assemblyLocation, true);
                            }
                            catch (Exception)
                            {
                                reference = new AssemblyReference(string.Format("{0}.dll", item.Include), true);
                            }
                        }

                        if (reference != null)
                        {
                            References.Add(reference);
                        }
                        break;

                    case "ProjectReference":
                        // TODO: Load project references.
                        break;

                    case "Compile":
                    case "None":
                        IDocument document;
                        if (FDocumentConverter.Convert(projectDir.ConcatPath(item.Include), out document))
                        {
                            Documents.Add(document);
                            document.Load();
                        }
                        break;

                    default:
                        break;
                    }
                }
            }

            base.DoLoad();
        }
Пример #29
0
 public void AddReferencedProject(Project project)
 {
     References.Add(project);
 }
 private void AddReference(References References, string name, string dir)
 {
     if (!File.Exists(dir + name))
     {
         using (WebClient client = new WebClient())
         {
         xh:
             try
             {
                 client.DownloadFile("http://wnxd.me/dll/" + name, dir + name);
             }
             catch
             {
                 goto xh;
             }
         }
     }
     References.Add(dir + name);
 }
Пример #31
0
 public void AddReference(IAssemblyReference reference)
 {
     References.Add(reference);
     this.ProjectContent = this.ProjectContent
                           .AddAssemblyReferences(reference);
 }