internal Library LoadLibraryFromManifest(string libManifestFile)
        {
            Project proj;
            Library lib = null;

            string fullpath = ExpandEnvVars(libManifestFile, "");

            try
            {
                if (File.Exists(fullpath))
                {
                    lib = new Library();

                    proj = LoadProject(fullpath);

                    Dictionary<string, string> tbl = new Dictionary<string, string>();
                    tbl["AssemblyName"] = "Name";
                    tbl["ProjectGuid"] = "Guid";

                    LoadStringProps(proj, lib, tbl);

                    Library dbLib = m_helper.FindLibrary(lib.Guid);
                    if (dbLib != null)
                    {
                        System.Diagnostics.Debug.Assert(0 == string.Compare(lib.Guid, dbLib.Guid, true));
                        return dbLib;
                    }

                    foreach (ProjectImportElement imp in proj.Xml.Imports)
                    {
                        switch (Path.GetExtension(imp.Project).ToUpper().Trim())
                        {
                            case ".LIBCATPROJ":
                                LibraryCategory lc = LoadLibraryCategoryProj(imp.Project, Path.GetDirectoryName(fullpath));
                                if (lc != null)
                                {
                                    MFComponent cmp = new MFComponent(MFComponentType.LibraryCategory, lc.Name, lc.Guid, lc.ProjectPath);
                                    lib.Dependencies.Add(cmp);
                                }
                                else
                                {
                                    System.Diagnostics.Debug.Assert(false);
                                }
                                break;
                        }
                    }

                    m_helper.AddLibraryToInventory(lib, true, m_helper.DefaultInventory);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: loading Library file: " + fullpath + "\r\n", e.Message);
                lib = null;
            }
            
            return lib;
        }
        internal Library LoadLibraryProj(string libProjFile, string path, bool fForceReload)
        {
            Project proj;
            string fullpath = ExpandEnvVars(libProjFile, path);
            Library lib = null;

            try
            {
                lib = m_helper.FindLibraryByProject(fullpath);
                Library dbLib = null;

                if (!fForceReload)
                {
                    if (lib != null)
                    {
                        return lib;
                    }
                }

                if (!File.Exists(fullpath))
                {
                    return null;
                }

                if (lib == null)
                {
                    lib = new Library();
                }


                proj = LoadProject(fullpath);

                path = Path.GetDirectoryName(fullpath);

                lib.ProjectPath = ConvertPathToEnv(fullpath);

                if (fullpath.ToUpper().Contains("\\CLR\\"))
                {
                    lib.Level = LibraryLevel.CLR;
                }
                else if (fullpath.ToUpper().Contains("\\SUPPORT\\"))
                {
                    lib.Level = LibraryLevel.Support;
                }
                else if (fullpath.ToUpper().Contains("\\PAL\\"))
                {
                    lib.Level = LibraryLevel.PAL;
                }
                else
                {
                    lib.Level = LibraryLevel.HAL;
                }

                if (Path.GetFileName(fullpath).ToUpper().Contains("_STUB") ||
                    fullpath.ToUpper().Contains("\\STUBS"))
                {
                    lib.IsStub = true;
                }

                Dictionary<string, string> tbl = new Dictionary<string, string>();
                tbl["AssemblyName"] = "Name";
                tbl["ProjectGuid"] = "Guid";

                LoadStringProps(proj, lib, tbl);

                if (!fForceReload)
                {
                    dbLib = m_helper.FindLibrary(lib.Guid);

                    if (dbLib != null)
                    {
                        if (!string.Equals(dbLib.Name, lib.Name, StringComparison.InvariantCultureIgnoreCase))
                        {
                            System.Diagnostics.Debug.WriteLine("WARNING!!! Loaded library name doesn't match database library (possible bad project file)");
                            System.Diagnostics.Debug.WriteLine(dbLib.Name + " != " + lib.Name);
                        }
                        return dbLib;
                    }

                    dbLib = m_helper.FindLibraryByName(lib.Name);
                    if (dbLib != null) return dbLib;
                }

                if (string.IsNullOrEmpty(lib.LibraryFile)) lib.LibraryFile = lib.Name + ".$(LIB_EXT)";
                if (string.IsNullOrEmpty(lib.ManifestFile)) lib.ManifestFile = lib.LibraryFile + ".manifest";

                foreach (ProjectPropertyGroupElement pg in proj.Xml.PropertyGroups)
                {
                    foreach (ProjectPropertyElement bp in pg.Properties)
                    {
                        string cond = CombineConditionals(pg.Condition, bp.Condition);

                        switch (bp.Name)
                        {
                            /*
                        case "OutputType":
                            // don't allow projects to be loaded as library
                            if (0 == string.Compare(bp.Value.Trim(), "Executable", true))
                            {
                                return null;
                            }
                            break;
                            */
                            case "Version":
                                string[] vers = bp.Value.Split('.');
                                if (vers != null)
                                {
                                    if (vers.Length > 0) lib.Version.Major = vers[0];
                                    if (vers.Length > 1) lib.Version.Minor = vers[1];
                                    if (vers.Length > 2) lib.Version.Revision = vers[2];
                                    if (vers.Length > 3) lib.Version.Build = vers[3];
                                }
                                break;
                            case "PlatformIndependentBuild":
                                {
                                    bool fPlatIndep = false;
                                    bool.TryParse(bp.Value, out fPlatIndep);
                                    lib.PlatformIndependent = fPlatIndep;
                                }
                                break;
                            default:
                                {
                                    MFProperty prop = new MFProperty();
                                    prop.Name = bp.Name;
                                    prop.Value = bp.Value;
                                    prop.Condition = cond;
                                    lib.Properties.Add(prop);
                                }
                                break;
                        }
                    }
                }

                if (string.IsNullOrEmpty(lib.Name))
                {
                    string dirName = Path.GetFileName(Path.GetDirectoryName(fullpath));
                    if (string.Compare(dirName, "GlobalLock") == 0)
                    {
                        lib.Name = dirName;
                    }
                    else
                    {
                        return null;
                    }
                }


                LoadCompileItems(proj, lib, path);

                if (string.IsNullOrEmpty(lib.Guid))
                {
                    lib.Guid = System.Guid.NewGuid().ToString("B");
                }

                foreach (ProjectItemGroupElement big in proj.Xml.ItemGroups)
                {
                    foreach (ProjectItemElement bi in big.Items)
                    {
                        string cond = CombineConditionals(big.Condition, bi.Condition);

                        switch (bi.ItemType)
                        {
                            case "RequiredProjects":
                                if (bi.Include.Trim().ToUpper().EndsWith(".PROJ"))
                                {
                                    Library lib2 = LoadLibraryProj(bi.Include, path);

                                    if (lib2 != null)
                                    {
                                        lib.Dependencies.Add(new MFComponent(MFComponentType.Library, lib2.Name, lib2.Guid, bi.Include));
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("Warning! unknown library " + bi.Include);
                                        //System.Diagnostics.Debug.Assert(false);
                                    }
                                }
                                break;
                            case "LibraryCategories":
                                LibraryCategory libCat = LoadLibraryCategoryProj(bi.Include, path);
                                lib.Dependencies.Add(new MFComponent(MFComponentType.LibraryCategory, libCat.Name, libCat.Guid, bi.Include, cond));
                                break;
                            case "FastCompileCPPFile":
                            case "Compile":
                            case "HFiles":
                            case "IncludePaths":
                                // handled by LoadCompileItems
                                break;

                            case "SubDirectories":
                                break;

                            default:
                                {
                                    MFBuildFile f = new MFBuildFile();
                                    f.Condition = cond;
                                    f.File = bi.Include;
                                    f.ItemName = bi.ItemType;
                                    lib.OtherFiles.Add(f);
                                }
                                break;
                        }
                    }
                }

                if (lib.IsStub && lib.LibraryCategory != null && !string.IsNullOrEmpty(lib.LibraryCategory.Guid))
                {
                    LibraryCategory lc = m_helper.FindLibraryCategory(lib.LibraryCategory.Guid);
                    if (lc != null)
                    {
                        lc.StubLibrary = new MFComponent(MFComponentType.Library, lib.Name, lib.Guid, lib.ProjectPath);

                        if (lc.Level != LibraryLevel.CLR && lc.Level != LibraryLevel.Support && lc.Templates.Count == 0)
                        {
                            lc.Templates.Clear();

                            ApiTemplate api = new ApiTemplate();
                            api.FilePath = ConvertPathToEnv(fullpath);
                            lc.Templates.Add(api);

                            foreach (MFBuildFile bf in lib.SourceFiles)
                            {
                                api = new ApiTemplate();
                                api.FilePath = ConvertPathToEnv(Path.Combine(path, bf.File));
                                lc.Templates.Add(api);
                            }
                            foreach (MFBuildFile bf in lib.HeaderFiles)
                            {
                                if (Path.IsPathRooted(MsBuildWrapper.ExpandEnvVars(bf.File,"")) || bf.File.Contains("..")) continue;

                                api = new ApiTemplate();
                                api.FilePath = ConvertPathToEnv(Path.Combine(path, bf.File));
                                lc.Templates.Add(api);
                            }
                            foreach (MFBuildFile bf in lib.FastCompileFiles)
                            {
                                api = new ApiTemplate();
                                api.FilePath = ConvertPathToEnv(Path.Combine(path, bf.File));
                                lc.Templates.Add(api);
                            }
                        }

                    }
                }

                foreach (ProjectTargetElement targ in proj.Xml.Targets)
                {
                    lib.Targets.Add(targ);
                }

                foreach (ProjectImportElement imp in proj.Xml.Imports)
                {
                    switch (Path.GetExtension(imp.Project).ToUpper().Trim())
                    {
                        case ".LIBCATPROJ":
                            LibraryCategory lc = LoadLibraryCategoryProj(imp.Project, path);
                            if (lc != null)
                            {
                                MFComponent cmp = new MFComponent(MFComponentType.LibraryCategory, lc.Name, lc.Guid, lc.ProjectPath);
                                lib.Dependencies.Add(cmp);
                            }
                            else
                            {
                                System.Diagnostics.Debug.Assert(false);
                            }
                            break;
                    }
                }

                m_helper.AddLibraryToInventory(lib, false, m_helper.DefaultInventory);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: loading Library file: " + fullpath + "\r\n", e.Message);
                lib = null;
            }

            return lib;
        }
 public MFComponentHash(Library lib, LibraryCategory type, MFComponent comp)
 {
     Library = lib;
     LibraryCategory = type;
     MFComponent = comp;
 }
        internal void SaveLibraryProj(Library lib)
        {
            if (!string.IsNullOrEmpty(lib.ProjectPath))
            {
                string fullpath = ExpandEnvVars(lib.ProjectPath, "");

                Project proj = LoadProject(fullpath);

                proj.ProjectCollection.UnloadProject(proj);

                proj = new Project();
                proj.Xml.DefaultTargets = "Build";

                try
                {
                    // save properties first
                    Dictionary<string, string> tbl = new Dictionary<string, string>();
                    tbl["Name"] = "AssemblyName";
                    tbl["Guid"] = "ProjectGuid";

                    ProjectPropertyGroupElement bpg = SaveStringProps(proj, lib, tbl);

                    List<MFProperty> delayedProps = new List<MFProperty>();
                    foreach (MFProperty prop in lib.Properties)
                    {
                        if (!prop.Name.Contains("$(") && !prop.Condition.Contains("$("))
                        {
                            ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                            bp.Condition = prop.Condition;
                        }
                        else
                        {
                            delayedProps.Add(prop);
                        }
                    }
                    bpg.AddProperty("PlatformIndependentBuild", lib.PlatformIndependent.ToString().ToLower());
                    bpg.AddProperty("Version", lib.Version.Major + "." + lib.Version.Minor + "." + lib.Version.Revision + "." + lib.Version.Build);
                    
                    // add standard import
                    proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings");

                    proj.Save(fullpath);

                    bpg = proj.Xml.AddPropertyGroup();
                    foreach (MFProperty prop in delayedProps)
                    {
                        ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
                        bp.Condition = prop.Condition;
                    }

                    // add item group
                    SaveCompileItems(proj, lib.FastCompileFiles, lib.HeaderFiles, lib.SourceFiles, lib.OtherFiles, lib.IncludePaths);

                    ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                    foreach (MFComponent cmp in lib.Dependencies)
                    {
                        switch (cmp.ComponentType)
                        {
                            case MFComponentType.Library:
                                Library l = m_helper.FindLibrary(cmp);
                                if (l != null)
                                {
                                    ProjectItemElement bi = big.AddItem("RequiredProjects", ConvertPathToEnv(l.ProjectPath));
                                    bi.Condition = cmp.Conditional;
                                }
                                else if(!string.IsNullOrEmpty(cmp.ProjectPath))
                                {
                                    ProjectItemElement bi = big.AddItem("RequiredProjects", ConvertPathToEnv(cmp.ProjectPath));
                                    bi.Condition = cmp.Conditional;                                    
                                }
                                break;
                            case MFComponentType.LibraryCategory:
                                ProjectImportElement pie = proj.Xml.AddImport(cmp.ProjectPath);
                                pie.Condition = cmp.Conditional;
                                break;
                            default:
                                System.Diagnostics.Debug.Assert(false);
                                break;
                        }
                    }

                    foreach(ProjectTargetElement targ in lib.Targets)
                    {
                        ProjectTargetElement t = proj.Xml.AddTarget(targ.Name);

                        t.Condition = targ.Condition;
                        t.DependsOnTargets = targ.DependsOnTargets;
                        t.Inputs = targ.Inputs;
                        t.Outputs = targ.Outputs;

                        foreach (ProjectTaskElement task in targ.Tasks)
                        {
                            ProjectTaskElement tsk = t.AddTask(task.Name);
                            tsk.Condition = task.Condition;
                            tsk.ContinueOnError = task.ContinueOnError;

                            foreach (KeyValuePair<string,string> param in task.Parameters)
                            {
                                tsk.SetParameter(param.Key, param.Value);
                            }
                        }
                    }

                    proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Targets");
                    
                    proj.Save(fullpath);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error: saving Library file: " + fullpath + "\r\n", e.Message);
                }
            }
        }
        public void AnalyzeLibraries(InventoryHelper helper, MFSolution solution, List<LibraryCategory> unresolved, List<LibraryCategory> removed)
        {
            Dictionary<string, MFComponent> reqLibList = new Dictionary<string, MFComponent>();
            Dictionary<string, MFComponent> unresolvedTypes = new Dictionary<string, MFComponent>();
            List<MFComponent> features = new List<MFComponent>();
            Dictionary<string, MFComponent> preferredLibrary = new Dictionary<string, MFComponent>();
            
            Processor proc = helper.FindProcessor(solution.Processor.Guid);

            libraryCategoriesField.Clear();

            ///
            /// First add all the features and there dependencies
            ///
            if (this.IsClrProject)
            {
                foreach (MFComponent cmpFeat in featuresField)
                {
                    RecurseFeatureDeps(cmpFeat, features, helper);
                }

                ///
                /// get debug transport
                ///
                if (solution.TransportType != null)
                {
                    string key = solution.TransportType.Guid.ToLower();

                    foreach (MFComponent transportFeat in solution.TransportType.FeatureAssociations)
                    {
                        if (!features.Contains(transportFeat))
                        {
                            features.Add(transportFeat);
                        }
                    }
                }
            }

            this.featuresField.Clear();
            foreach (MFComponent cmpFeat in features)
            {
                Feature feat = helper.FindFeature(cmpFeat.Guid);

                this.featuresField.Add(cmpFeat);

                foreach (MFComponent cmp in feat.ComponentDependencies)
                {
                    string key = cmp.Guid.ToLower();

                    if (cmp.ComponentType == MFComponentType.LibraryCategory)
                    {
                        if (!unresolvedTypes.ContainsKey(key))
                        {
                            unresolvedTypes[key] = cmp;
                        }
                    }
                    else if (cmp.ComponentType == MFComponentType.Library)
                    {
                        reqLibList[key] = cmp;
                        RecurseLibCatDeps(cmp, unresolvedTypes, helper, false);
                    }
                }
            }

            ///
            /// Add any required libraries before analyzing all project libraries
            ///
            foreach (Library lib in helper.GetRequiredLibraries())
            {
                // Only add CLR libraries to CLR projects
                if (lib.Level == LibraryLevel.CLR && !this.IsClrProject)
                    continue;

                string key = lib.Guid.ToLower();

                if (!reqLibList.ContainsKey(key))
                {
                    MFComponent cmpNew = new MFComponent(MFComponentType.Library, lib.Name, lib.Guid, lib.ProjectPath);

                    reqLibList[key] = cmpNew;

                    RecurseLibCatDeps(cmpNew, unresolvedTypes, helper, false);
                }
            }

            ///
            /// Now add all required library categories
            ///
            foreach (LibraryCategory lc in helper.GetRequiredLibraryCategories())
            {
                if (lc.Level == LibraryLevel.CLR && !this.isClrProjectField) continue;

                string key = lc.Guid.ToLower();

                if (!unresolvedTypes.ContainsKey(key))
                {
                    MFComponent cmp = new MFComponent(MFComponentType.LibraryCategory, lc.Name, lc.Guid, lc.ProjectPath);

                    unresolvedTypes[lc.Guid.ToLower()] = cmp;
                }
            }

            ///
            /// Add cloned solution's solution-dependent projects
            /// 
            if (solution.m_cloneSolution != null && m_cloneProj != null)
            {
                foreach (MFComponent lib in m_cloneProj.librariesField)
                {
                    // If we have already added a library for the current solution, then just add a new component to the project
                    if (solution.m_clonedLibraryMap.ContainsKey(lib.Guid.ToUpper()))
                    {
                        Library newLib = solution.m_clonedLibraryMap[lib.Guid.ToUpper()];

                        librariesField.Add(new MFComponent(lib.ComponentType, newLib.Name, newLib.Guid, newLib.ProjectPath, lib.Conditional));
                    }
                    // otherwise, create a new library based on the cloned solution's library
                    else if (lib.ProjectPath.ToUpper().Contains("\\SOLUTIONS\\" + solution.m_cloneSolution.Name.ToUpper() + "\\"))
                    {
                        string name = CopyHelper.ReplaceText(lib.Name, solution.m_cloneSolution.Name, solution.Name);
                        string path = CopyHelper.ReplaceText(lib.ProjectPath, solution.m_cloneSolution.Name, solution.Name);
                        string guid = System.Guid.NewGuid().ToString("B").ToUpper();

                        // find cloned solution's library in the intventory
                        Library l = helper.FindLibrary(lib);
                        if (l != null)
                        {
                            Library l2 = new Library();

                            // copy and rename 
                            l.CopyTo(l2);

                            CopyHelper.Rename(l2, solution.m_cloneSolution.Name, solution.Name);

                            l2.Name = name;
                            l2.Guid = guid;
                            l2.ProjectPath = path;

                            // add library to inventory
                            helper.AddLibraryToInventory(l2, false, helper.DefaultInventory);

                            // hash to used so that we don't add multiple libraries for each project
                            solution.m_clonedLibraryMap[lib.Guid.ToUpper()] = l2;
                            // Add the component to this projects library list
                            MFComponent newCmp = new MFComponent(lib.ComponentType, name, guid, path, lib.Conditional);
                            librariesField.Add(newCmp);

                            if (l.HasLibraryCategory)
                            {
                                preferredLibrary[l.LibraryCategory.Guid.ToLower()] = newCmp;
                            }
                        }
                    }
                }
            }

            ///
            /// HACK - fix this to make it data driven (add a field on library categories that allows them to be required by a solution)
            /// 
            if (this.isClrProjectField)
            {
                LibraryCategory lc = helper.FindLibraryCategoryByName("WearLeveling_HAL");

                if (lc != null)
                {
                    string key = lc.Guid.ToLower();
                    if (unresolvedTypes.ContainsKey(key))
                    {
                        solution.m_solRequiredLibCats[key] = unresolvedTypes[key];
                    }
                }
            }
            else if(solution.m_solRequiredLibCats != null)
            {
                foreach (MFComponent cmp in solution.m_solRequiredLibCats.Values)
                {
                    string key = cmp.Guid.ToLower();

                    if (!unresolvedTypes.ContainsKey(key))
                    {
                        unresolvedTypes[key] = cmp;
                    }
                }
            }

            /// 
            /// Use a copy of the libraries, because the libraryField may be updated inside the loop
            /// 
            MFComponent[] __libs = new MFComponent[librariesField.Count];
            librariesField.CopyTo(__libs);

            List<MFComponent> libs = new List<MFComponent>(__libs);
            Dictionary<string, MFComponent> resolvedTypes = new Dictionary<string, MFComponent>();
            List<string> duplicateLibList = new List<string>();

            while (true)
            {
                List<MFComponent> remList = new List<MFComponent>();
                Dictionary<string, MFComponent> newUnresolvedTypes = new Dictionary<string, MFComponent>();

                foreach (MFComponent cmpLib in libs)
                {
                    Library lib = helper.FindLibrary(cmpLib);

                    bool fKeepingLib = false;

                    if (duplicateLibList.Contains(cmpLib.Guid.ToLower()) || lib == null || !ValidateLibrary(lib, solution, proc, helper))
                    {
                        librariesField.Remove(cmpLib);
                        remList.Add(cmpLib);
                        continue;
                    }

                    if (lib.HasLibraryCategory)
                    {
                        if (preferredLibrary.ContainsKey(lib.LibraryCategory.Guid.ToLower()) &&
                            string.Compare(cmpLib.Guid, preferredLibrary[lib.LibraryCategory.Guid.ToLower()].Guid, true) != 0)
                        {
                            fKeepingLib = true;
                        }
                        ///
                        /// Make sure the library selection matches the feature selection
                        ///
                        else if (this.isClrProjectField)
                        {
                            LibraryCategory lc = helper.FindLibraryCategory(lib.LibraryCategory.Guid);

                            if (lc != null)
                            {
                                if (lc.FeatureAssociations.Count > 0)
                                {
                                    bool fFeatureSelected = false;

                                    foreach (MFComponent feat in lc.FeatureAssociations)
                                    {
                                        if (features.Contains(feat))
                                        {
                                            fFeatureSelected = true;
                                            break;
                                        }
                                    }

                                    if (((!fFeatureSelected && !lib.IsStub) || (fFeatureSelected && lib.IsStub)) &&
                                        string.IsNullOrEmpty(cmpLib.Conditional))
                                    {
                                        librariesField.Remove(cmpLib);
                                        remList.Add(cmpLib);
                                        continue;
                                    }
                                }
                            }
                        }

                        if (!fKeepingLib)
                        {
                            string key = lib.LibraryCategory.Guid.ToLower();

                            if (unresolvedTypes.ContainsKey(key) || (!string.IsNullOrEmpty(cmpLib.Conditional) && resolvedTypes.ContainsKey(key)))
                            {
                                unresolvedTypes.Remove(key);
                                resolvedTypes[key] = lib.LibraryCategory;
                                fKeepingLib = true;
                                RecurseLibCatDeps(cmpLib, newUnresolvedTypes, helper, true);
                            }
                        }
                    }
                    else
                    {
                        fKeepingLib = true;
                    }

                    if (fKeepingLib)
                    {
                        remList.Add(cmpLib);

                        duplicateLibList.Add(cmpLib.Guid.ToLower());

                        foreach (MFComponent dep in lib.Dependencies)
                        {
                            if (dep.ComponentType == MFComponentType.Library)
                            {
                                if (duplicateLibList.Contains(dep.Guid.ToLower()) || librariesField.Contains(dep))
                                {
                                    continue;
                                }

                                Library libDep = helper.FindLibrary(dep);

                                if (libDep != null && libDep.HasLibraryCategory)
                                {
                                    string key = libDep.LibraryCategory.Guid.ToLower();
                                    if(!unresolvedTypes.ContainsKey(key) && !resolvedTypes.ContainsKey(key) && !newUnresolvedTypes.ContainsKey(key))
                                    {
                                        newUnresolvedTypes[key] = libDep.LibraryCategory;
                                    }
                                }
                                else
                                {
                                    remList.Add(dep);
                                    librariesField.Add(dep);
                                }
                            }
                        }
                    }
                }

                foreach (MFComponent cmp in remList)
                {
                    if (libs.Contains(cmp))
                    {
                        libs.Remove(cmp);
                    }
                }

                if (newUnresolvedTypes.Count == 0) break;

                foreach (string key in newUnresolvedTypes.Keys)
                {
                    if (!unresolvedTypes.ContainsKey(key) && !resolvedTypes.ContainsKey(key))
                    {
                        unresolvedTypes[key] = newUnresolvedTypes[key];
                    }
                }
            }

            foreach (MFComponent cmp in resolvedTypes.Values)
            {
                libraryCategoriesField.Add(cmp);
            }

            foreach (MFComponent cmp in libs)
            {
                librariesField.Remove(cmp);
            }

            foreach (MFComponent cmp in reqLibList.Values)
            {
                if (!librariesField.Contains(cmp))
                {
                    Library lib = helper.FindLibrary(cmp);
                    if (lib != null && ValidateLibrary(lib, solution, proc, helper))
                    {
                        librariesField.Add(cmp);
                    }
                }
            }

            foreach (MFComponent cmp in unresolvedTypes.Values)
            {
                LibraryCategory lc = helper.FindLibraryCategory(cmp.Guid);

                unresolved.Add(lc);
            }
        }
        public void AddLibraryToInventory(Library library, bool isManifest, Inventory inv)
        {
            if (isManifest)
            {
                // only add manifests if we don't have the project loaded
                if (m_guidToObjectHash.ContainsKey(library.Guid.ToLower()))
                {
                    return;
                }
            }

            string path = MsBuildWrapper.ExpandEnvVars(library.ProjectPath, "").ToLower();
            if (m_projToObjectHash.ContainsKey(path))
            {
                return;

                //Console.WriteLine("Warning: project path alread in inventory: " + library.ProjectPath);
            }
            m_projToObjectHash[path] = library;

            string libFile = Path.GetFileNameWithoutExtension(library.LibraryFile);
            if (!string.IsNullOrEmpty(libFile))
            {
                libFile = libFile.ToLower();

                if (m_fileToObjectHash.ContainsKey(libFile))
                {
                    if (!isManifest)
                    {
                        m_fileToObjectHash[libFile] = library;
                    }
                }
                else
                {
                    m_fileToObjectHash[libFile] = library;
                }
            }
            string guid = library.Guid;

            if (string.IsNullOrEmpty(guid))
            {
                if (!isManifest)
                {
                    Console.WriteLine("WARNING: project without guid found: " + library.ProjectPath);
                }
                library.Guid = Guid.NewGuid().ToString("B");
                guid = library.Guid;
            }
            guid = guid.ToLower();

            if (m_guidToObjectHash.ContainsKey(guid))
            {
                Console.WriteLine("Warning: GUID alread in inventory: " + guid);
            }
            m_guidToObjectHash[guid] = library;

            inv.Libraries.Add(library);
        }
 public void CopyTo(Library dest)
 {
     CopyHelper.CopyTo(this, dest);
 }
        public bool ValidateLibrary(Library lib, MFSolution solution, Processor proc, InventoryHelper helper)
        {
            try
            {
                if (!lib.IsSolutionWizardVisible)
                {
                    return false;
                }

                // don't show processor specific libraries
                if ((lib.ProcessorSpecific != null) && !string.IsNullOrEmpty(lib.ProcessorSpecific.Guid) &&
                    (0 != string.Compare(lib.ProcessorSpecific.Guid, solution.Processor.Guid, true)))
                {
                    return false;
                }

                if (!string.IsNullOrEmpty(lib.CustomFilter))
                {
                    bool OK = false;

                    // don't show custom specific libraries
                    foreach (string libFilter in lib.CustomFilter.Split(';'))
                    {
                        string[] customAttribs = proc.CustomFilter.Split(';');

                        foreach (string attrib in customAttribs)
                        {
                            if (string.Compare(attrib, libFilter, true) == 0)
                            {
                                OK = true;
                                break;
                            }
                        }
                        if (!OK)
                        {
                            foreach (string attrib in solution.CustomFilter.Split(';'))
                            {
                                if (0 == string.Compare(attrib, libFilter, true))
                                {
                                    OK = true;
                                    break;
                                }
                            }
                        }

                        /// 
                        /// Now lets check to see if one of the selected features contains this filter.
                        /// This is used for Network (LWIP) to enable the libraries to be auto selected
                        /// based on which Network feature was choosen
                        /// 
                        if (!OK)
                        {
                            MFProject defProj = null;
                            foreach(MFProject proj in solution.Projects)
                            {
                                if(proj.IsClrProject)
                                {
                                    defProj = proj; 
                                    break;
                                }
                            }

                            foreach (MFComponent feat in defProj.Features)
                            {
                                Feature f = helper.FindFeature(feat.Guid);
                                
                                if (f != null && 0 == string.Compare(f.Filter, libFilter, true))
                                {
                                    OK = true;
                                    break;
                                }
                            }
                        }

                        if (!OK)
                        {
                            OK = (0 == string.Compare(lib.CustomFilter, solution.Name, true));
                        }
                        if (OK) break;
                    }

                    if (!OK) return false;
                }

                if (!IsBootloaderProject() && lib.IsBootloaderLibrary())
                {
                    return false;
                }

                // only add CLR libraries to a CLR project
                if (lib.Level == LibraryLevel.CLR && !this.IsClrProject)
                {
                    return false;
                }

                string projPath = lib.ProjectPath.ToLower();
                if (projPath.Contains(@"\devicecode\drivers\sample\"))
                {
                    return false;
                }

                if (projPath.Contains("\\solutions\\") && !projPath.Contains("\\solutions\\" + solution.Name.ToLower() + "\\"))
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception validating solution libraries: " + e.ToString());
                return false;
            }

            return true;
        }
        private void addLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode parent = treeViewInventory.Nodes[0].Nodes["Libraries"];
            TreeNode sel = treeViewInventory.SelectedNode;
            string path = "";

            if (IsRootNodeOf(parent, sel, ref path))
            {
                while (sel.Tag != null)
                {
                    sel = sel.Parent;
                }
                parent = sel;
            }

            Library newLib  = new Library();

            string []folders = path.Split('\\');
            switch (folders[0].ToUpper())
            {
                case "CLR":
                    newLib.Level = LibraryLevel.CLR;
                    break;
                case "HAL":
                    newLib.Level = LibraryLevel.HAL;
                    break;
                case "PAL":
                    newLib.Level = LibraryLevel.PAL;
                    break;
                case "SUPPORT":
                    newLib.Level = LibraryLevel.Support;
                    break;
            }

            newLib.Groups = string.Join("\\", folders, 1, folders.Length - 1).TrimEnd('\\'); 
            newLib.Guid = Guid.NewGuid().ToString("B").ToUpper();

            TreeNode newNode = AddTreeElement(parent, "<New Library>", newLib, true, DefaultInventory.Libraries, c_defaultInventoryKey);

            DefaultInventory.Libraries.Add(newLib);

            newNode.EnsureVisible();
            treeViewInventory.SelectedNode = newNode;
            newNode.BeginEdit();
        }
        /// <summary>
        /// Adds a "Generate Template" node to the library category node if supported
        /// </summary>
        /// <param name="pcd"></param>
        /// <param name="lc"></param>
        private Library AddGenerateTemplateNode(ProjectComboData pcd, LibraryCategory lc)
        {
            // There are no CLR or Support libraries that can be overriden
            if (lc.Level != LibraryLevel.CLR && (lc.Templates.Count > 0))
            {
                Library lib = null;

                string key = lc.Guid.ToLower();

                // Since each project may have its own set of libraries (and generate template nodes)
                // we need to synchronize the component guids for like categories
                if (m_lcGuidToGenGuid.ContainsKey(key))
                {
                    lib = m_lcGuidToGenGuid[key];
                }
                else
                {
                    lib = new Library();
                    lib.Name = c_GenerateTemplateString;
                    lib.Level = lc.Level;
                    lib.Description = "Generates template code in your solution's DeviceCode directory for the given Library Category." + 
                                      "The project will be generated in Solutions\\" + m_solution.Name + "\\DeviceCode\\" + lc.Name;
                    lib.LibraryCategory = new MFComponent(MFComponentType.LibraryCategory, lc.Name, lc.Guid, lc.ProjectPath);
                    m_lcGuidToGenGuid[key] = lib;
                }

                lib.ProjectPath = m_spoClientPath + "\\Solutions\\" + m_solution.Name + "\\DeviceCode\\" + lc.Name + "\\dotnetmf.proj";

                // add the library to the inventory
                if (null == m_helper.FindLibrary(lib.Guid))
                {
                    m_helper.AddLibraryToInventory(lib, false, m_inv);
                }

                return lib;
            }

            return null;
        }
        public LibraryWrapper CloneLibrary(LibraryWrapper BaseLib, string NewName, string NewGroups, string NewPath, LibraryLevelWrapper NewLevel, bool NewIsStub)
        {
            Library Lib = new Library();
            BaseLib.InnerObject.CopyTo(Lib);

            Lib.Name = NewName;
            Lib.Groups = NewGroups;
            Lib.ProjectPath = NewPath;
            Lib.Level = (LibraryLevel)NewLevel;
            Lib.IsStub = NewIsStub;
            Lib.LibraryFile = Lib.Name + ".$(LIB_EXT)";
            Lib.ManifestFile = Lib.Name + ".$(LIB_EXT).manifest";
            Lib.Properties.Clear();

            return BaseWrapper.Wrap<LibraryWrapper>(Lib);
        }
 public LibraryWrapper CreateLibrary(string Name, LibraryLevelWrapper Level, string Description, string ProjectPath, bool IsTemplate, ComponentWrapper LibraryCategory)
 {
     Library library = new Library
     {
         Name = Name,
         Level = (LibraryLevel)Level,
         Description = Description,
         ProjectPath = ProjectPath
     };
     LibraryWrapper wrapper = BaseWrapper.Wrap<LibraryWrapper>(library);
     wrapper.LibraryCategory = LibraryCategory;
     wrapper.IsTemplate = IsTemplate;
     return wrapper;
 }
        public LibraryWrapper CreateLibrary(string name, string groups, string path, LibraryLevelWrapper level, bool isStub)
        {
            Library Lib = new Library
            {
                Name = name,
                Groups = groups,
                ProjectPath = path,
                Level = (LibraryLevel)level,
                IsStub = isStub,
                LibraryFile = name + ".$(LIB_EXT)",
                ManifestFile = name + ".$(LIB_EXT).manifest"
            };

            return BaseWrapper.Wrap<LibraryWrapper>(Lib);
        }