예제 #1
0
        /// <summary>
        /// Saves the current <see cref="MshConsoleInfo"/> object to a file specified
        /// by <paramref name="path"/>. IsDirty is set to false once file is saved.
        /// </summary>
        /// <param name="path">
        /// If path is not an absolute path, then an absolute path is constructed by
        /// using Path.GetFullPath() API.
        /// </param>
        /// <exception cref="PSArgumentException">
        /// 1.Path does not specify proper file extension.
        /// </exception>
        /// <exception cref="PSArgumentNullException">
        /// 1. Path is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// path contains one or more of the invalid characters defined in System.IO.Path.InvalidPathChars.
        /// </exception>
        internal void SaveAsConsoleFile(string path)
        {
            if (null == path)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            // Check whether the filename specified is an absolute path.
            string absolutePath = path;

            if (!Path.IsPathRooted(absolutePath))
            {
                absolutePath = Path.GetFullPath(Filename);
            }

            // Ignore case when looking for file extension.
            if (!absolutePath.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't have the right extension {1}.", path, StringLiterals.PowerShellConsoleFileExtension);
                throw PSTraceSource.NewArgumentException("absolutePath", ConsoleInfoErrorStrings.BadConsoleExtension);
            }

            //ConsoleFileElement will write to file
            PSConsoleFileElement.WriteToFile(absolutePath, this.PSVersion, this.ExternalPSSnapIns);
            //update the console file variable
            Filename = absolutePath;
            IsDirty  = false;
        }
예제 #2
0
 internal void Save()
 {
     if (this.fileName == null)
     {
         throw PSTraceSource.NewInvalidOperationException("ConsoleInfoErrorStrings", "SaveDefaultError", new object[] { "" });
     }
     PSConsoleFileElement.WriteToFile(this.fileName, this.PSVersion, this.ExternalPSSnapIns);
     this.isDirty = false;
 }
예제 #3
0
 private Collection <PSSnapInInfo> Load(
     string path,
     out PSConsoleLoadException cle)
 {
     using (MshConsoleInfo.tracer.TraceMethod())
     {
         cle = (PSConsoleLoadException)null;
         MshConsoleInfo._mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", (object)path);
         if (string.IsNullOrEmpty(path))
         {
             throw MshConsoleInfo.tracer.NewArgumentNullException(nameof(path));
         }
         if (!Path.IsPathRooted(path))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", (object)path);
             throw MshConsoleInfo.tracer.NewArgumentException(nameof(path), "ConsoleInfoErrorStrings", "PathNotAbsolute", (object)path);
         }
         if (!path.EndsWith(".psc1", StringComparison.OrdinalIgnoreCase))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", (object)path, (object)".psc1");
             throw MshConsoleInfo.tracer.NewArgumentException(nameof(path), "ConsoleInfoErrorStrings", "BadConsoleExtension", (object)"");
         }
         PSConsoleFileElement fromFile = PSConsoleFileElement.CreateFromFile(path);
         if (!Utils.IsVersionSupported(fromFile.MonadVersion))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", (object)fromFile.MonadVersion);
             throw MshConsoleInfo.tracer.NewArgumentException("PSVersion", "ConsoleInfoErrorStrings", "BadMonadVersion", (object)fromFile.MonadVersion, (object)this.psVersion.ToString());
         }
         Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>();
         foreach (string psSnapIn in fromFile.PSSnapIns)
         {
             try
             {
                 this.AddPSSnapIn(psSnapIn);
             }
             catch (PSArgumentException ex)
             {
                 PSSnapInException psSnapInException = new PSSnapInException(psSnapIn, ex.Message, (Exception)ex);
                 MshConsoleInfo._mshsnapinTracer.TraceException((Exception)psSnapInException);
                 exceptions.Add(psSnapInException);
             }
             catch (SecurityException ex)
             {
                 string            message           = ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInReadError");
                 PSSnapInException psSnapInException = new PSSnapInException(psSnapIn, message, (Exception)ex);
                 MshConsoleInfo._mshsnapinTracer.TraceException((Exception)psSnapInException);
                 exceptions.Add(psSnapInException);
             }
         }
         if (exceptions.Count > 0)
         {
             cle = new PSConsoleLoadException(this, exceptions);
         }
         this.isDirty = false;
         return(this.externalPSSnapIns);
     }
 }
예제 #4
0
        /// <summary>
        /// Saves the current <see cref="MshConsoleInfo"/> object to its console file.
        /// IsDirty is set to false once file is saved.
        /// </summary>
        /// <exception cref="PSInvalidOperationException">
        /// Msh is loaded with default mshsnapins. $console is currently empty.
        /// </exception>
        internal void Save()
        {
            if (null == Filename)
            {
                throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.SaveDefaultError);
            }

            PSConsoleFileElement.WriteToFile(Filename, this.PSVersion, this.ExternalPSSnapIns);
            IsDirty = false;
        }
예제 #5
0
 internal void Save()
 {
     using (MshConsoleInfo.tracer.TraceMethod())
     {
         if (this.fileName == null)
         {
             throw MshConsoleInfo.tracer.NewInvalidOperationException("ConsoleInfoErrorStrings", "SaveDefaultError", (object)"");
         }
         PSConsoleFileElement.WriteToFile(this, this.fileName);
         this.isDirty = false;
     }
 }
예제 #6
0
        private Collection <PSSnapInInfo> Load(string path, out PSConsoleLoadException cle)
        {
            cle = null;
            _mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", new object[] { path });
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }
            if (!Path.IsPathRooted(path))
            {
                _mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", new object[] { path });
                throw PSTraceSource.NewArgumentException("path", "ConsoleInfoErrorStrings", "PathNotAbsolute", new object[] { path });
            }
            if (!path.EndsWith(".psc1", StringComparison.OrdinalIgnoreCase))
            {
                _mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", new object[] { path, ".psc1" });
                throw PSTraceSource.NewArgumentException("path", "ConsoleInfoErrorStrings", "BadConsoleExtension", new object[] { "" });
            }
            PSConsoleFileElement element = PSConsoleFileElement.CreateFromFile(path);

            if (!Utils.IsPSVersionSupported(element.MonadVersion))
            {
                _mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", new object[] { element.MonadVersion });
                throw PSTraceSource.NewArgumentException("PSVersion", "ConsoleInfoErrorStrings", "BadMonadVersion", new object[] { element.MonadVersion, this.psVersion.ToString() });
            }
            Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>();

            foreach (string str in element.PSSnapIns)
            {
                try
                {
                    this.AddPSSnapIn(str);
                }
                catch (PSArgumentException exception)
                {
                    PSSnapInException item = new PSSnapInException(str, exception.Message, exception);
                    exceptions.Add(item);
                }
                catch (SecurityException exception3)
                {
                    string            pSSnapInReadError = ConsoleInfoErrorStrings.PSSnapInReadError;
                    PSSnapInException exception4        = new PSSnapInException(str, pSSnapInReadError, exception3);
                    exceptions.Add(exception4);
                }
            }
            if (exceptions.Count > 0)
            {
                cle = new PSConsoleLoadException(this, exceptions);
            }
            this.isDirty = false;
            return(this.externalPSSnapIns);
        }
예제 #7
0
 internal void SaveAsConsoleFile(string path)
 {
     using (MshConsoleInfo.tracer.TraceMethod())
     {
         string path1 = path != null ? path : throw MshConsoleInfo.tracer.NewArgumentNullException(nameof(path));
         if (!Path.IsPathRooted(path1))
         {
             path1 = Path.GetFullPath(this.fileName);
         }
         if (!path1.EndsWith(".psc1", StringComparison.OrdinalIgnoreCase))
         {
             MshConsoleInfo._mshsnapinTracer.TraceError("Console file {0} doesn't have the right extension {1}.", (object)path, (object)".psc1");
             throw MshConsoleInfo.tracer.NewArgumentException("absolutePath", "ConsoleInfoErrorStrings", "BadConsoleExtension", (object)"");
         }
         PSConsoleFileElement.WriteToFile(this, path1);
         this.fileName = path1;
         this.isDirty  = false;
     }
 }
예제 #8
0
        internal void SaveAsConsoleFile(string path)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }
            string fullPath = path;

            if (!Path.IsPathRooted(fullPath))
            {
                fullPath = Path.GetFullPath(this.fileName);
            }
            if (!fullPath.EndsWith(".psc1", StringComparison.OrdinalIgnoreCase))
            {
                _mshsnapinTracer.TraceError("Console file {0} doesn't have the right extension {1}.", new object[] { path, ".psc1" });
                throw PSTraceSource.NewArgumentException("absolutePath", "ConsoleInfoErrorStrings", "BadConsoleExtension", new object[] { "" });
            }
            PSConsoleFileElement.WriteToFile(fullPath, this.PSVersion, this.ExternalPSSnapIns);
            this.fileName = fullPath;
            this.isDirty  = false;
        }
예제 #9
0
 internal static PSConsoleFileElement CreateFromFile(string path)
 {
     _mshsnapinTracer.WriteLine("Loading console info from file {0}.", new object[] { path });
     XmlDocument document = InternalDeserializer.LoadUnsafeXmlDocument(new FileInfo(path), false, null);
     if (document["PSConsoleFile"] == null)
     {
         _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", new object[] { path, "PSConsoleFile" });
         throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MonadConsoleNotFound, path));
     }
     if ((document["PSConsoleFile"]["PSVersion"] == null) || string.IsNullOrEmpty(document["PSConsoleFile"]["PSVersion"].InnerText))
     {
         _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", new object[] { path, "PSVersion" });
         throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MonadVersionNotFound, path));
     }
     XmlElement element = document["PSConsoleFile"];
     if (element.HasAttribute("ConsoleSchemaVersion"))
     {
         if (!element.GetAttribute("ConsoleSchemaVersion").Equals("1.0", StringComparison.OrdinalIgnoreCase))
         {
             string format = StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path);
             string errorMessageFormat = string.Format(Thread.CurrentThread.CurrentCulture, format, new object[] { "1.0" });
             _mshsnapinTracer.TraceError(errorMessageFormat, new object[0]);
             throw new XmlException(errorMessageFormat);
         }
     }
     else
     {
         _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", new object[] { path });
         throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path));
     }
     element = document["PSConsoleFile"]["PSVersion"];
     PSConsoleFileElement element2 = new PSConsoleFileElement(element.InnerText.Trim());
     bool flag = false;
     bool flag2 = false;
     for (System.Xml.XmlNode node = document["PSConsoleFile"].FirstChild; node != null; node = node.NextSibling)
     {
         if (node.NodeType != XmlNodeType.Comment)
         {
             element = node as XmlElement;
             if (element == null)
             {
                 throw new XmlException(ConsoleInfoErrorStrings.BadXMLFormat);
             }
             if (element.Name == "PSVersion")
             {
                 if (flag2)
                 {
                     _mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", new object[] { path });
                     throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, "PSVersion"));
                 }
                 flag2 = true;
             }
             else
             {
                 if (element.Name != "PSSnapIns")
                 {
                     _mshsnapinTracer.TraceError("Tag {0} is not supported in console file", new object[] { element.Name });
                     throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadXMLElementFound, new object[] { element.Name, "PSConsoleFile", "PSVersion", "PSSnapIns" }));
                 }
                 if (flag)
                 {
                     _mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", new object[] { path });
                     throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, "PSSnapIns"));
                 }
                 flag = true;
                 for (System.Xml.XmlNode node2 = element.FirstChild; node2 != null; node2 = node2.NextSibling)
                 {
                     XmlElement element3 = node2 as XmlElement;
                     if ((element3 == null) || (element3.Name != "PSSnapIn"))
                     {
                         throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInNotFound, node2.Name));
                     }
                     string attribute = element3.GetAttribute("Name");
                     if (string.IsNullOrEmpty(attribute))
                     {
                         throw new XmlException(ConsoleInfoErrorStrings.IDNotFound);
                     }
                     element2.mshsnapins.Add(attribute);
                     _mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", new object[] { attribute, path });
                 }
             }
         }
     }
     return element2;
 }
예제 #10
0
        internal static PSConsoleFileElement CreateFromFile(string path)
        {
            _mshsnapinTracer.WriteLine("Loading console info from file {0}.", new object[] { path });
            XmlDocument document = InternalDeserializer.LoadUnsafeXmlDocument(new FileInfo(path), false, null);

            if (document["PSConsoleFile"] == null)
            {
                _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", new object[] { path, "PSConsoleFile" });
                throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MonadConsoleNotFound, path));
            }
            if ((document["PSConsoleFile"]["PSVersion"] == null) || string.IsNullOrEmpty(document["PSConsoleFile"]["PSVersion"].InnerText))
            {
                _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", new object[] { path, "PSVersion" });
                throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MonadVersionNotFound, path));
            }
            XmlElement element = document["PSConsoleFile"];

            if (element.HasAttribute("ConsoleSchemaVersion"))
            {
                if (!element.GetAttribute("ConsoleSchemaVersion").Equals("1.0", StringComparison.OrdinalIgnoreCase))
                {
                    string format             = StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path);
                    string errorMessageFormat = string.Format(Thread.CurrentThread.CurrentCulture, format, new object[] { "1.0" });
                    _mshsnapinTracer.TraceError(errorMessageFormat, new object[0]);
                    throw new XmlException(errorMessageFormat);
                }
            }
            else
            {
                _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", new object[] { path });
                throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path));
            }
            element = document["PSConsoleFile"]["PSVersion"];
            PSConsoleFileElement element2 = new PSConsoleFileElement(element.InnerText.Trim());
            bool flag  = false;
            bool flag2 = false;

            for (System.Xml.XmlNode node = document["PSConsoleFile"].FirstChild; node != null; node = node.NextSibling)
            {
                if (node.NodeType != XmlNodeType.Comment)
                {
                    element = node as XmlElement;
                    if (element == null)
                    {
                        throw new XmlException(ConsoleInfoErrorStrings.BadXMLFormat);
                    }
                    if (element.Name == "PSVersion")
                    {
                        if (flag2)
                        {
                            _mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", new object[] { path });
                            throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, "PSVersion"));
                        }
                        flag2 = true;
                    }
                    else
                    {
                        if (element.Name != "PSSnapIns")
                        {
                            _mshsnapinTracer.TraceError("Tag {0} is not supported in console file", new object[] { element.Name });
                            throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadXMLElementFound, new object[] { element.Name, "PSConsoleFile", "PSVersion", "PSSnapIns" }));
                        }
                        if (flag)
                        {
                            _mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", new object[] { path });
                            throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, "PSSnapIns"));
                        }
                        flag = true;
                        for (System.Xml.XmlNode node2 = element.FirstChild; node2 != null; node2 = node2.NextSibling)
                        {
                            XmlElement element3 = node2 as XmlElement;
                            if ((element3 == null) || (element3.Name != "PSSnapIn"))
                            {
                                throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInNotFound, node2.Name));
                            }
                            string attribute = element3.GetAttribute("Name");
                            if (string.IsNullOrEmpty(attribute))
                            {
                                throw new XmlException(ConsoleInfoErrorStrings.IDNotFound);
                            }
                            element2.mshsnapins.Add(attribute);
                            _mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", new object[] { attribute, path });
                        }
                    }
                }
            }
            return(element2);
        }
예제 #11
0
        /// <summary>
        /// Loads a Monad Console file specified by <paramref name="path"/>
        /// </summary>
        /// <param name="path">
        /// The absolute path from which the content is loaded.
        /// </param>
        /// <param name="cle">
        /// PSConsoleLoadException occurred while loading this console file. This object
        /// also contains specific PSSnapInExceptions that occurred while loading.
        /// </param>
        /// <returns>
        /// A list of <see cref="PSSnapInInfo"/> objects specified in the console file.
        /// </returns>
        /// <exception cref="PSArgumentNullException">
        /// Path is null.
        /// </exception>
        /// <exception cref="PSArgumentException">
        /// 1. Path does not specify proper file extension.
        /// 2. PSSnapInId doesnt contain valid characters.
        /// 3. Path is not an Absolute Path.
        ///    Example of valid paths:"\\MyDir\\MyFile.txt" and "C:\\MyDir".
        /// </exception>
        /// <exception cref="ArgumentException">
        /// path contains one or more of the invalid characters defined in System.IO.Path.InvalidPathChars.
        /// </exception>
        /// <exception cref="XmlException">
        /// Unable to load/parse the file specified by path.
        /// </exception>
        private Collection <PSSnapInInfo> Load(string path, out PSConsoleLoadException cle)
        {
            // Initialize the out parameter..
            cle = null;

            s_mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", path);

            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            // Check whether the path is an absolute path
            if (!Path.IsPathRooted(path))
            {
                s_mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", path);

                throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.PathNotAbsolute, path);
            }

            if (!path.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                s_mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", path, StringLiterals.PowerShellConsoleFileExtension);

                throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.BadConsoleExtension);
            }

            PSConsoleFileElement consoleFileElement;

            // exceptions are thrown to the caller
            consoleFileElement = PSConsoleFileElement.CreateFromFile(path);

            // consoleFileElement will never be null..
            if (!Utils.IsPSVersionSupported(consoleFileElement.MonadVersion))
            {
                s_mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", consoleFileElement.MonadVersion);

                throw PSTraceSource.NewArgumentException("PSVersion", ConsoleInfoErrorStrings.BadMonadVersion, consoleFileElement.MonadVersion,
                                                         PSVersion.ToString());
            }

            // Create a store for exceptions
            Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>();

            foreach (string mshsnapin in consoleFileElement.PSSnapIns)
            {
                try
                {
                    this.AddPSSnapIn(mshsnapin);
                }
                catch (PSArgumentException ae)
                {
                    PSSnapInException sle = new PSSnapInException(mshsnapin, ae.Message, ae);

                    // Eat ArgumentException and continue..
                    exceptions.Add(sle);
                }
                catch (System.Security.SecurityException se)
                {
                    string            message = ConsoleInfoErrorStrings.PSSnapInReadError;
                    PSSnapInException sle     = new PSSnapInException(mshsnapin, message, se);
                    // Eat SecurityException and continue..

                    exceptions.Add(sle);
                }
            }

            // Before returning check whether there are any exceptions
            if (exceptions.Count > 0)
            {
                cle = new PSConsoleLoadException(this, exceptions);
            }

            // We are able to load console file and currently monad engine
            // can service this. So mark the isdirty flag.
            IsDirty = false;

            return(_externalPSSnapIns);
        }
예제 #12
0
        /// <summary>
        /// Reads a Monad Console file specified by <paramref name="path"/> and constructs
        /// a PSConsoleFileElement.
        /// </summary>
        /// <param name="path">The absolute path of the file to read from.</param>
        /// <returns>A MShConsoleFileElement object that represents content of the console file.</returns>
        /// <remarks>The return object wont be null.</remarks>
        /// <exception cref="XmlException">
        /// There is a load or parser error in the XML.
        /// </exception>
        /// <!--
        /// Caller should not pass a null value for path.
        /// -->
        internal static PSConsoleFileElement CreateFromFile(string path)
        {
            Diagnostics.Assert(path != null, "Filename should not be null");

            s_mshsnapinTracer.WriteLine("Loading console info from file {0}.", path);

            XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                new FileInfo(path),
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */

            // Validate content
            if (doc[MSHCONSOLEFILE] == null)
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, MSHCONSOLEFILE);

                throw new XmlException(
                          StringUtil.Format(ConsoleInfoErrorStrings.MonadConsoleNotFound, path));
            }

            if ((doc[MSHCONSOLEFILE][PSVERSION] == null) ||
                (string.IsNullOrEmpty(doc[MSHCONSOLEFILE][PSVERSION].InnerText)))
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, PSVERSION);

                throw new XmlException(
                          StringUtil.Format(ConsoleInfoErrorStrings.MonadVersionNotFound, path));
            }

            // This will never be null..
            XmlElement xmlElement = (XmlElement)doc[MSHCONSOLEFILE];

            if (xmlElement.HasAttribute(CSCHEMAVERSION))
            {
                if (!xmlElement.GetAttribute(CSCHEMAVERSION).Equals(CSCHEMAVERSIONNUMBER, StringComparison.OrdinalIgnoreCase))
                {
                    string resourceTemplate =
                        StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path);
                    string message = string.Format(CultureInfo.CurrentCulture,
                                                   resourceTemplate, CSCHEMAVERSIONNUMBER);

                    s_mshsnapinTracer.TraceError(message);

                    throw new XmlException(message);
                }
            }
            else
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", path);

                throw new XmlException(
                          StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path));
            }

            //process MonadVersion
            //This will never be null..
            xmlElement = (XmlElement)doc[MSHCONSOLEFILE][PSVERSION];

            // Construct PSConsoleFileElement as we seem to have valid data
            PSConsoleFileElement consoleFileElement = new PSConsoleFileElement(xmlElement.InnerText.Trim());

            bool isPSSnapInsProcessed = false;
            bool isPSVersionProcessed = false;

            for (XmlNode mshSnapInsNode = doc["PSConsoleFile"].FirstChild; mshSnapInsNode != null; mshSnapInsNode = mshSnapInsNode.NextSibling)
            {
                if (mshSnapInsNode.NodeType == XmlNodeType.Comment)
                {
                    // support comments inside a PSConsoleFile Element
                    continue;
                }

                //populate mshsnapin information
                xmlElement = mshSnapInsNode as XmlElement;

                if (null == xmlElement)
                {
                    throw new XmlException(ConsoleInfoErrorStrings.BadXMLFormat);
                }

                if (xmlElement.Name == PSVERSION)
                {
                    if (isPSVersionProcessed)
                    {
                        s_mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", path);

                        throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, PSVERSION));
                    }

                    isPSVersionProcessed = true;
                    continue;
                }

                if (xmlElement.Name != SNAPINS)
                {
                    s_mshsnapinTracer.TraceError("Tag {0} is not supported in console file", xmlElement.Name);

                    throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadXMLElementFound, xmlElement.Name, MSHCONSOLEFILE, PSVERSION, SNAPINS));
                }

                // PSSnapIns element is already processed. We dont support multiple
                // PSSnapIns elements
                if (isPSSnapInsProcessed)
                {
                    s_mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", path);

                    throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, SNAPINS));
                }

                // We are about to process mshsnapins element..so we should not
                // process some more mshsnapins elements..this boolean keeps track
                // of this.
                isPSSnapInsProcessed = true;

                // decode all the child nodes of <PSSnapIns> node...
                for (XmlNode mshSnapInNode = xmlElement.FirstChild; mshSnapInNode != null; mshSnapInNode = mshSnapInNode.NextSibling)
                {
                    XmlElement mshSnapInElement = mshSnapInNode as XmlElement;

                    if ((null == mshSnapInElement) || (mshSnapInElement.Name != SNAPIN))
                    {
                        throw new XmlException(
                                  StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInNotFound, mshSnapInNode.Name));
                    }

                    string id = mshSnapInElement.GetAttribute(SNAPINNAME);

                    if (string.IsNullOrEmpty(id))
                    {
                        throw new XmlException(ConsoleInfoErrorStrings.IDNotFound);
                    }

                    consoleFileElement.PSSnapIns.Add(id);

                    s_mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", id, path);
                }
            }

            return(consoleFileElement);
        }
예제 #13
0
 internal static PSConsoleFileElement CreateFromFile(string path)
 {
     using (PSConsoleFileElement.tracer.TraceMethod())
     {
         PSConsoleFileElement._mshsnapinTracer.WriteLine("Loading console info from file {0}.", (object)path);
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.Load(path);
         if (xmlDocument["PSConsoleFile"] == null)
         {
             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", (object)path, (object)"PSConsoleFile");
             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MonadConsoleNotFound", (object)path));
         }
         if (xmlDocument["PSConsoleFile"]["PSVersion"] == null || string.IsNullOrEmpty(xmlDocument["PSConsoleFile"]["PSVersion"].InnerText))
         {
             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", (object)path, (object)"PSVersion");
             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MonadVersionNotFound", (object)path));
         }
         XmlElement xmlElement1 = xmlDocument["PSConsoleFile"];
         if (xmlElement1.HasAttribute("ConsoleSchemaVersion"))
         {
             if (!xmlElement1.GetAttribute("ConsoleSchemaVersion").Equals("1.0", StringComparison.OrdinalIgnoreCase))
             {
                 string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadConsoleVersion", (object)path), (object)"1.0");
                 PSConsoleFileElement._mshsnapinTracer.TraceError(str);
                 throw new XmlException(str);
             }
             PSConsoleFileElement consoleFileElement = new PSConsoleFileElement(xmlDocument["PSConsoleFile"]["PSVersion"].InnerText.Trim());
             bool flag1 = false;
             bool flag2 = false;
             for (XmlNode xmlNode1 = xmlDocument["PSConsoleFile"].FirstChild; xmlNode1 != null; xmlNode1 = xmlNode1.NextSibling)
             {
                 if (xmlNode1.NodeType != XmlNodeType.Comment)
                 {
                     if (!(xmlNode1 is XmlElement xmlElement))
                     {
                         throw new XmlException(ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "BadXMLFormat"));
                     }
                     if (xmlElement.Name == "PSVersion")
                     {
                         if (flag2)
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", (object)path);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MultipleMshSnapinsElementNotSupported", (object)"PSVersion"));
                         }
                         flag2 = true;
                     }
                     else
                     {
                         if (xmlElement.Name != "PSSnapIns")
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Tag {0} is not supported in console file", (object)xmlElement.Name);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadXMLElementFound", (object)xmlElement.Name, (object)"PSConsoleFile", (object)"PSVersion", (object)"PSSnapIns"));
                         }
                         if (flag1)
                         {
                             PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", (object)path);
                             throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "MultipleMshSnapinsElementNotSupported", (object)"PSSnapIns"));
                         }
                         flag1 = true;
                         for (XmlNode xmlNode2 = xmlElement.FirstChild; xmlNode2 != null; xmlNode2 = xmlNode2.NextSibling)
                         {
                             if (!(xmlNode2 is XmlElement xmlElement) || xmlElement.Name != "PSSnapIn")
                             {
                                 throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "PSSnapInNotFound", (object)xmlNode2.Name));
                             }
                             string attribute = xmlElement.GetAttribute("Name");
                             if (string.IsNullOrEmpty(attribute))
                             {
                                 throw new XmlException(ResourceManagerCache.GetResourceString("ConsoleInfoErrorStrings", "IDNotFound"));
                             }
                             consoleFileElement.mshsnapins.Add(attribute);
                             PSConsoleFileElement._mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", (object)attribute, (object)path);
                         }
                     }
                 }
             }
             return(consoleFileElement);
         }
         PSConsoleFileElement._mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", (object)path);
         throw new XmlException(ResourceManagerCache.FormatResourceString("ConsoleInfoErrorStrings", "BadConsoleVersion", (object)path));
     }
 }
예제 #14
0
        /// <summary>
        /// Reads a Monad Console file specified by <paramref name="path"/> and constructs
        /// a PSConsoleFileElement.
        /// </summary>
        /// <param name="path">The absolute path of the file to read from.</param>
        /// <returns>A MShConsoleFileElement object that represents content of the console file.</returns>
        /// <remarks>The return object wont be null.</remarks>
        /// <exception cref="XmlException">
        /// There is a load or parser error in the XML.
        /// </exception>
        /// <!--
        /// Caller should not pass a null value for path.
        /// -->
        internal static PSConsoleFileElement CreateFromFile(string path)
        {
            Diagnostics.Assert(path != null, "Filename should not be null");

            s_mshsnapinTracer.WriteLine("Loading console info from file {0}.", path);

            XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                new FileInfo(path),
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */

            // Validate content
            if (doc[MSHCONSOLEFILE] == null)
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, MSHCONSOLEFILE);

                throw new XmlException(
                    StringUtil.Format(ConsoleInfoErrorStrings.MonadConsoleNotFound, path));
            }

            if ((doc[MSHCONSOLEFILE][PSVERSION] == null) ||
                 (string.IsNullOrEmpty(doc[MSHCONSOLEFILE][PSVERSION].InnerText)))
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, PSVERSION);

                throw new XmlException(
                    StringUtil.Format(ConsoleInfoErrorStrings.MonadVersionNotFound, path));
            }

            // This will never be null..
            XmlElement xmlElement = (XmlElement)doc[MSHCONSOLEFILE];

            if (xmlElement.HasAttribute(CSCHEMAVERSION))
            {
                if (!xmlElement.GetAttribute(CSCHEMAVERSION).Equals(CSCHEMAVERSIONNUMBER, StringComparison.OrdinalIgnoreCase))
                {
                    string resourceTemplate =
                            StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path);
                    string message = string.Format(CultureInfo.CurrentCulture,
                        resourceTemplate, CSCHEMAVERSIONNUMBER);

                    s_mshsnapinTracer.TraceError(message);

                    throw new XmlException(message);
                }
            }
            else
            {
                s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", path);

                throw new XmlException(
                        StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path));
            }

            //process MonadVersion
            //This will never be null..
            xmlElement = (XmlElement)doc[MSHCONSOLEFILE][PSVERSION];

            // Construct PSConsoleFileElement as we seem to have valid data
            PSConsoleFileElement consoleFileElement = new PSConsoleFileElement(xmlElement.InnerText.Trim());

            bool isPSSnapInsProcessed = false;
            bool isPSVersionProcessed = false;

            for (XmlNode mshSnapInsNode = doc["PSConsoleFile"].FirstChild; mshSnapInsNode != null; mshSnapInsNode = mshSnapInsNode.NextSibling)
            {
                if (mshSnapInsNode.NodeType == XmlNodeType.Comment)
                {
                    // support comments inside a PSConsoleFile Element
                    continue;
                }

                //populate mshsnapin information
                xmlElement = mshSnapInsNode as XmlElement;

                if (null == xmlElement)
                {
                    throw new XmlException(ConsoleInfoErrorStrings.BadXMLFormat);
                }

                if (xmlElement.Name == PSVERSION)
                {
                    if (isPSVersionProcessed)
                    {
                        s_mshsnapinTracer.TraceError("Console file {0} contains more than one  msh versions", path);

                        throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, PSVERSION));
                    }

                    isPSVersionProcessed = true;
                    continue;
                }

                if (xmlElement.Name != SNAPINS)
                {
                    s_mshsnapinTracer.TraceError("Tag {0} is not supported in console file", xmlElement.Name);

                    throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadXMLElementFound, xmlElement.Name, MSHCONSOLEFILE, PSVERSION, SNAPINS));
                }

                // PSSnapIns element is already processed. We dont support multiple
                // PSSnapIns elements
                if (isPSSnapInsProcessed)
                {
                    s_mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", path);

                    throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, SNAPINS));
                }

                // We are about to process mshsnapins element..so we should not 
                // process some more mshsnapins elements..this boolean keeps track
                // of this.
                isPSSnapInsProcessed = true;

                // decode all the child nodes of <PSSnapIns> node...
                for (XmlNode mshSnapInNode = xmlElement.FirstChild; mshSnapInNode != null; mshSnapInNode = mshSnapInNode.NextSibling)
                {
                    XmlElement mshSnapInElement = mshSnapInNode as XmlElement;

                    if ((null == mshSnapInElement) || (mshSnapInElement.Name != SNAPIN))
                    {
                        throw new XmlException(
                            StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInNotFound, mshSnapInNode.Name));
                    }

                    string id = mshSnapInElement.GetAttribute(SNAPINNAME);

                    if (string.IsNullOrEmpty(id))
                    {
                        throw new XmlException(ConsoleInfoErrorStrings.IDNotFound);
                    }

                    consoleFileElement.PSSnapIns.Add(id);

                    s_mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", id, path);
                }
            }

            return consoleFileElement;
        }