예제 #1
0
        public static void TestGetRelativePath()
        {
            ConsoleHelper.WriteLine("Testing GetRelativePath():", false);
            string[] paths =
            {
                @"Folder1\Folder2\File1.csproj",
                @"Folder3\Folder4\File2.csproj",
                @"..\..\Folder3\Folder4\File2.csproj",

                @"dir1\file1",                        @"dir2\file2",  @"..\dir2\file2",
                @"dir1\",                             @"dir2\file2",  @"..\dir2\file2"
            };

            for (int i = 0; i < paths.Length; i += 3)
            {
                string s = FileHelper.GetRelativePath(paths[i], paths[i + 1]);
                if (s == paths[i + 2])
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Green, $"'{paths[i]}' -> '{paths[i + 1]}' = '{s}'");
                }
                else
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red, $"'{paths[i]}' -> '{paths[i + 1]}' = '{s}' ({paths[i + 2]})");
                }
            }
        }
예제 #2
0
        private ProjectRef CreateProjectReferenceFromReference(string solutionfile, List <Project> projects, AssemblyRef assref)
        {
            Project referencedProject;

            try
            {
                referencedProject = projects.SingleOrDefault(p => p._proj_assemblyname == assref.Shortinclude);
            }
            catch (System.InvalidOperationException)
            {
                // Early validation prevents this exception
                ConsoleHelper.ColorWrite(ConsoleColor.Red, "Error: Projects have identical assembly names.");
                throw;
            }

            string relpath = FileHelper.GetRelativePath(_sln_path, referencedProject._sln_path);

            return(new ProjectRef
            {
                Include = relpath,
                Shortinclude = referencedProject._sln_shortfilename,
                Name = referencedProject._sln_shortfilename,
                Project = referencedProject._proj_guid,
                Package = referencedProject._sln_package,
                Names = null,
                Projects = null,
                Packages = null
            });
        }
예제 #3
0
        public void AddToDoc(XDocument xdoc, XNamespace ns)
        {
            ConsoleHelper.WriteLine($"  Adding assembly ref: '{Include}", true);

            XElement newref;

            if (Hintpath == null)
            {
                newref = new XElement(ns + "Reference",
                                      new XAttribute("Include", Include),
                                      new XElement(ns + "SpecificVersion", "False")
                                      );
            }
            else
            {
                newref = new XElement(ns + "Reference",
                                      new XAttribute("Include", Include),
                                      new XElement(ns + "SpecificVersion", "False"),
                                      new XElement(ns + "HintPath", Hintpath)
                                      );
            }


            // Sort insert
            var groups = from el in xdoc.Element(ns + "Project").Elements(ns + "ItemGroup")
                         where el.Element(ns + "Reference") != null
                         select el;

            if (groups.Count() == 0)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow, $"NotImplementedException: Cannot insert reference!");
                return;
            }

            var refs = from el in groups.ElementAt(0).Elements(ns + "Reference")
                       where el.Attribute("Include") != null
                       orderby el.Attribute("Include").Value
                       select el;

            if (Include.CompareTo(refs.First().Attribute("Include").Value) < 0)
            {
                groups.ElementAt(0).AddFirst(newref);
            }
            else if (Include.CompareTo(refs.Last().Attribute("Include").Value) > 0)
            {
                refs.Last().AddAfterSelf(newref);
            }
            else
            {
                for (int i = 0; i < refs.Count() - 1; i++)
                {
                    string inc1 = refs.ElementAt(i).Attribute("Include").Value;
                    string inc2 = refs.ElementAt(i + 1).Attribute("Include").Value;
                    if (Include.CompareTo(inc1) > 0 && Include.CompareTo(inc2) < 0)
                    {
                        refs.ElementAt(i).AddAfterSelf(newref);
                    }
                }
            }
        }
예제 #4
0
        private static void CheckName(string solutionfile, string path, string assemblyname)
        {
            if (assemblyname == null)
            {
                return;
            }

            int    pos;
            string filename = Path.GetFileNameWithoutExtension(path);

            pos = filename.LastIndexOf('.');
            if (pos >= 0)
            {
                filename = filename.Substring(pos + 1);
            }

            string assname = assemblyname;

            pos = assname.LastIndexOf('.');
            if (pos >= 0)
            {
                assname = assname.Substring(pos + 1);
            }
            bool wrotemessage = false;

            if (assname != filename &&
                $"{assname}Lib" != filename &&
                $"{assname}CSharp" != filename &&
                !assemblyname.Replace(".", "").EndsWith(filename))
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                         $"Warning: Mismatched name for project '{path}': Assembly name: '{assemblyname}'. File name: '{Path.GetFileNameWithoutExtension(path)}'.");
                wrotemessage = true;
            }


            // Egentligen borde det göras en rak jämförelse mellan projektfilsnamn och assemblyname,
            // men då skulle det varnas på de flesta projekt. Vi skriver ut detta "spam"
            // som verbose information i stället.

            if (!wrotemessage)
            {
                filename = Path.GetFileNameWithoutExtension(path);

                if (filename != assemblyname)
                {
                    ConsoleHelper.WriteLine(
                        $"  Warning: Mismatched name for project '{path}': Assembly name: '{assemblyname}'. File name: '{filename}'.",
                        true);
                }
                else
                {
                    ConsoleHelper.WriteLine(
                        $"  Very good: Name for project '{path}': Assembly name==File name: '{assemblyname}'.",
                        true);
                }
            }
        }
예제 #5
0
        public void Compact()
        {
            // _proj_assemblynames -> _proj_assemblyname
            // _proj_guids         -> _proj_guid
            // _proj_outputtypes   -> _proj_outputtype

            if (_proj_assemblynames.Count > 1)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                         $"Warning: Corrupt project file: {_sln_path}, multiple assembly names: '{_proj_assemblynames.Count}', compacting Name elements.");
                _modified = true;
            }
            if (_proj_assemblynames.Count >= 1)
            {
                _proj_assemblyname  = _proj_assemblynames[0];
                _proj_assemblynames = null;
            }

            if (_proj_guids.Count > 1)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                         $"Warning: Corrupt project file: {_sln_path}, multiple guids: '{_proj_guids.Count}', compacting ProjectGuid elements.");
                _modified = true;
            }
            if (_proj_guids.Count >= 1)
            {
                _proj_guid  = _proj_guids[0];
                _proj_guids = null;
            }

            if (_proj_outputtypes.Count > 1)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                         $"Warning: Corrupt project file: {_sln_path}, multiple output types: '{_proj_outputtypes.Count}', compacting Private elements.");
                _modified = true;
            }
            if (_proj_outputtypes.Count >= 1)
            {
                _proj_outputtype  = _proj_outputtypes[0];
                _proj_outputtypes = null;
            }

            return;
        }
예제 #6
0
        public bool FixProjects(List <Project> projects, List <string> hintpaths, string outputpath, bool copylocal, bool removeversion)
        {
            bool valid = true;

            foreach (Project p in projects.OrderBy(p => p._sln_path))
            {
                p.Compact();
            }

            foreach (Project p in projects.OrderBy(p => p._sln_path))
            {
                p.CompactRefs();
            }

            ConsoleHelper.WriteLineDeferred("-=-=- Validating -=-=-");
            foreach (Project p in projects.OrderBy(p => p._sln_path))
            {
                if (!p.Validate(_solutionfile, projects))
                {
                    valid = false;
                }
            }
            ConsoleHelper.WriteLineDeferred(null);

            if (!valid)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, "Fix errors before continuing!");
                return(false);
            }

            foreach (Project p in projects.OrderBy(p => p._sln_path))
            {
                p.Fix(_solutionfile, projects, hintpaths, outputpath, copylocal, removeversion);
            }

            return(true);  // Success
        }
예제 #7
0
        public static void TestCompactPath()
        {
            ConsoleHelper.WriteLine("Testing CompactPath():", false);
            string[] paths =
            {
                @"",                       @"",
                @"\",                      @"\",
                @"..",                     @"..",
                @"\..",                    @"\..",
                @"..\",                    @"..\",
                @"ab\",                    @"ab\",
                @"\ba",                    @"\ba",
                @"a",                      @"a",
                @"..\a",                   @"..\a",

                @"a\..",                   @"",
                @"..\a\..",                @"..",
                @"..\..\a",                @"..\..\a",
                @"abc\def\..",             @"abc",
                @"abc\..\def",             @"def",
                @"..\abc\def",             @"..\abc\def",

                @"\a\..",                  @"\",
                @"\..\a\..",               @"\..",
                @"\..\..\a",               @"\..\..\a",
                @"\abc\def\..",            @"\abc",
                @"\abc\..\def",            @"\def",
                @"\..\abc\def",            @"\..\abc\def",

                @"a\..\",                  @"\",
                @"..\a\..\",               @"..\",
                @"..\..\a\",               @"..\..\a\",
                @"abc\def\..\",            @"abc\",
                @"abc\..\def\",            @"def\",
                @"..\abc\def\",            @"..\abc\def\",

                @"\a\..\",                 @"\",
                @"\..\a\..\",              @"\..\",
                @"\..\..\a\",              @"\..\..\a\",
                @"\abc\def\..\",           @"\abc\",
                @"\abc\..\def\",           @"\def\",
                @"\..\abc\def\",           @"\..\abc\def\",

                @"dir1\dir2\dir3\..\dir4", @"dir1\dir2\dir4",

                @"\\",                     @"\",
                @"\\x",                    @"\x",
                @"x\\",                    @"x\",

                @"\\",                     @"\",
                @"\\..",                   @"\..",
                @"..\\",                   @"..\",

                @"\\\\",                   @"\"
            };

            for (int i = 0; i < paths.Length; i += 2)
            {
                string s = FileHelper.CompactPath(paths[i]);
                if (s == paths[i + 1])
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Green, $"'{paths[i]}' -> '{s}'");
                }
                else
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red, $"'{paths[i]}' -> '{s}' ({paths[i + 1]})");
                }
            }
        }
예제 #8
0
        public List <Project> LoadProjects()
        {
            string[] rows;
            try
            {
                rows = File.ReadAllLines(_solutionfile);
            }
            catch (IOException ex)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load solution: '{_solutionfile}': {ex.Message}");
                return(null);
            }
            catch (UnauthorizedAccessException ex)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load solution: '{_solutionfile}': {ex.Message}");
                return(null);
            }
            catch (ArgumentException ex)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load solution: '{_solutionfile}': {ex.Message}");
                return(null);
            }

            List <Project> projects = new List <Project>();

            foreach (string row in rows)
            {
                // Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyCsProject", "Folder\Folder\MyCsProject.csproj", "{01010101-0101-0101-0101-010101010101}"
                // Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "MyVbProject", "Folder\Folder\MyVbProject.vbproj", "{02020202-0202-0202-0202-020202020202}"

                string[] projtypeguids = { "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}" };

                foreach (string projtypeguid in projtypeguids)
                {
                    string projtypeline = $"Project(\"{projtypeguid}\") =";

                    if (row.StartsWith(projtypeline))
                    {
                        string[] values = row.Substring(projtypeline.Length).Split(',');
                        if (values.Length != 3)
                        {
                            continue;
                        }

                        string package       = row.Substring(9, projtypeline.Length - 13);
                        string shortfilename = values[0].Trim().Trim('"');
                        string path          = values[1].Trim().Trim('"');
                        string guid          = values[2].Trim().Trim('"');

                        projects.Add(new Project()
                        {
                            _sln_package       = package,
                            _sln_shortfilename = shortfilename,
                            _sln_path          = path,
                            _sln_guid          = guid,
                            _modified          = false
                        });
                    }
                }
            }


            bool error = false;

            foreach (Project p in projects)
            {
                Project p2 = Project.LoadProject(_solutionfile, p._sln_path);
                if (p2 == null)
                {
                    error = true;
                    continue;
                }

                ConsoleHelper.WriteLine(
                    $"sln_package: '{p._sln_package}" +
                    $"', sln_guid: '{p._sln_guid}" +
                    $"', sln_shortfilename: '{p._sln_shortfilename}" +
                    $"', sln_path: '{p._sln_path}" +
                    $"', proj_assemblynames: {p2._proj_assemblynames.Count}" +
                    $", proj_guids: {p2._proj_guids.Count}" +
                    $", proj_outputtypes: {p2._proj_outputtypes.Count}.",
                    true);

                p._proj_assemblynames = p2._proj_assemblynames;
                p._proj_guids         = p2._proj_guids;
                p._proj_outputtypes   = p2._proj_outputtypes;

                p._outputpaths       = p2._outputpaths;
                p._references        = p2._references;
                p._projectReferences = p2._projectReferences;
            }

            if (error)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, "Fix errors before continuing!");
                return(null);
            }

            return(projects);
        }
예제 #9
0
        private bool TryToRetrieveAssemblyInfoOfProjectReference(string solutionfile, List <Project> projects, ProjectRef projref,
                                                                 out string assemblyname, out string outputtype)
        {
            XDocument  xdoc;
            XNamespace ns;

            string fullfilename = Path.Combine(
                Path.GetDirectoryName(solutionfile),
                Path.GetDirectoryName(_sln_path),
                projref.Include);

            ConsoleHelper.WriteLine($"  Loading external project: '{fullfilename}'.", true);

            try
            {
                // Delve greedily and deep into the external project file.
                xdoc = XDocument.Load(fullfilename);
            }
            catch (IOException ex)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename}': {ex.Message}");
                assemblyname = outputtype = null;
                return(false);
            }
            catch (System.Xml.XmlException ex)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename}': {ex.Message}");
                assemblyname = outputtype = null;
                return(false);
            }

            ns = xdoc.Root.Name.Namespace;


            XElement[] assemblynames = xdoc.Elements(ns + "Project").Elements(ns + "PropertyGroup").Elements(ns + "AssemblyName").ToArray();
            if (assemblynames.Length == 0)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow, $"Couldn't load project: '{fullfilename}': Missing AssemblyName.");
                assemblyname = null;
            }
            else
            {
                assemblyname = assemblynames.Single().Value;
            }

            XElement[] outputtypes = xdoc.Elements(ns + "Project").Elements(ns + "PropertyGroup").Elements(ns + "OutputType").ToArray();
            if (outputtypes.Length == 0)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Yellow, $"Couldn't load project: '{fullfilename}': Missing OutputType.");
                outputtype = null;
            }
            else
            {
                outputtype = outputtypes.Single().Value;
            }

            if (assemblyname != null)
            {
                // Caution: External project (its assembly name) may conflict with a loaded project name
                bool afterthis = false;
                foreach (Project proj in projects.OrderBy(p => p._sln_path))
                {
                    if (proj == this)
                    {
                        afterthis = true;
                        continue;
                    }
                    if (!afterthis)
                    {
                        continue;
                    }

                    if (assemblyname == proj._proj_assemblyname)
                    {
                        ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Error: Projects have identical assembly names: '{assemblyname}': '{fullfilename}' and '{proj._sln_path}'.");
                        throw new Exception("Error");
                    }
                }
            }

            return(true);
        }
예제 #10
0
        public static Project LoadProject(string solutionfile, string projectfilepath)
        {
            Project    newproj = new Project();
            XDocument  xdoc;
            XNamespace ns;

            string fullfilename = Path.Combine(Path.GetDirectoryName(solutionfile), projectfilepath);

            try
            {
                xdoc = XDocument.Load(fullfilename);
            }
            catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is System.Xml.XmlException)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename}': {ex.Message}");
                return(null);
            }

            ns = xdoc.Root.Name.Namespace;


            try
            {
                newproj._proj_assemblynames = xdoc
                                              .Elements(ns + "Project")
                                              .Elements(ns + "PropertyGroup")
                                              .Elements(ns + "AssemblyName")
                                              .Select(a => a.Value)
                                              .ToList();
            }
            catch (NullReferenceException)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename}': Missing AssemblyName.");
                return(null);
            }

            try
            {
                newproj._proj_guids = xdoc
                                      .Elements(ns + "Project")
                                      .Elements(ns + "PropertyGroup")
                                      .Elements(ns + "ProjectGuid")
                                      .Select(g => g.Value).ToList();
            }
            catch (NullReferenceException)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename}': Missing ProjectGuid.");
                return(null);
            }

            try
            {
                newproj._proj_outputtypes = xdoc
                                            .Elements(ns + "Project")
                                            .Elements(ns + "PropertyGroup")
                                            .Elements(ns + "OutputType")
                                            .Select(o => o.Value).ToList();
            }
            catch (NullReferenceException)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red, $"Couldn't load project: '{fullfilename} ': Missing OutputType.");
                return(null);
            }


            newproj._outputpaths = xdoc
                                   .Elements(ns + "Project")
                                   .Elements(ns + "PropertyGroup")
                                   .Elements(ns + "OutputPath")
                                   .Select(el => el.Value)
                                   .ToList();

            newproj._references = xdoc
                                  .Elements(ns + "Project")
                                  .Elements(ns + "ItemGroup")
                                  .Elements(ns + "Reference")
                                  .Where(el => el.Attribute("Include") != null)
                                  .OrderBy(el => GetShortRef(el.Attribute("Include").Value))
                                  .Select(el => new AssemblyRef
            {
                Include      = el.Attribute("Include").Value,
                Shortinclude = GetShortRef(el.Attribute("Include").Value),
                Names        = (from elName in el.Elements(ns + "Name")
                                orderby elName.Value
                                select elName.Value).ToList(),
                Hintpaths = (from elHintPath in el.Elements(ns + "HintPath")
                             orderby elHintPath.Value
                             select elHintPath.Value).ToList(),
                Copylocals = (from elName in el.Elements(ns + "Private")
                              orderby elName.Value
                              select elName.Value).ToList(),
                Name      = null,
                Hintpath  = null,
                Copylocal = null
            })
                                  .ToList();

            newproj._projectReferences = xdoc
                                         .Elements(ns + "Project")
                                         .Elements(ns + "ItemGroup")
                                         .Elements(ns + "ProjectReference")
                                         .Where(el => el.Attribute("Include") != null)
                                         .OrderBy(el => Path.GetFileNameWithoutExtension(el.Attribute("Include").Value))
                                         .Select(el => new ProjectRef
            {
                Include      = el.Attribute("Include").Value,
                Shortinclude = Path.GetFileNameWithoutExtension(el.Attribute("Include").Value),
                Names        = (from elName in el.Elements(ns + "Name")
                                orderby elName.Value
                                select elName.Value).ToList(),
                Projects = (from elProject in el.Elements(ns + "Project")
                            orderby elProject.Value
                            select elProject.Value).ToList(),
                Packages = (from elPackage in el.Elements(ns + "Package")
                            orderby elPackage.Value
                            select elPackage.Value).ToList(),
                Name    = null,
                Project = null,
                Package = null
            })
                                         .ToList();


            return(newproj);
        }
예제 #11
0
        // Validate existence of assembly file in hint paths.
        // Notice: newly created assembly refs are searched again, but (if assembly was found earlier) no "->"-message will be shown.
        // Handles absolute paths (not verified much).
        // Always try to replace path, but keep original assembly path if file didn't exist in any specified hintpath.
        // If gac registered dll does exist in any hintpath, add/update hintpath.
        // (If gac registered dll with hintpath doesn't exist in any hintpath: remove hintpath (no matter if it exist in original path -
        //   except if it's private/copylocal))
        private void FixHintPath(string solutionfile, List <string> hintpaths, AssemblyRef assref)
        {
            //string ext = GetAssRefExt(assref.hintpath);

            //string asspath_new2 = LocateAssemblyInHintPaths(solutionfile, hintpaths, assref.shortinclude, "Library");

            /*
             * Om det inte gick att ta reda på en assref's typ (dll/exe), antar vi dll.
             * Det finns då en risk att exe konverteras till dll om vi hittar en dllfil
             * med samma namn i någon hint katalog. Detta är oavsett om assembly referensen
             * är skapad från projref eller inladdad rakt av.
             */

            string ext;

            if (assref.Hintpath == null)
            {
                ext = ".dll";
            }
            else
            {
                ext = Path.GetExtension(assref.Hintpath);
            }

            string asspath_new = LocateAssemblyInHintPaths(solutionfile, hintpaths, assref.Shortinclude, ext);

            if (assref.Hintpath == null)
            {
                if (asspath_new == null)
                {
                    if (!Gac.IsSystemAssembly(assref.Shortinclude, out _, true))
                    {
                        // Error - no existing hint path, and no file found in any specified hint path.
                        ConsoleHelper.ColorWrite(ConsoleColor.Yellow, $"Warning: Couldn't find assembly: '{assref.Shortinclude}{ext}'.");
                    }
                }
                else
                {
                    // Ok - replacing null with new hint path
                    ConsoleHelper.WriteLine($"  Found assembly in hintpath: '{assref.Shortinclude}': -> '{asspath_new}'. Ext: '{ext}'.", true);
                    assref.Hintpath = asspath_new;
                    _modified       = true;
                }
            }
            else
            {
                if (asspath_new == null)
                {
                    if (Gac.IsSystemAssembly(assref.Shortinclude, out _, true) && (!assref.Copylocal.HasValue || assref.Copylocal.Value == false))
                    {
                        // Remove path to gac, even if it's valid on this computer,
                        // the specified command args hintpaths are the only allowed.

                        ConsoleHelper.WriteLine($"  Didn't find gac assembly in any specified hintpath: '{assref.Shortinclude}'. Removing hintpath: '{assref.Hintpath}'.", true);
                        assref.Hintpath = null;
                        _modified       = true;
                    }
                    else
                    {
                        string asspath;
                        if (Path.IsPathRooted(assref.Hintpath))
                        {
                            asspath = assref.Hintpath;
                        }
                        else
                        {
                            asspath = Path.Combine(
                                Path.GetDirectoryName(solutionfile),
                                Path.GetDirectoryName(_sln_path),
                                assref.Hintpath);
                        }

                        if (!File.Exists(asspath))
                        {
                            // Error - no file in existing hint path, and no file found in any specified hint path.
                            ConsoleHelper.ColorWrite(ConsoleColor.Yellow, $"Warning: Couldn't find assembly: '{assref.Shortinclude}': File not found: '{asspath}'.");
                        }
                    }
                }
                else
                {
                    // Ok - if diff, replace existing hint path with new hint path
                    if (string.Compare(asspath_new, assref.Hintpath, true) != 0)
                    {
                        ConsoleHelper.WriteLine($"  Found assembly in specified hintpath: '{assref.Shortinclude}': '{assref.Hintpath}' -> '{asspath_new}'.", true);
                        assref.Hintpath = asspath_new;
                        _modified       = true;
                    }
                }
            }

            return;
        }
예제 #12
0
        public bool Validate(string solutionfile, List <Project> projects)
        {
            bool valid = true;

            if (_sln_guid != null && _proj_guid != null && string.Compare(_sln_guid, _proj_guid, true) != 0)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                         $"Mismatched guid for project '{_sln_path}': Guid in solution: '{_sln_guid}'. Guid in project: '{_proj_guid}'.");
                valid = false;
            }
            if (string.Compare(_sln_shortfilename, Path.GetFileNameWithoutExtension(_sln_path), true) != 0)
            {
                ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                         $"Mismatched name for project '{_sln_path}': Project name in solution: '{_sln_shortfilename}'. File name: '{Path.GetFileNameWithoutExtension(_sln_path)}'.");
                valid = false;
            }

            CheckName(solutionfile, _sln_path, _proj_assemblyname);


            bool afterthis = false;

            foreach (Project proj in projects.OrderBy(p => p._sln_path))
            {
                if (proj == this)
                {
                    afterthis = true;
                    continue;
                }
                if (!afterthis)
                {
                    continue;
                }

                if (_proj_assemblyname == proj._proj_assemblyname)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                             $"Error: Projects have identical assembly names: '{_proj_assemblyname}': '{_sln_path}' and '{proj._sln_path}'.");
                    valid = false;
                }
            }


            foreach (AssemblyRef assref in _references)
            {
                if (string.Compare(assref.Shortinclude, _proj_assemblyname, true) == 0 ||
                    string.Compare(assref.Shortinclude, _sln_shortfilename, true) == 0)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                             $"Error: Project have reference to itself: '{_sln_path}'. Reference: '{assref.Shortinclude}'.");
                    valid = false;
                }


                // This might bail on unknown project types which later could have been converted
                // to project references. In those cases a warning should have been enough.
                if (assref.Hintpath != null)
                {
                    string path = assref.Hintpath;

                    string[] exts = { ".dll", ".exe" };
                    if (!exts.Any(e => path.EndsWith(e, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                                 $"Error: Invalid reference type: '{_sln_path}'. Ext: '{Path.GetExtension(path)}'. Path: '{path}'.");
                        valid = false;
                    }
                }
            }

            foreach (ProjectRef projref in _projectReferences)
            {
                if (string.Compare(projref.Shortinclude, _proj_assemblyname, true) == 0 ||
                    string.Compare(projref.Shortinclude, _sln_shortfilename, true) == 0)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                             $"Error: Project have reference to itself: '{_sln_path}'. Project reference: '{projref.Shortinclude}'.");
                    valid = false;
                }


                // This might bail on names which later could have been converted
                // to assembly references. In those cases a warning should have been enough.
                string shortinclude = projref.Shortinclude;
                if (projects.Any(p => string.Compare(p._sln_shortfilename, shortinclude, true) == 0) &&
                    !projects.Any(p => string.Compare(p._sln_shortfilename, shortinclude, false) == 0))
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                             $"Error: Reference has mismatched casing: Project: '{_sln_path} '. Project reference: '{shortinclude}'. Target project: '{projects.First(p => string.Compare(p._sln_shortfilename, shortinclude, true) == 0)._sln_shortfilename}'.");
                    valid = false;
                }


                // Project references which we need must atleast exist in file system.
                string fullfilename = Path.Combine(
                    Path.GetDirectoryName(solutionfile),
                    Path.GetDirectoryName(_sln_path),
                    projref.Include);
                if (!projects.Any(p => p._sln_shortfilename == projref.Shortinclude) && !File.Exists(fullfilename))
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Red,
                                             $"Error: Project reference does not exist: Project: '{_sln_path}'. Project reference path: '{fullfilename}'.");
                    valid = false;
                }
            }


            return(valid);
        }
예제 #13
0
        public void CompactRefs()
        {
            foreach (AssemblyRef assref in _references)
            {
                if (assref.Names.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, reference: '{assref.Include}', compacting Name elements.");
                    _modified = true;
                }
                if (assref.Names.Count >= 1)
                {
                    assref.Name  = assref.Names[0];
                    assref.Names = null;
                }

                if (assref.Hintpaths.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, reference: '{assref.Include}', compacting HintPath elements.");
                    _modified = true;
                }
                if (assref.Hintpaths.Count >= 1)
                {
                    assref.Hintpath  = assref.Hintpaths[0];
                    assref.Hintpaths = null;
                }

                if (assref.Copylocals.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, reference: '{assref.Include}', compacting Private elements.");
                    _modified = true;
                }
                if (assref.Copylocals.Count >= 1)
                {
                    if (bool.TryParse(assref.Copylocals[0], out bool b))
                    {
                        assref.Copylocal = b;
                    }
                    assref.Copylocals = null;
                }
            }

            foreach (ProjectRef projref in _projectReferences)
            {
                if (projref.Names.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, project reference: '{projref.Include}', compacting Name elements.");
                    _modified = true;
                }
                if (projref.Names.Count >= 1)
                {
                    projref.Name  = projref.Names[0];
                    projref.Names = null;
                }

                if (projref.Projects.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, project reference: '{projref.Include}', compacting Project elements.");
                    _modified = true;
                }
                if (projref.Projects.Count >= 1)
                {
                    projref.Project  = projref.Projects[0];
                    projref.Projects = null;
                }

                if (projref.Packages.Count > 1)
                {
                    ConsoleHelper.ColorWrite(ConsoleColor.Yellow,
                                             $"Warning: Corrupt project file: {_sln_path}, project reference: '{projref.Include}', compacting Package elements.");
                    _modified = true;
                }
                if (projref.Packages.Count >= 1)
                {
                    projref.Package  = projref.Packages[0];
                    projref.Packages = null;
                }
            }

            return;
        }