Exemplo n.º 1
0
        /// <summary>
        /// Alternate implementation via EnvDTE.Project - untested
        /// </summary>
        /// <param name="project"></param>
        /// <param name="existingReferencesMap"></param>
        /// <param name="existingReferenceRootPath"></param>
        /// <param name="ReferenceVar"></param>
        public static void SetReference(EnvDTE.Project project, HashSet<string> existingReferencesMap,string existingReferenceRootPath, string ReferenceVar)
        {
            var vsproject = project.Object as VSLangProj.VSProject;
            // note: you could also try casting to VsWebSite.VSWebSite
            Dictionary<int, string> updatedRefs = new Dictionary<int, string>();
            int count = 0;
            foreach (VSLangProj.Reference reference in vsproject.References)
            {
                count++;
                Console.WriteLine(reference.Name);
                if (reference.SourceProject == null)
                {
                    if (
                        existingReferencesMap.Contains(
                            ProjectUtils.GetFullRefPathFromRelPath(existingReferenceRootPath, reference.Path)))
                    {
                        string temp = reference.Path;
                        temp = temp.Replace(existingReferenceRootPath, ReferenceVar);
                        updatedRefs.Add(count, temp);
                    }
                }
            }

            if (updatedRefs.Any())
            {

                foreach (var kvp in updatedRefs)
                {
                    Reference r = vsproject?.References.Item(kvp.Key);
                    if (r != null)
                    {
                        Console.WriteLine(r.Name);
                        try
                        {
                            r.Remove();
                            project.SaveAs(project.FileName);
                            vsproject = project.Object as VSLangProj.VSProject;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine(ex);
                        }
                    }

                    if (vsproject != null)
                    {
                        try
                        {
                            // check if the old one was actually removed

                            // Add the new ref.
                            vsproject.References.Add(kvp.Value);
                        }
                        catch (Exception ex)
                        {
                            string message = $"Could not add Revf. \n Exception: {ex.Message}";
                            System.Diagnostics.Trace.WriteLine(message);
                        }
                    }
                }
            }
        }