示例#1
0
        private static string GetObjectName(object x, MshExpressionFactory expressionFactory)
        {
            if ((x is PSObject) && ((LanguagePrimitives.IsBoolOrSwitchParameterType(((PSObject)x).BaseObject.GetType()) || LanguagePrimitives.IsNumeric(Type.GetTypeCode(((PSObject)x).BaseObject.GetType()))) || LanguagePrimitives.IsNull(x)))
            {
                return(x.ToString());
            }
            if (x == null)
            {
                return("$null");
            }
            MethodInfo info = x.GetType().GetMethod("ToString", Type.EmptyTypes, null);

            if (info.DeclaringType.Equals(info.ReflectedType))
            {
                return(AsPSObject(x).ToString());
            }
            MshExpressionResult displayName = GetDisplayName(AsPSObject(x), expressionFactory);

            if ((displayName != null) && (displayName.Exception == null))
            {
                return(AsPSObject(displayName.Result).ToString());
            }
            string str = AsPSObject(x).ToString();

            if (str == string.Empty)
            {
                object obj2 = PSObject.Base(x);
                if (obj2 != null)
                {
                    str = obj2.ToString();
                }
            }
            return(str);
        }
示例#2
0
        internal static MshExpression GetDisplayNameExpression(
            PSObject target,
            MshExpressionFactory expressionFactory)
        {
            MshExpression defaultNameExpression = PSObjectHelper.GetDefaultNameExpression(target);

            if (defaultNameExpression != null)
            {
                return(defaultNameExpression);
            }
            string[] strArray = new string[6]
            {
                "name",
                "id",
                "key",
                "*key",
                "*name",
                "*id"
            };
            foreach (string s in strArray)
            {
                List <MshExpression> mshExpressionList = new MshExpression(s).ResolveNames(target);
                while (mshExpressionList.Count > 0 && (mshExpressionList[0].ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || mshExpressionList[0].ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || mshExpressionList[0].ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase)))
                {
                    mshExpressionList.RemoveAt(0);
                }
                if (mshExpressionList.Count != 0)
                {
                    return(mshExpressionList[0]);
                }
            }
            return((MshExpression)null);
        }
示例#3
0
        internal static EnumerableExpansion GetEnumerableExpansionFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (EnumerableExpansionDirective expansionDirective in db.defaultSettingsSection.enumerableExpansionDirectiveList)
            {
                if (match.PerfectMatch(new TypeMatchItem(expansionDirective, expansionDirective.appliesTo)))
                {
                    return(expansionDirective.enumerableExpansion);
                }
            }
            if (match.BestMatch != null)
            {
                return(((EnumerableExpansionDirective)(match.BestMatch)).enumerableExpansion);
            }
            else
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    EnumerableExpansion result = GetEnumerableExpansionFromType(expressionFactory, db, typesWithoutPrefix);
                    return(result);
                }

                // return a default value if no matches were found
                return(EnumerableExpansion.EnumOnly);
            }
        }
示例#4
0
        internal bool LoadFromFile(Collection <PSSnapInTypeAndFormatErrors> files, MshExpressionFactory expressionFactory, bool acceptLoadingErrors, AuthorizationManager authorizationManager, PSHost host, bool preValidated, out List <XmlLoaderLoggerEntry> logEntries)
        {
            bool flag;

            try
            {
                TypeInfoDataBase base2 = null;
                lock (this.updateDatabaseLock)
                {
                    base2 = LoadFromFileHelper(files, expressionFactory, authorizationManager, host, preValidated, out logEntries, out flag);
                }
                lock (this.databaseLock)
                {
                    if (acceptLoadingErrors || flag)
                    {
                        this.dataBase = base2;
                    }
                    return(flag);
                }
            }
            finally
            {
                lock (this.databaseLock)
                {
                    if (this.dataBase == null)
                    {
                        TypeInfoDataBase db = new TypeInfoDataBase();
                        AddPreLoadInstrinsics(db);
                        AddPostLoadInstrinsics(db);
                        this.dataBase = db;
                    }
                }
            }
            return(flag);
        }
        internal TypeInfoDataBaseManager(
            IEnumerable <string> formatFiles,
            bool isShared,
            AuthorizationManager authorizationManager,
            PSHost host)
        {
            this.formatFileList = new List <string>();
            Collection <PSSnapInTypeAndFormatErrors> files = new Collection <PSSnapInTypeAndFormatErrors>();
            Collection <string> loadErrors = new Collection <string>();

            foreach (string formatFile in formatFiles)
            {
                if (string.IsNullOrEmpty(formatFile) || !Path.IsPathRooted(formatFile))
                {
                    throw TypeInfoDataBaseManager.tracer.NewArgumentException(nameof(formatFiles), "FormatAndOut.XmlLoading", "FormatFileNotRooted", (object)formatFile);
                }
                files.Add(new PSSnapInTypeAndFormatErrors(string.Empty, formatFile)
                {
                    Errors = loadErrors
                });
                this.formatFileList.Add(formatFile);
            }
            MshExpressionFactory        expressionFactory = new MshExpressionFactory(new CreateScriptBlockFromString(this.CreateScriptBlock));
            List <XmlLoaderLoggerEntry> logEntries        = (List <XmlLoaderLoggerEntry>)null;

            this.LoadFromFile(files, expressionFactory, true, authorizationManager, host, out logEntries);
            this.isShared = isShared;
            if (loadErrors.Count > 0)
            {
                throw new FormatTableLoadException(loadErrors);
            }
        }
示例#6
0
 internal static string FormatField(FieldFormattingDirective directive, object val, int enumerationLimit, StringFormatError formatErrorObject, MshExpressionFactory expressionFactory)
 {
     PSObject so = AsPSObject(val);
     if ((directive != null) && !string.IsNullOrEmpty(directive.formatString))
     {
         try
         {
             if (directive.formatString.Contains("{0") || directive.formatString.Contains("}"))
             {
                 return string.Format(CultureInfo.CurrentCulture, directive.formatString, new object[] { so });
             }
             return so.ToString(directive.formatString, null);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
             if (formatErrorObject != null)
             {
                 formatErrorObject.sourceObject = so;
                 formatErrorObject.exception = exception;
                 formatErrorObject.formatString = directive.formatString;
                 return "";
             }
         }
     }
     return SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject);
 }
        internal static List<MshResolvedExpressionParameterAssociation> SetupActiveProperties(List<MshParameter> rawMshParameterList,
                                                   PSObject target, MshExpressionFactory expressionFactory)
        {
            // check if we received properties from the command line
            if (rawMshParameterList != null && rawMshParameterList.Count > 0)
            {
                return AssociationManager.ExpandParameters(rawMshParameterList, target);
            }

            // we did not get any properties:
            //try to get properties from the default property set of the object
            List<MshResolvedExpressionParameterAssociation> activeAssociationList = AssociationManager.ExpandDefaultPropertySet(target, expressionFactory);

            if (activeAssociationList.Count > 0)
            {
                // we got a valid set of properties from the default property set..add computername for
                // remoteobjects (if available)
                if (PSObjectHelper.ShouldShowComputerNameProperty(target))
                {
                    activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null,
                        new MshExpression(RemotingConstants.ComputerNameNoteProperty)));
                }

                return activeAssociationList;
            }

            // we failed to get anything from the default property set
            // just get all the properties
            activeAssociationList = AssociationManager.ExpandAll(target);
            // Remove PSComputerName and PSShowComputerName from the display as needed.
            AssociationManager.HandleComputerNameProperties(target, activeAssociationList);

            return activeAssociationList;
        }
示例#8
0
        internal static FormatShape GetShapeFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames)
        {
            ShapeSelectionDirectives shapeDirectives = db.defaultSettingsSection.shapeSelectionDirectives;

            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (FormatShapeSelectionOnType shapeSelOnType in shapeDirectives.formatShapeSelectionOnTypeList)
            {
                if (match.PerfectMatch(new TypeMatchItem(shapeSelOnType, shapeSelOnType.appliesTo)))
                {
                    return(shapeSelOnType.formatShape);
                }
            }
            if (match.BestMatch != null)
            {
                return(((FormatShapeSelectionOnType)(match.BestMatch)).formatShape);
            }
            else
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    FormatShape result = GetShapeFromType(expressionFactory, db, typesWithoutPrefix);
                    return(result);
                }

                // return a default value if no matches were found
                return(FormatShape.Undefined);
            }
        }
示例#9
0
        internal static List<MshResolvedExpressionParameterAssociation> SetupActiveProperties(List<MshParameter> rawMshParameterList,
                                                   PSObject target, MshExpressionFactory expressionFactory)
        {
            // check if we received properties from the command line
            if (rawMshParameterList != null && rawMshParameterList.Count > 0)
            {
                return AssociationManager.ExpandParameters(rawMshParameterList, target);
            }

            // we did not get any properties:
            //try to get properties from the default property set of the object
            List<MshResolvedExpressionParameterAssociation> activeAssociationList = AssociationManager.ExpandDefaultPropertySet(target, expressionFactory);

            if (activeAssociationList.Count > 0)
            {
                // we got a valid set of properties from the default property set..add computername for
                // remoteobjects (if available)
                if (PSObjectHelper.ShouldShowComputerNameProperty(target))
                {
                    activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null,
                        new MshExpression(RemotingConstants.ComputerNameNoteProperty)));
                }

                return activeAssociationList;
            }

            // we failed to get anything from the default property set
            // just get all the properties
            activeAssociationList = AssociationManager.ExpandAll(target);
            // Remove PSComputerName and PSShowComputerName from the display as needed.
            AssociationManager.HandleComputerNameProperties(target, activeAssociationList);

            return activeAssociationList;
        }
示例#10
0
        private static ViewGenerator SelectViewGeneratorFromViewDefinition(
            TerminatingErrorContext errorContext,
            MshExpressionFactory expressionFactory,
            TypeInfoDataBase db,
            ViewDefinition view,
            FormattingCommandLineParameters parameters)
        {
            ViewGenerator viewGenerator = null;

            if (view.mainControl is TableControlBody)
            {
                viewGenerator = new TableViewGenerator();
            }
            else if (view.mainControl is ListControlBody)
            {
                viewGenerator = new ListViewGenerator();
            }
            else if (view.mainControl is WideControlBody)
            {
                viewGenerator = new WideViewGenerator();
            }
            else if (view.mainControl is ComplexControlBody)
            {
                viewGenerator = new ComplexViewGenerator();
            }

            Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");
            viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters);
            return(viewGenerator);
        }
示例#11
0
 internal static ViewDefinition GetViewByShapeAndType(MshExpressionFactory expressionFactory, TypeInfoDataBase db,
                                                      FormatShape shape, Collection <string> typeNames, string viewName)
 {
     if (shape == FormatShape.Undefined)
     {
         return(GetDefaultView(expressionFactory, db, typeNames));
     }
     // map the FormatShape to a type derived from ViewDefinition
     System.Type t = null;
     if (shape == FormatShape.Table)
     {
         t = typeof(TableControlBody);
     }
     else if (shape == FormatShape.List)
     {
         t = typeof(ListControlBody);
     }
     else if (shape == FormatShape.Wide)
     {
         t = typeof(WideControlBody);
     }
     else if (shape == FormatShape.Complex)
     {
         t = typeof(ComplexControlBody);
     }
     else
     {
         Diagnostics.Assert(false, "unknonw shape: this should never happen unless a new shape is added");
         return(null);
     }
     return(GetView(expressionFactory, db, t, typeNames, viewName));
 }
示例#12
0
 internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames, bool useInheritance)
 {
     _expressionFactory = expressionFactory;
     _db = db;
     _typeNameHierarchy = typeNames;
     _useInheritance    = useInheritance;
 }
示例#13
0
        internal static ViewDefinition GetOutOfBandView(MshExpressionFactory expressionFactory,
                                                        TypeInfoDataBase db, Collection <string> typeNames)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
            {
                if (!IsOutOfBandView(vd))
                {
                    continue;
                }
                if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
                {
                    return(vd);
                }
            }

            // this is the best match we had
            ViewDefinition result = match.BestMatch as ViewDefinition;

            // we were unable to find a best match so far..try
            // to get rid of Deserialization prefix and see if a
            // match can be found.
            if (null == result)
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    result = GetOutOfBandView(expressionFactory, db, typesWithoutPrefix);
                }
            }

            return(result);
        }
 internal override void BeginProcessing()
 {
     base.BeginProcessing();
     this.enumerationLimit         = FormatEnumerationLimit();
     this.expressionFactory        = new MshExpressionFactory();
     this.formatObjectDeserializer = new FormatObjectDeserializer(base.TerminatingErrorContext);
 }
示例#15
0
 internal TypeInfoDataBaseManager(IEnumerable<string> formatFiles, bool isShared, AuthorizationManager authorizationManager, PSHost host)
 {
     this.databaseLock = new object();
     this.updateDatabaseLock = new object();
     this.formatFileList = new List<string>();
     Collection<PSSnapInTypeAndFormatErrors> files = new Collection<PSSnapInTypeAndFormatErrors>();
     Collection<string> loadErrors = new Collection<string>();
     foreach (string str in formatFiles)
     {
         if (string.IsNullOrEmpty(str) || !Path.IsPathRooted(str))
         {
             throw PSTraceSource.NewArgumentException("formatFiles", "FormatAndOutXmlLoadingStrings", "FormatFileNotRooted", new object[] { str });
         }
         PSSnapInTypeAndFormatErrors item = new PSSnapInTypeAndFormatErrors(string.Empty, str) {
             Errors = loadErrors
         };
         files.Add(item);
         this.formatFileList.Add(str);
     }
     MshExpressionFactory expressionFactory = new MshExpressionFactory();
     List<XmlLoaderLoggerEntry> logEntries = null;
     this.LoadFromFile(files, expressionFactory, true, authorizationManager, host, false, out logEntries);
     this.isShared = isShared;
     if (loadErrors.Count > 0)
     {
         throw new FormatTableLoadException(loadErrors);
     }
 }
示例#16
0
        private static void LoadFormatDataHelper(
            ExtendedTypeDefinition formatData,
            MshExpressionFactory expressionFactory, List <XmlLoaderLoggerEntry> logEntries, ref bool success,
            PSSnapInTypeAndFormatErrors file, TypeInfoDataBase db,
            bool isBuiltInFormatData,
            bool isForHelp)
        {
            using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader())
            {
                if (!loader.LoadFormattingData(formatData, db, expressionFactory, isBuiltInFormatData, isForHelp))
                {
                    success = false;
                }

                foreach (XmlLoaderLoggerEntry entry in loader.LogEntries)
                {
                    // filter in only errors from the current file...
                    if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error)
                    {
                        string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError,
                                                                    file.PSSnapinName, entry.message);
                        file.Errors.Add(mshsnapinMessage);
                    }
                }
                // now aggregate the entries...
                logEntries.AddRange(loader.LogEntries);
            }
        }
示例#17
0
 internal override void BeginProcessing()
 {
     base.BeginProcessing();
     this.enumerationLimit = FormatEnumerationLimit();
     this.expressionFactory = new MshExpressionFactory();
     this.formatObjectDeserializer = new FormatObjectDeserializer(base.TerminatingErrorContext);
 }
示例#18
0
        internal static ViewDefinition GetViewByShapeAndType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, FormatShape shape, Collection <string> typeNames, string viewName)
        {
            if (shape == FormatShape.Undefined)
            {
                return(GetDefaultView(expressionFactory, db, typeNames));
            }
            Type mainControlType = null;

            if (shape == FormatShape.Table)
            {
                mainControlType = typeof(TableControlBody);
            }
            else if (shape == FormatShape.List)
            {
                mainControlType = typeof(ListControlBody);
            }
            else if (shape == FormatShape.Wide)
            {
                mainControlType = typeof(WideControlBody);
            }
            else if (shape == FormatShape.Complex)
            {
                mainControlType = typeof(ComplexControlBody);
            }
            else
            {
                return(null);
            }
            return(GetView(expressionFactory, db, mainControlType, typeNames, viewName));
        }
示例#19
0
        internal TypeInfoDataBaseManager(IEnumerable <string> formatFiles, bool isShared, AuthorizationManager authorizationManager, PSHost host)
        {
            this.databaseLock       = new object();
            this.updateDatabaseLock = new object();
            this.formatFileList     = new List <string>();
            Collection <PSSnapInTypeAndFormatErrors> files = new Collection <PSSnapInTypeAndFormatErrors>();
            Collection <string> loadErrors = new Collection <string>();

            foreach (string str in formatFiles)
            {
                if (string.IsNullOrEmpty(str) || !Path.IsPathRooted(str))
                {
                    throw PSTraceSource.NewArgumentException("formatFiles", "FormatAndOutXmlLoadingStrings", "FormatFileNotRooted", new object[] { str });
                }
                PSSnapInTypeAndFormatErrors item = new PSSnapInTypeAndFormatErrors(string.Empty, str)
                {
                    Errors = loadErrors
                };
                files.Add(item);
                this.formatFileList.Add(str);
            }
            MshExpressionFactory        expressionFactory = new MshExpressionFactory();
            List <XmlLoaderLoggerEntry> logEntries        = null;

            this.LoadFromFile(files, expressionFactory, true, authorizationManager, host, false, out logEntries);
            this.isShared = isShared;
            if (loadErrors.Count > 0)
            {
                throw new FormatTableLoadException(loadErrors);
            }
        }
示例#20
0
 internal override void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters)
 {
     base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters);
     if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
     {
         _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl;
     }
 }
示例#21
0
        private static string GetSmartToStringDisplayName(
            object x,
            MshExpressionFactory expressionFactory)
        {
            MshExpressionResult displayName = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory);

            return(displayName != null && displayName.Exception == null?PSObjectHelper.AsPSObject(displayName.Result).ToString() : PSObjectHelper.AsPSObject(x).ToString());
        }
示例#22
0
 internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters formatParameters)
 {
     this.errorContext      = terminatingErrorContext;
     this.expressionFactory = mshExpressionFactory;
     this.parameters        = formatParameters;
     this.dataBaseInfo.db   = db;
     this.InitializeHelper();
 }
示例#23
0
 internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames, bool useInheritance)
 {
     this._failedResultsList = new List<MshExpressionResult>();
     this._bestMatchIndex = -1;
     this._expressionFactory = expressionFactory;
     this._db = db;
     this._typeNameHierarchy = typeNames;
     this._useInheritance = useInheritance;
 }
示例#24
0
        private static ViewDefinition GetDefaultView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
            {
                if (vd == null)
                {
                    continue;
                }

                if (IsOutOfBandView(vd))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH OutOfBand {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                if (vd.appliesTo == null)
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}  No applicable types",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                try
                {
                    TypeMatch.SetTracer(ActiveTracer);
                    if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
                    {
                        TraceHelper(vd, true);
                        return(vd);
                    }
                }
                finally
                {
                    TypeMatch.ResetTracer();
                }
                TraceHelper(vd, false);
            }
            // this is the best match we had
            ViewDefinition result = GetBestMatch(match);

            // we were unable to find a best match so far..try
            // to get rid of Deserialization prefix and see if a
            // match can be found.
            if (null == result)
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    result = GetDefaultView(expressionFactory, db, typesWithoutPrefix);
                }
            }

            return(result);
        }
示例#25
0
 internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames, bool useInheritance)
 {
     this._failedResultsList = new List <MshExpressionResult>();
     this._bestMatchIndex    = -1;
     this._expressionFactory = expressionFactory;
     this._db = db;
     this._typeNameHierarchy = typeNames;
     this._useInheritance    = useInheritance;
 }
示例#26
0
 internal static List<MshResolvedExpressionParameterAssociation> ExpandDefaultPropertySet(PSObject target, MshExpressionFactory expressionFactory)
 {
     List<MshResolvedExpressionParameterAssociation> list = new List<MshResolvedExpressionParameterAssociation>();
     foreach (MshExpression expression in PSObjectHelper.GetDefaultPropertySet(target))
     {
         list.Add(new MshResolvedExpressionParameterAssociation(null, expression));
     }
     return list;
 }
示例#27
0
        /// <summary>
        /// Update a shared formatting database with formatData of 'ExtendedTypeDefinition' type.
        /// This method should only be called from the FormatTable, where are shared formatting
        /// database is created.
        /// </summary>
        /// <param name="formatData">
        /// The format data to update the database
        /// </param>
        /// <param name="shouldPrepend">
        /// Specify the order in which the format data will be loaded
        /// </param>
        internal void AddFormatData(IEnumerable <ExtendedTypeDefinition> formatData, bool shouldPrepend)
        {
            Diagnostics.Assert(isShared, "this method should only be called from FormatTable to update a shared database");

            Collection <PSSnapInTypeAndFormatErrors> filesToLoad = new Collection <PSSnapInTypeAndFormatErrors>();
            ConcurrentBag <string> errors = new ConcurrentBag <string>();

            if (shouldPrepend)
            {
                foreach (ExtendedTypeDefinition typeDefinition in formatData)
                {
                    PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition);
                    entryToLoad.Errors = errors;
                    filesToLoad.Add(entryToLoad);
                }
                // check if the passed in formatData is empty
                if (filesToLoad.Count == 0)
                {
                    return;
                }
            }
            lock (_formatFileList)
            {
                foreach (string formatFile in _formatFileList)
                {
                    PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile);
                    fileToLoad.Errors = errors;
                    filesToLoad.Add(fileToLoad);
                }
            }
            if (!shouldPrepend)
            {
                foreach (ExtendedTypeDefinition typeDefinition in formatData)
                {
                    PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition);
                    entryToLoad.Errors = errors;
                    filesToLoad.Add(entryToLoad);
                }
                // check if the passed in formatData is empty
                if (filesToLoad.Count == _formatFileList.Count)
                {
                    return;
                }
            }

            MshExpressionFactory        expressionFactory = new MshExpressionFactory();
            List <XmlLoaderLoggerEntry> logEntries        = null;

            // load the formatting data
            LoadFromFile(filesToLoad, expressionFactory, false, null, null, false, out logEntries);

            // check to see if there are any errors loading the format files
            if (errors.Count > 0)
            {
                throw new FormatTableLoadException(errors);
            }
        }
示例#28
0
        private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so,
                                                                       TerminatingErrorContext errorContext,
                                                                       MshExpressionFactory expressionFactory,
                                                                       TypeInfoDataBase db,
                                                                       FormattingCommandLineParameters parameters)
        {
            // use some heuristics to determine the shape if none is specified
            if (shape == FormatShape.Undefined && parameters == null)
            {
                // check first if we have a known shape for a type
                var typeNames = so.InternalTypeNames;
                shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames);

                if (shape == FormatShape.Undefined)
                {
                    // check if we can have a table:
                    // we want to get the # of properties we are going to display
                    List <MshExpression> expressionList = PSObjectHelper.GetDefaultPropertySet(so);
                    if (expressionList.Count == 0)
                    {
                        // we failed to get anything from a property set
                        // we just get the first properties out of the first object
                        foreach (MshResolvedExpressionParameterAssociation mrepa in AssociationManager.ExpandAll(so))
                        {
                            expressionList.Add(mrepa.ResolvedExpression);
                        }
                    }

                    // decide what shape we want for the given number of properties
                    shape = DisplayDataQuery.GetShapeFromPropertyCount(db, expressionList.Count);
                }
            }

            ViewGenerator viewGenerator = null;

            if (shape == FormatShape.Table)
            {
                viewGenerator = new TableViewGenerator();
            }
            else if (shape == FormatShape.List)
            {
                viewGenerator = new ListViewGenerator();
            }
            else if (shape == FormatShape.Wide)
            {
                viewGenerator = new WideViewGenerator();
            }
            else if (shape == FormatShape.Complex)
            {
                viewGenerator = new ComplexViewGenerator();
            }
            Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");

            viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters);
            return(viewGenerator);
        }
示例#29
0
 internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters)
 {
     this.errorContext                 = terminatingErrorContext;
     this.expressionFactory            = mshExpressionFactory;
     this.parameters                   = formatParameters;
     this.dataBaseInfo.db              = db;
     this.dataBaseInfo.view            = view;
     this.dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes(db, view.appliesTo);
     this.InitializeHelper();
 }
 internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List <ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext)
 {
     this.db                    = dataBase;
     this.loadingInfo           = loadingInfo;
     this.expressionFactory     = expressionFactory;
     this.controlDefinitionList = controlDefinitionList;
     this.errorManager          = resultErrorManager;
     this.enumerationLimit      = enumerationLimit;
     this.errorContext          = errorContext;
 }
示例#31
0
 internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
 {
     base.Initialize(errorContext, expressionFactory, so, db, parameters);
     if ((base.dataBaseInfo != null) && (base.dataBaseInfo.view != null))
     {
         this.listBody = (ListControlBody)base.dataBaseInfo.view.mainControl;
     }
     base.inputParameters = parameters;
     this.SetUpActiveProperties(so);
 }
示例#32
0
 internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List<ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext)
 {
     this.db = dataBase;
     this.loadingInfo = loadingInfo;
     this.expressionFactory = expressionFactory;
     this.controlDefinitionList = controlDefinitionList;
     this.errorManager = resultErrorManager;
     this.enumerationLimit = enumerationLimit;
     this.errorContext = errorContext;
 }
示例#33
0
        private static string GetSmartToStringDisplayName(object x, MshExpressionFactory expressionFactory)
        {
            MshExpressionResult displayName = GetDisplayName(AsPSObject(x), expressionFactory);

            if ((displayName != null) && (displayName.Exception == null))
            {
                return(AsPSObject(displayName.Result).ToString());
            }
            return(AsPSObject(x).ToString());
        }
示例#34
0
 internal TypeMatch(
     MshExpressionFactory expressionFactory,
     TypeInfoDataBase db,
     Collection <string> typeNames)
 {
     this._expressionFactory = expressionFactory;
     this._db = db;
     this._typeNameHierarchy = typeNames;
     this._useInheritance    = true;
 }
示例#35
0
        internal void AddFormatData(IEnumerable <ExtendedTypeDefinition> formatData, bool shouldPrepend)
        {
            Collection <PSSnapInTypeAndFormatErrors> files = new Collection <PSSnapInTypeAndFormatErrors>();
            Collection <string> loadErrors = new Collection <string>();

            if (shouldPrepend)
            {
                foreach (ExtendedTypeDefinition definition in formatData)
                {
                    PSSnapInTypeAndFormatErrors item = new PSSnapInTypeAndFormatErrors(string.Empty, definition)
                    {
                        Errors = loadErrors
                    };
                    files.Add(item);
                }
                if (files.Count == 0)
                {
                    return;
                }
            }
            lock (this.formatFileList)
            {
                foreach (string str in this.formatFileList)
                {
                    PSSnapInTypeAndFormatErrors errors2 = new PSSnapInTypeAndFormatErrors(string.Empty, str)
                    {
                        Errors = loadErrors
                    };
                    files.Add(errors2);
                }
            }
            if (!shouldPrepend)
            {
                foreach (ExtendedTypeDefinition definition2 in formatData)
                {
                    PSSnapInTypeAndFormatErrors errors3 = new PSSnapInTypeAndFormatErrors(string.Empty, definition2)
                    {
                        Errors = loadErrors
                    };
                    files.Add(errors3);
                }
                if (files.Count == this.formatFileList.Count)
                {
                    return;
                }
            }
            MshExpressionFactory        expressionFactory = new MshExpressionFactory();
            List <XmlLoaderLoggerEntry> logEntries        = null;

            this.LoadFromFile(files, expressionFactory, false, null, null, false, out logEntries);
            if (loadErrors.Count > 0)
            {
                throw new FormatTableLoadException(loadErrors);
            }
        }
示例#36
0
        internal override void BeginProcessing()
        {
            base.BeginProcessing();

            // Get the Format Enumeration Limit.
            _enumerationLimit = InnerFormatShapeCommand.FormatEnumerationLimit();

            _expressionFactory = new MshExpressionFactory();

            _formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext);
        }
        internal override void BeginProcessing()
        {
            base.BeginProcessing();

            // Get the Format Enumeration Limit.
            _enumerationLimit = InnerFormatShapeCommand.FormatEnumerationLimit();

            _expressionFactory = new MshExpressionFactory();

            _formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext);
        }
示例#38
0
        internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                                    PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
        {
            base.Initialize(errorContext, expressionFactory, so, db, parameters);
            if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
            {
                _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl;
            }

            this.inputParameters = parameters;
            SetUpActiveProperties(so);
        }
示例#39
0
        internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                                          PSObject so, TypeInfoDataBase db,
                                          FormattingCommandLineParameters parameters)
        {
            base.Initialize(errorContext, expressionFactory, so, db, parameters);

            if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
            {
                _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl;
            }

            List <MshParameter> rawMshParameterList = null;

            if (parameters != null)
            {
                rawMshParameterList = parameters.mshParameterList;
            }

            // check if we received properties from the command line
            if (rawMshParameterList != null && rawMshParameterList.Count > 0)
            {
                this.activeAssociationList = AssociationManager.ExpandTableParameters(rawMshParameterList, so);
                return;
            }

            // we did not get any properties:
            //try to get properties from the default property set of the object
            this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory);
            if (this.activeAssociationList.Count > 0)
            {
                // we got a valid set of properties from the default property set..add computername for
                // remoteobjects (if available)
                if (PSObjectHelper.ShouldShowComputerNameProperty(so))
                {
                    activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null,
                                                                                            new MshExpression(RemotingConstants.ComputerNameNoteProperty)));
                }
                return;
            }

            // we failed to get anything from the default property set
            this.activeAssociationList = AssociationManager.ExpandAll(so);
            if (this.activeAssociationList.Count > 0)
            {
                // Remove PSComputerName and PSShowComputerName from the display as needed.
                AssociationManager.HandleComputerNameProperties(so, activeAssociationList);
                FilterActiveAssociationList();
                return;
            }

            // we were unable to retrieve any properties, so we leave an empty list
            this.activeAssociationList = new List <MshResolvedExpressionParameterAssociation>();
        }
示例#40
0
        private static ViewDefinition GetView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Type mainControlType, Collection <string> typeNames, string viewName)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (ViewDefinition definition in db.viewDefinitionsSection.viewDefinitionList)
            {
                if ((definition == null) || (mainControlType != definition.mainControl.GetType()))
                {
                    ActiveTracer.WriteLine("NOT MATCH {0}  NAME: {1}", new object[] { ControlBase.GetControlShapeName(definition.mainControl), (definition != null) ? definition.name : string.Empty });
                }
                else if (IsOutOfBandView(definition))
                {
                    ActiveTracer.WriteLine("NOT MATCH OutOfBand {0}  NAME: {1}", new object[] { ControlBase.GetControlShapeName(definition.mainControl), definition.name });
                }
                else if (definition.appliesTo == null)
                {
                    ActiveTracer.WriteLine("NOT MATCH {0}  NAME: {1}  No applicable types", new object[] { ControlBase.GetControlShapeName(definition.mainControl), definition.name });
                }
                else if ((viewName != null) && !string.Equals(definition.name, viewName, StringComparison.OrdinalIgnoreCase))
                {
                    ActiveTracer.WriteLine("NOT MATCH {0}  NAME: {1}", new object[] { ControlBase.GetControlShapeName(definition.mainControl), definition.name });
                }
                else
                {
                    try
                    {
                        TypeMatch.SetTracer(ActiveTracer);
                        if (match.PerfectMatch(new TypeMatchItem(definition, definition.appliesTo)))
                        {
                            TraceHelper(definition, true);
                            return(definition);
                        }
                    }
                    finally
                    {
                        TypeMatch.ResetTracer();
                    }
                    TraceHelper(definition, false);
                }
            }
            ViewDefinition bestMatch = GetBestMatch(match);

            if (bestMatch == null)
            {
                Collection <string> collection = Deserializer.MaskDeserializationPrefix(typeNames);
                if (collection != null)
                {
                    bestMatch = GetView(expressionFactory, db, mainControlType, collection, viewName);
                }
            }
            return(bestMatch);
        }
示例#41
0
 protected override void BeginProcessing()
 {
     this.expressionFactory = new MshExpressionFactory();
     if (this.title != null)
     {
         this.windowProxy = new OutWindowProxy(this.title, this.outputMode, this);
     }
     else
     {
         this.windowProxy = new OutWindowProxy(base.MyInvocation.Line, this.outputMode, this);
     }
     this.typeInfoDataBase = base.Context.FormatDBManager.GetTypeInfoDataBase();
 }
示例#42
0
        internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
                                            MshExpressionFactory mshExpressionFactory,
                                            PSObject so,
                                            TypeInfoDataBase db,
                                            FormattingCommandLineParameters formatParameters)
        {
            errorContext = terminatingErrorContext;
            expressionFactory = mshExpressionFactory;
            parameters = formatParameters;
            dataBaseInfo.db = db;

            InitializeHelper();
        }
示例#43
0
        internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                                        PSObject so, TypeInfoDataBase db,
            FormattingCommandLineParameters parameters)
        {
            base.Initialize(errorContext, expressionFactory, so, db, parameters);

            if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
            {
                _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl;
            }

            List<MshParameter> rawMshParameterList = null;

            if (parameters != null)
                rawMshParameterList = parameters.mshParameterList;

            // check if we received properties from the command line
            if (rawMshParameterList != null && rawMshParameterList.Count > 0)
            {
                this.activeAssociationList = AssociationManager.ExpandTableParameters(rawMshParameterList, so);
                return;
            }

            // we did not get any properties:
            //try to get properties from the default property set of the object
            this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory);
            if (this.activeAssociationList.Count > 0)
            {
                // we got a valid set of properties from the default property set..add computername for
                // remoteobjects (if available)
                if (PSObjectHelper.ShouldShowComputerNameProperty(so))
                {
                    activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null,
                        new MshExpression(RemotingConstants.ComputerNameNoteProperty)));
                }
                return;
            }

            // we failed to get anything from the default property set
            this.activeAssociationList = AssociationManager.ExpandAll(so);
            if (this.activeAssociationList.Count > 0)
            {
                // Remove PSComputerName and PSShowComputerName from the display as needed.
                AssociationManager.HandleComputerNameProperties(so, activeAssociationList);
                FilterActiveAssociationList();
                return;
            }

            // we were unable to retrieve any properties, so we leave an empty list
            this.activeAssociationList = new List<MshResolvedExpressionParameterAssociation>();
        }
示例#44
0
        internal void Initialize(MshExpressionFactory expressionFactory,
                                 TypeInfoDataBase db)
        {
            _expressionFactory = expressionFactory;
            _typeInfoDatabase = db;

            // Initialize Format Error Manager.
            FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy();

            formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages;
            formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput;

            _errorManager = new FormatErrorManager(formatErrorPolicy);
        }
示例#45
0
 private static ViewDefinition GetDefaultView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
 {
     TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
     foreach (ViewDefinition definition in db.viewDefinitionsSection.viewDefinitionList)
     {
         if (definition != null)
         {
             if (IsOutOfBandView(definition))
             {
                 ActiveTracer.WriteLine("NOT MATCH OutOfBand {0}  NAME: {1}", new object[] { ControlBase.GetControlShapeName(definition.mainControl), definition.name });
             }
             else if (definition.appliesTo == null)
             {
                 ActiveTracer.WriteLine("NOT MATCH {0}  NAME: {1}  No applicable types", new object[] { ControlBase.GetControlShapeName(definition.mainControl), definition.name });
             }
             else
             {
                 try
                 {
                     TypeMatch.SetTracer(ActiveTracer);
                     if (match.PerfectMatch(new TypeMatchItem(definition, definition.appliesTo)))
                     {
                         TraceHelper(definition, true);
                         return definition;
                     }
                 }
                 finally
                 {
                     TypeMatch.ResetTracer();
                 }
                 TraceHelper(definition, false);
             }
         }
     }
     ViewDefinition bestMatch = GetBestMatch(match);
     if (bestMatch == null)
     {
         Collection<string> collection = Deserializer.MaskDeserializationPrefix(typeNames);
         if (collection != null)
         {
             bestMatch = GetDefaultView(expressionFactory, db, collection);
         }
     }
     return bestMatch;
 }
示例#46
0
        internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
                                        MshExpressionFactory mshExpressionFactory,
                                        TypeInfoDataBase db,
                                        ViewDefinition view,
                                        FormattingCommandLineParameters formatParameters)
        {
            Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null");
            Diagnostics.Assert(db != null, "db cannot be null");
            Diagnostics.Assert(view != null, "view cannot be null");

            errorContext = terminatingErrorContext;
            expressionFactory = mshExpressionFactory;
            parameters = formatParameters;

            dataBaseInfo.db = db;
            dataBaseInfo.view = view;
            dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes(db, view.appliesTo);

            InitializeHelper();
        }
示例#47
0
 internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors)
 {
     ViewGenerator generator;
     errors = null;
     ConsolidatedString internalTypeNames = so.InternalTypeNames;
     ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, internalTypeNames);
     if (view != null)
     {
         if (view.mainControl is ComplexControlBody)
         {
             generator = new ComplexViewGenerator();
         }
         else
         {
             generator = new ListViewGenerator();
         }
         generator.Initialize(errorContext, expressionFactory, db, view, null);
     }
     else
     {
         if (DefaultScalarTypes.IsTypeInList(internalTypeNames) || IsPropertyLessObject(so))
         {
             return GenerateOutOfBandObjectAsToString(so);
         }
         if (!useToStringFallback)
         {
             return null;
         }
         if (new MshExpression("*").ResolveNames(so).Count <= 0)
         {
             return null;
         }
         generator = new ListViewGenerator();
         generator.Initialize(errorContext, expressionFactory, so, db, null);
     }
     FormatEntryData data = generator.GeneratePayload(so, enumerationLimit);
     data.outOfBand = true;
     data.SetStreamTypeFromPSObject(so);
     errors = generator.ErrorManager.DrainFailedResultList();
     return data;
 }
示例#48
0
        private static ViewDefinition GetView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection<string> typeNames, string viewName)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);
            foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
            {
                if (vd == null || mainControlType != vd.mainControl.GetType())
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), (null != vd ? vd.name : string.Empty));
                    continue;
                }
                if (IsOutOfBandView(vd))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH OutOfBand {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                if (vd.appliesTo == null)
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}  No applicable types",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                // first make sure we match on name:
                // if not, we do not try a match at all
                if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }

                // check if we have a perfect match
                // if so, we are done
                try
                {
                    TypeMatch.SetTracer(ActiveTracer);
                    if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
                    {
                        TraceHelper(vd, true);
                        return vd;
                    }
                }
                finally
                {
                    TypeMatch.ResetTracer();
                }
                TraceHelper(vd, false);
            }

            // this is the best match we had
            ViewDefinition result = GetBestMatch(match);

            // we were unable to find a best match so far..try
            // to get rid of Deserialization prefix and see if a
            // match can be found.
            if (null == result)
            {
                Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName);
                }
            }

            return result;
        }
示例#49
0
        internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                    TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors)
        {
            errors = null;

            var typeNames = so.InternalTypeNames;
            ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames);

            ViewGenerator outOfBandViewGenerator;
            if (view != null)
            {
                // process an out of band view retrieved from the display database
                if (view.mainControl is ComplexControlBody)
                {
                    outOfBandViewGenerator = new ComplexViewGenerator();
                }
                else
                {
                    outOfBandViewGenerator = new ListViewGenerator();
                }
                outOfBandViewGenerator.Initialize(errorContext, expressionFactory, db, view, null);
            }
            else
            {
                if (DefaultScalarTypes.IsTypeInList(typeNames) ||
                    IsPropertyLessObject(so))
                {
                    // we force a ToString() on well known types
                    return GenerateOutOfBandObjectAsToString(so);
                }

                if (!useToStringFallback)
                {
                    return null;
                }

                // we must check we have enough properties for a list view
                if (new MshExpression("*").ResolveNames(so).Count <= 0)
                {
                    return null;
                }

                // we do not have a view, we default to list view
                // process an out of band view as a default
                outOfBandViewGenerator = new ListViewGenerator();
                outOfBandViewGenerator.Initialize(errorContext, expressionFactory, so, db, null);
            }

            FormatEntryData fed = outOfBandViewGenerator.GeneratePayload(so, enumerationLimit);
            fed.outOfBand = true;
            fed.SetStreamTypeFromPSObject(so);

            errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList();

            return fed;
        }
示例#50
0
        /// <summary>
        /// entry point for the loader algorithm
        /// </summary>
        /// <param name="info">information needed to load the file</param>
        /// <param name="db">database instance to load the file into</param>
        /// <param name="expressionFactory">expression factory to validate script blocks</param>
        /// <param name="authorizationManager">
        /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed)
        /// </param>
        /// <param name="host">
        /// Host passed to <paramref name="authorizationManager"/>.  Can be null if no interactive questions should be asked.
        /// </param>
        /// <param name="preValidated">
        /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be
        /// skipped at runtime.
        /// </param>
        /// <returns>true if successful</returns>
        internal bool LoadXmlFile(
            XmlFileLoadInfo info,
            TypeInfoDataBase db,
            MshExpressionFactory expressionFactory,
            AuthorizationManager authorizationManager,
            PSHost host,
            bool preValidated)
        {
            if (info == null)
                throw PSTraceSource.NewArgumentNullException("info");

            if (info.filePath == null)
                throw PSTraceSource.NewArgumentNullException("info.filePath");

            if (db == null)
                throw PSTraceSource.NewArgumentNullException("db");

            if (expressionFactory == null)
                throw PSTraceSource.NewArgumentNullException("expressionFactory");

            if (SecuritySupport.IsProductBinary(info.filePath))
            {
                this.SetLoadingInfoIsProductCode(true);
            }

            this.displayResourceManagerCache = db.displayResourceManagerCache;

            this.expressionFactory = expressionFactory;
            this.SetDatabaseLoadingInfo(info);
            this.ReportTrace("loading file started");

            // load file into XML document
            XmlDocument newDocument = null;
            bool isFullyTrusted = false;

            newDocument = LoadXmlDocumentFromFileLoadingInfo(authorizationManager, host, out isFullyTrusted);

            // If we're not in a locked-down environment, types and formatting are allowed based just on the authorization
            // manager. If we are in a locked-down environment, additionally check the system policy.
            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                SetLoadingInfoIsFullyTrusted(isFullyTrusted);
            }

            if (newDocument == null)
            {
                return false;
            }

            // load the XML document into a copy of the
            // in memory database
            bool previousSuppressValidation = _suppressValidation;
            try
            {
                _suppressValidation = preValidated;

                try
                {
                    this.LoadData(newDocument, db);
                }
                catch (TooManyErrorsException)
                {
                    // already logged an error before throwing
                    return false;
                }
                catch (Exception e) // will rethrow
                {
                    //Error in file {0}: {1}
                    this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message));
                    throw;
                }
                if (this.HasErrors)
                {
                    return false;
                }
            }
            finally
            {
                _suppressValidation = previousSuppressValidation;
            }

            this.ReportTrace("file loaded with no errors");
            return true;
        }
示例#51
0
 internal override void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters)
 {
     base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters);
     if ((base.dataBaseInfo != null) && (base.dataBaseInfo.view != null))
     {
         this.listBody = (ListControlBody) base.dataBaseInfo.view.mainControl;
     }
 }
示例#52
0
 internal bool LoadFormattingData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db, MshExpressionFactory expressionFactory)
 {
     if (typeDefinition == null)
     {
         throw PSTraceSource.NewArgumentNullException("typeDefinition");
     }
     if (typeDefinition.TypeName == null)
     {
         throw PSTraceSource.NewArgumentNullException("typeDefinition.TypeName");
     }
     if (db == null)
     {
         throw PSTraceSource.NewArgumentNullException("db");
     }
     if (expressionFactory == null)
     {
         throw PSTraceSource.NewArgumentNullException("expressionFactory");
     }
     base.expressionFactory = expressionFactory;
     base.ReportTrace("loading ExtendedTypeDefinition started");
     try
     {
         this.LoadData(typeDefinition, db);
     }
     catch (TooManyErrorsException)
     {
         return false;
     }
     catch (Exception exception)
     {
         base.ReportErrorForLoadingFromObjectModel(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFormattingData, typeDefinition.TypeName, exception.Message), typeDefinition.TypeName);
         throw;
     }
     if (base.HasErrors)
     {
         return false;
     }
     base.ReportTrace("ExtendedTypeDefinition loaded with no errors");
     return true;
 }
示例#53
0
        /// <summary>
        /// entry point for the loader algorithm to load formatting data from ExtendedTypeDefinition
        /// </summary>
        /// <param name="typeDefinition">the ExtendedTypeDefinition instance to load formatting data from</param>
        /// <param name="db">database instance to load the formatting data into</param>
        /// <param name="expressionFactory">expression factory to validate the script block</param>
        /// <param name="isBuiltInFormatData">do we implicitly trust the script blocks (so they should run in full langauge mode)?</param>
        /// <param name="isForHelp">true when the view is for help output</param>
        /// <returns></returns>
        internal bool LoadFormattingData(
            ExtendedTypeDefinition typeDefinition,
            TypeInfoDataBase db,
            MshExpressionFactory expressionFactory,
            bool isBuiltInFormatData,
            bool isForHelp)
        {
            if (typeDefinition == null)
                throw PSTraceSource.NewArgumentNullException("typeDefinition");
            if (typeDefinition.TypeName == null)
                throw PSTraceSource.NewArgumentNullException("typeDefinition.TypeName");
            if (db == null)
                throw PSTraceSource.NewArgumentNullException("db");
            if (expressionFactory == null)
                throw PSTraceSource.NewArgumentNullException("expressionFactory");

            this.expressionFactory = expressionFactory;
            this.ReportTrace("loading ExtendedTypeDefinition started");

            try
            {
                this.SetLoadingInfoIsFullyTrusted(isBuiltInFormatData);
                this.SetLoadingInfoIsProductCode(isBuiltInFormatData);
                this.LoadData(typeDefinition, db, isForHelp);
            }
            catch (TooManyErrorsException)
            {
                // already logged an error before throwing
                return false;
            }
            catch (Exception e) // will rethrow
            {
                //Error in formatting data "{0}": {1}
                this.ReportErrorForLoadingFromObjectModel(
                    StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFormattingData, typeDefinition.TypeName, e.Message), typeDefinition.TypeName);
                throw;
            }
            if (this.HasErrors)
            {
                return false;
            }

            this.ReportTrace("ExtendedTypeDefinition loaded with no errors");
            return true;
        }
示例#54
0
 internal bool LoadXmlFile(XmlFileLoadInfo info, TypeInfoDataBase db, MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, bool preValidated)
 {
     if (info == null)
     {
         throw PSTraceSource.NewArgumentNullException("info");
     }
     if (info.filePath == null)
     {
         throw PSTraceSource.NewArgumentNullException("info.filePath");
     }
     if (db == null)
     {
         throw PSTraceSource.NewArgumentNullException("db");
     }
     if (expressionFactory == null)
     {
         throw PSTraceSource.NewArgumentNullException("expressionFactory");
     }
     base.displayResourceManagerCache = db.displayResourceManagerCache;
     base.expressionFactory = expressionFactory;
     base.SetDatabaseLoadingInfo(info);
     base.ReportTrace("loading file started");
     XmlDocument doc = null;
     bool isFullyTrusted = false;
     doc = base.LoadXmlDocumentFromFileLoadingInfo(authorizationManager, host, out isFullyTrusted);
     if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
     {
         base.SetLoadingInfoIsFullyTrusted(isFullyTrusted);
     }
     if (doc == null)
     {
         return false;
     }
     bool suppressValidation = this.suppressValidation;
     try
     {
         this.suppressValidation = preValidated;
         try
         {
             this.LoadData(doc, db);
         }
         catch (TooManyErrorsException)
         {
             return false;
         }
         catch (Exception exception)
         {
             base.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, base.FilePath, exception.Message));
             throw;
         }
         if (base.HasErrors)
         {
             return false;
         }
     }
     finally
     {
         this.suppressValidation = suppressValidation;
     }
     base.ReportTrace("file loaded with no errors");
     return true;
 }
 internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                         PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
 {
     base.Initialize(errorContext, expressionFactory, so, db, parameters);
     this.inputParameters = parameters;
 }
示例#56
0
        private static ViewGenerator SelectViewGeneratorFromViewDefinition(
                                        TerminatingErrorContext errorContext,
                                        MshExpressionFactory expressionFactory,
                                        TypeInfoDataBase db,
                                        ViewDefinition view,
                                        FormattingCommandLineParameters parameters)
        {
            ViewGenerator viewGenerator = null;
            if (view.mainControl is TableControlBody)
            {
                viewGenerator = new TableViewGenerator();
            }
            else if (view.mainControl is ListControlBody)
            {
                viewGenerator = new ListViewGenerator();
            }
            else if (view.mainControl is WideControlBody)
            {
                viewGenerator = new WideViewGenerator();
            }
            else if (view.mainControl is ComplexControlBody)
            {
                viewGenerator = new ComplexViewGenerator();
            }

            Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");
            viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters);
            return viewGenerator;
        }
示例#57
0
        private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so,
                                    TerminatingErrorContext errorContext,
                                    MshExpressionFactory expressionFactory,
                                    TypeInfoDataBase db,
                                    FormattingCommandLineParameters parameters)
        {
            // use some heuristics to determine the shape if none is specified
            if (shape == FormatShape.Undefined && parameters == null)
            {
                // check first if we have a known shape for a type
                var typeNames = so.InternalTypeNames;
                shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames);

                if (shape == FormatShape.Undefined)
                {
                    // check if we can have a table:
                    // we want to get the # of properties we are going to display
                    List<MshExpression> expressionList = PSObjectHelper.GetDefaultPropertySet(so);
                    if (expressionList.Count == 0)
                    {
                        // we failed to get anything from a property set
                        // we just get the first properties out of the first object
                        foreach (MshResolvedExpressionParameterAssociation mrepa in AssociationManager.ExpandAll(so))
                        {
                            expressionList.Add(mrepa.ResolvedExpression);
                        }
                    }

                    // decide what shape we want for the given number of properties
                    shape = DisplayDataQuery.GetShapeFromPropertyCount(db, expressionList.Count);
                }
            }

            ViewGenerator viewGenerator = null;
            if (shape == FormatShape.Table)
            {
                viewGenerator = new TableViewGenerator();
            }
            else if (shape == FormatShape.List)
            {
                viewGenerator = new ListViewGenerator();
            }
            else if (shape == FormatShape.Wide)
            {
                viewGenerator = new WideViewGenerator();
            }
            else if (shape == FormatShape.Complex)
            {
                viewGenerator = new ComplexViewGenerator();
            }
            Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");

            viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters);
            return viewGenerator;
        }
示例#58
0
        private static ViewDefinition GetDefaultView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
            {
                if (vd == null)
                    continue;

                if (IsOutOfBandView(vd))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH OutOfBand {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                if (vd.appliesTo == null)
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}  No applicable types",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                try
                {
                    TypeMatch.SetTracer(ActiveTracer);
                    if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
                    {
                        TraceHelper(vd, true);
                        return vd;
                    }
                }
                finally
                {
                    TypeMatch.ResetTracer();
                }
                TraceHelper(vd, false);
            }
            // this is the best match we had
            ViewDefinition result = GetBestMatch(match);
            // we were unable to find a best match so far..try
            // to get rid of Deserialization prefix and see if a
            // match can be found.
            if (null == result)
            {
                Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (null != typesWithoutPrefix)
                {
                    result = GetDefaultView(expressionFactory, db, typesWithoutPrefix);
                }
            }

            return result;
        }
示例#59
0
        internal void Initialize(TerminatingErrorContext errorContext,
                                    MshExpressionFactory expressionFactory,
                                    TypeInfoDataBase db,
                                    PSObject so,
                                    FormatShape shape,
                                    FormattingCommandLineParameters parameters)
        {
            ViewDefinition view = null;
            const string findViewType = "FINDING VIEW  TYPE: {0}";
            const string findViewShapeType = "FINDING VIEW {0} TYPE: {1}";
            const string findViewNameType = "FINDING VIEW NAME: {0}  TYPE: {1}";
            const string viewFound = "An applicable view has been found";
            const string viewNotFound = "No applicable view has been found";
            try
            {
                DisplayDataQuery.SetTracer(s_formatViewBindingTracer);

                // shape not specified: we need to select one
                var typeNames = so.InternalTypeNames;
                if (shape == FormatShape.Undefined)
                {
                    using (s_formatViewBindingTracer.TraceScope(findViewType, PSObjectTypeName(so)))
                    {
                        view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null);
                    }
                    if (view != null)
                    {
                        // we got a matching view from the database
                        // use this and we are done
                        _viewGenerator = SelectViewGeneratorFromViewDefinition(
                                                errorContext,
                                                expressionFactory,
                                                db,
                                                view,
                                                parameters);
                        s_formatViewBindingTracer.WriteLine(viewFound);
                        PrepareViewForRemoteObjects(ViewGenerator, so);
                        return;
                    }

                    s_formatViewBindingTracer.WriteLine(viewNotFound);
                    // we did not get any default view (and shape), we need to force one
                    // we just select properties out of the object itself, since they were not
                    // specified on the command line
                    _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null);
                    PrepareViewForRemoteObjects(ViewGenerator, so);

                    return;
                }

                // we have a predefined shape: did the user specify properties on the command line?
                if (parameters != null && parameters.mshParameterList.Count > 0)
                {
                    _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
                    return;
                }

                // predefined shape: did the user specify the name of a view?
                if (parameters != null && !string.IsNullOrEmpty(parameters.viewName))
                {
                    using (s_formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName,
                        PSObjectTypeName(so)))
                    {
                        view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName);
                    }
                    if (view != null)
                    {
                        _viewGenerator = SelectViewGeneratorFromViewDefinition(
                                                    errorContext,
                                                    expressionFactory,
                                                    db,
                                                    view,
                                                    parameters);
                        s_formatViewBindingTracer.WriteLine(viewFound);
                        return;
                    }
                    s_formatViewBindingTracer.WriteLine(viewNotFound);
                    // illegal input, we have to terminate
                    ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape);
                }

                // predefined shape: do we have a default view in format.ps1xml?
                using (s_formatViewBindingTracer.TraceScope(findViewShapeType, shape, PSObjectTypeName(so)))
                {
                    view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null);
                }
                if (view != null)
                {
                    _viewGenerator = SelectViewGeneratorFromViewDefinition(
                                                errorContext,
                                                expressionFactory,
                                                db,
                                                view,
                                                parameters);
                    s_formatViewBindingTracer.WriteLine(viewFound);
                    PrepareViewForRemoteObjects(ViewGenerator, so);

                    return;
                }
                s_formatViewBindingTracer.WriteLine(viewNotFound);
                // we just select properties out of the object itself
                _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
                PrepareViewForRemoteObjects(ViewGenerator, so);
            }
            finally
            {
                DisplayDataQuery.ResetTracer();
            }
        }
示例#60
0
 internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames, bool useInheritance)
 {
     _expressionFactory = expressionFactory;
     _db = db;
     _typeNameHierarchy = typeNames;
     _useInheritance = useInheritance;
 }