private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNode) { using (this.StackFrame(viewDefinitionsNode)) { int index = 0; foreach (XmlNode n in viewDefinitionsNode.ChildNodes) { if (MatchNodeName(n, XmlTags.ViewNode)) { ViewDefinition view = LoadView(n, index++); if (view != null) { ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from file {2}", ControlBase.GetControlShapeName(view.mainControl), view.name, view.loadingInfo.filePath)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); } } else { ProcessUnknownNode(n); } } } }
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; } }
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; }
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; }
internal static TypeGroupDefinition FindGroupDefinition(TypeInfoDataBase db, string groupName) { foreach (TypeGroupDefinition definition in db.typeGroupSection.typeGroupDefinitionList) { if (string.Equals(definition.name, groupName, StringComparison.OrdinalIgnoreCase)) { return definition; } } return null; }
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); }
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(); }
internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters formatParameters) { errorContext = terminatingErrorContext; expressionFactory = mshExpressionFactory; parameters = formatParameters; dataBaseInfo.db = db; InitializeHelper(); }
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>(); }
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); }
internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, PSPropertyExpressionFactory expressionFactory, List <ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext) { _db = dataBase; _loadingInfo = loadingInfo; _expressionFactory = expressionFactory; _controlDefinitionList = controlDefinitionList; _errorManager = resultErrorManager; _enumerationLimit = enumerationLimit; _errorContext = errorContext; }
internal bool LoadFromFile( Collection <PSSnapInTypeAndFormatErrors> files, MshExpressionFactory expressionFactory, bool acceptLoadingErrors, AuthorizationManager authorizationManager, PSHost host, out List <XmlLoaderLoggerEntry> logEntries) { if (this.isShared) { throw TypeInfoDataBaseManager.tracer.NewInvalidOperationException("FormatAndOut.XmlLoading", "SharedFormattableCannotBeUpdated"); } bool success; try { TypeInfoDataBase typeInfoDataBase = (TypeInfoDataBase)null; lock (this.updateDatabaseLock) typeInfoDataBase = TypeInfoDataBaseManager.LoadFromFileHelper(files, expressionFactory, authorizationManager, host, out logEntries, out success); lock (this.databaseLock) { if (!acceptLoadingErrors) { if (!success) { goto label_15; } } this.dataBase = typeInfoDataBase; } } finally { lock (this.databaseLock) { if (this.dataBase == null) { TypeInfoDataBase db = new TypeInfoDataBase(); TypeInfoDataBaseManager.AddPreLoadInstrinsics(db); TypeInfoDataBaseManager.AddPostLoadInstrinsics(db); this.dataBase = db; } } } label_15: return(success); }
/// <summary> /// Load the database /// NOTE: need to be protected by lock since not thread safe per se. /// </summary> /// <param name="files">*.formal.xml files to be loaded.</param> /// <param name="expressionFactory">Expression factory to validate script blocks.</param> /// <param name="acceptLoadingErrors">If true, load the database even if there are loading errors.</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> /// <param name="logEntries">Trace and error logs from loading the format Xml files.</param> /// <returns>True if we had a successful load.</returns> internal bool LoadFromFile( Collection <PSSnapInTypeAndFormatErrors> files, PSPropertyExpressionFactory expressionFactory, bool acceptLoadingErrors, AuthorizationManager authorizationManager, PSHost host, bool preValidated, out List <XmlLoaderLoggerEntry> logEntries) { bool success; try { TypeInfoDataBase newDataBase = null; lock (updateDatabaseLock) { newDataBase = LoadFromFileHelper(files, expressionFactory, authorizationManager, host, preValidated, out logEntries, out success); } // if we have a valid database, assign it to the // current database lock (databaseLock) { if (acceptLoadingErrors || success) { Database = newDataBase; } } } finally { // if, for any reason, we failed the load, we initialize the // data base to an empty instance lock (databaseLock) { if (Database == null) { TypeInfoDataBase tempDataBase = new TypeInfoDataBase(); AddPreLoadIntrinsics(tempDataBase); AddPostLoadIntrinsics(tempDataBase); Database = tempDataBase; } } } return(success); }
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; }
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(); }
internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory 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(); }
private static TypeInfoDataBase LoadFromFileHelper( Collection <PSSnapInTypeAndFormatErrors> files, MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, out List <XmlLoaderLoggerEntry> logEntries, out bool success) { success = true; logEntries = new List <XmlLoaderLoggerEntry>(); List <XmlFileLoadInfo> xmlFileLoadInfoList = new List <XmlFileLoadInfo>(); foreach (PSSnapInTypeAndFormatErrors file in files) { xmlFileLoadInfoList.Add(new XmlFileLoadInfo(Path.GetPathRoot(file.FullPath), file.FullPath, file.Errors, file.PSSnapinName)); } TypeInfoDataBase db = new TypeInfoDataBase(); TypeInfoDataBaseManager.AddPreLoadInstrinsics(db); foreach (XmlFileLoadInfo info in xmlFileLoadInfoList) { using (TypeInfoDataBaseLoader infoDataBaseLoader = new TypeInfoDataBaseLoader()) { if (!infoDataBaseLoader.LoadXmlFile(info, db, expressionFactory, authorizationManager, host)) { success = false; } foreach (XmlLoaderLoggerEntry logEntry in infoDataBaseLoader.LogEntries) { if (logEntry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { string str = XmlLoadingResourceManager.FormatString("MshSnapinQualifiedError", (object)info.psSnapinName, (object)logEntry.message); info.errors.Add(str); } } logEntries.AddRange((IEnumerable <XmlLoaderLoggerEntry>)infoDataBaseLoader.LogEntries); } } TypeInfoDataBaseManager.AddPostLoadInstrinsics(db); return(db); }
internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo appliesTo) { Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (TypeOrGroupReference reference in appliesTo.referenceList) { TypeReference reference2 = reference as TypeReference; if (reference2 != null) { if (!hashtable.ContainsKey(reference2.name)) { hashtable.Add(reference2.name, null); } } else { TypeGroupReference reference3 = reference as TypeGroupReference; if (reference3 != null) { TypeGroupDefinition definition = FindGroupDefinition(db, reference3.name); if (definition != null) { foreach (TypeReference reference4 in definition.typeReferenceList) { if (!hashtable.ContainsKey(reference4.name)) { hashtable.Add(reference4.name, null); } } } } } } AppliesTo to = new AppliesTo(); foreach (DictionaryEntry entry in hashtable) { to.AddAppliesToType(entry.Key as string); } return(to); }
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; }
internal static EnumerableExpansion GetEnumerableExpansionFromType( MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames) { TypeMatch typeMatch = new TypeMatch(expressionFactory, db, typeNames); foreach (EnumerableExpansionDirective expansionDirective in db.defaultSettingsSection.enumerableExpansionDirectiveList) { if (typeMatch.PerfectMatch(new TypeMatchItem((object)expansionDirective, expansionDirective.appliesTo))) { return(expansionDirective.enumerableExpansion); } } if (typeMatch.BestMatch != null) { return(((EnumerableExpansionDirective)typeMatch.BestMatch).enumerableExpansion); } Collection <string> typeNames1 = Deserializer.MaskDeserializationPrefix(typeNames); return(typeNames1 != null?DisplayDataQuery.GetEnumerableExpansionFromType(expressionFactory, db, typeNames1) : EnumerableExpansion.EnumOnly); }
internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo appliesTo) { Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (TypeOrGroupReference reference in appliesTo.referenceList) { TypeReference reference2 = reference as TypeReference; if (reference2 != null) { if (!hashtable.ContainsKey(reference2.name)) { hashtable.Add(reference2.name, null); } } else { TypeGroupReference reference3 = reference as TypeGroupReference; if (reference3 != null) { TypeGroupDefinition definition = FindGroupDefinition(db, reference3.name); if (definition != null) { foreach (TypeReference reference4 in definition.typeReferenceList) { if (!hashtable.ContainsKey(reference4.name)) { hashtable.Add(reference4.name, null); } } } } } } AppliesTo to = new AppliesTo(); foreach (DictionaryEntry entry in hashtable) { to.AddAppliesToType(entry.Key as string); } return to; }
private static bool ProcessBuiltin( PSSnapInTypeAndFormatErrors file, TypeInfoDataBase db, PSPropertyExpressionFactory expressionFactory, List <XmlLoaderLoggerEntry> logEntries, ref bool success) { if (s_builtinGenerators == null) { var builtInGenerators = new Dictionary <string, Tuple <bool, TypeGenerator> >(StringComparer.OrdinalIgnoreCase); var psHome = Utils.DefaultPowerShellAppBase; builtInGenerators.Add(Path.Combine(psHome, "Certificate.format.ps1xml"), GetBuiltin(false, Certificate_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Diagnostics.Format.ps1xml"), GetBuiltin(false, Diagnostics_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "DotNetTypes.format.ps1xml"), GetBuiltin(false, DotNetTypes_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Event.Format.ps1xml"), GetBuiltin(false, Event_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "FileSystem.format.ps1xml"), GetBuiltin(false, FileSystem_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Help.format.ps1xml"), GetBuiltin(true, Help_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "HelpV3.format.ps1xml"), GetBuiltin(true, HelpV3_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "PowerShellCore.format.ps1xml"), GetBuiltin(false, PowerShellCore_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "PowerShellTrace.format.ps1xml"), GetBuiltin(false, PowerShellTrace_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "Registry.format.ps1xml"), GetBuiltin(false, Registry_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "WSMan.Format.ps1xml"), GetBuiltin(false, WSMan_Format_Ps1Xml.GetFormatData)); Interlocked.CompareExchange(ref s_builtinGenerators, builtInGenerators, null); } Tuple <bool, TypeGenerator> generator; if (!s_builtinGenerators.TryGetValue(file.FullPath, out generator)) { return(false); } ProcessBuiltinFormatViewDefinitions(generator.Item2(), db, expressionFactory, file, logEntries, generator.Item1, ref success); return(true); }
internal static AppliesTo GetAllApplicableTypes( TypeInfoDataBase db, AppliesTo appliesTo) { Hashtable hashtable = new Hashtable((IEqualityComparer)StringComparer.OrdinalIgnoreCase); foreach (TypeOrGroupReference reference in appliesTo.referenceList) { if (reference is TypeReference typeReference) { if (!hashtable.ContainsKey((object)typeReference.name)) { hashtable.Add((object)typeReference.name, (object)null); } } else if (reference is TypeGroupReference typeGroupReference) { TypeGroupDefinition groupDefinition = DisplayDataQuery.FindGroupDefinition(db, typeGroupReference.name); if (groupDefinition != null) { foreach (TypeReference typeReference in groupDefinition.typeReferenceList) { if (!hashtable.ContainsKey((object)typeReference.name)) { hashtable.Add((object)typeReference.name, (object)null); } } } } } AppliesTo appliesTo1 = new AppliesTo(); foreach (DictionaryEntry dictionaryEntry in hashtable) { appliesTo1.AddAppliesToType(dictionaryEntry.Key as string); } return(appliesTo1); }
internal static FormatShape GetShapeFromType( MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames) { ShapeSelectionDirectives selectionDirectives = db.defaultSettingsSection.shapeSelectionDirectives; TypeMatch typeMatch = new TypeMatch(expressionFactory, db, typeNames); foreach (FormatShapeSelectionOnType shapeSelectionOnType in selectionDirectives.formatShapeSelectionOnTypeList) { if (typeMatch.PerfectMatch(new TypeMatchItem((object)shapeSelectionOnType, shapeSelectionOnType.appliesTo))) { return(shapeSelectionOnType.formatShape); } } if (typeMatch.BestMatch != null) { return(((FormatShapeSelectionBase)typeMatch.BestMatch).formatShape); } Collection <string> typeNames1 = Deserializer.MaskDeserializationPrefix(typeNames); return(typeNames1 != null?DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames1) : FormatShape.Undefined); }
internal static ViewDefinition GetOutOfBandView( MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection <string> typeNames) { TypeMatch typeMatch = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition viewDefinition in db.viewDefinitionsSection.viewDefinitionList) { if (DisplayDataQuery.IsOutOfBandView(viewDefinition) && typeMatch.PerfectMatch(new TypeMatchItem((object)viewDefinition, viewDefinition.appliesTo))) { return(viewDefinition); } } if (!(typeMatch.BestMatch is ViewDefinition viewDefinition)) { Collection <string> typeNames1 = Deserializer.MaskDeserializationPrefix(typeNames); if (typeNames1 != null) { viewDefinition = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames1); } } return(viewDefinition); }
/// <summary> /// Helper method to process Unknown error message. /// It helps is creating appropriate error message to /// be displayed to the user. /// </summary> /// <param name="errorContext">Error context.</param> /// <param name="viewName">Uses supplied view name.</param> /// <param name="so">Source object.</param> /// <param name="db">Types info database.</param> /// <param name="formatShape">Requested format shape.</param> private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string viewName, PSObject so, TypeInfoDataBase db, FormatShape formatShape) { string msg = null; bool foundValidViews = false; string formatTypeName = null; string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && db != null && db.viewDefinitionsSection != null && db.viewDefinitionsSection.viewDefinitionList != null && db.viewDefinitionsSection.viewDefinitionList.Count > 0) { StringBuilder validViews = new StringBuilder(); string currentObjectTypeName = so.BaseObject.GetType().ToString(); Type formatType = null; if (formatShape == FormatShape.Table) { formatType = typeof(TableControlBody); formatTypeName = "Table"; } else if (formatShape == FormatShape.List) { formatType = typeof(ListControlBody); formatTypeName = "List"; } else if (formatShape == FormatShape.Wide) { formatType = typeof(WideControlBody); formatTypeName = "Wide"; } else if (formatShape == FormatShape.Complex) { formatType = typeof(ComplexControlBody); formatTypeName = "Custom"; } if (formatType != null) { foreach (ViewDefinition currentViewDefinition in db.viewDefinitionsSection.viewDefinitionList) { if (currentViewDefinition.mainControl != null) { foreach (TypeOrGroupReference currentTypeOrGroupReference in currentViewDefinition.appliesTo.referenceList) { if (!string.IsNullOrEmpty(currentTypeOrGroupReference.name) && String.Equals(currentObjectTypeName, currentTypeOrGroupReference.name, StringComparison.OrdinalIgnoreCase)) { if (currentViewDefinition.mainControl.GetType() == formatType) { validViews.Append(currentViewDefinition.name); validViews.Append(separator); } else if (String.Equals(viewName, currentViewDefinition.name, StringComparison.OrdinalIgnoreCase)) { string cmdletFormatName = null; if (currentViewDefinition.mainControl is TableControlBody) { cmdletFormatName = "Format-Table"; } else if (currentViewDefinition.mainControl is ListControlBody) { cmdletFormatName = "Format-List"; } else if (currentViewDefinition.mainControl is WideControlBody) { cmdletFormatName = "Format-Wide"; } else if (currentViewDefinition.mainControl is ComplexControlBody) { cmdletFormatName = "Format-Custom"; } if (validViewFormats.Length == 0) { string suggestValidViewNamePrefix = StringUtil.Format(FormatAndOut_format_xxx.SuggestValidViewNamePrefix); validViewFormats.Append(suggestValidViewNamePrefix); } else { validViewFormats.Append(", "); } validViewFormats.Append(cmdletFormatName); } } } } } } if (validViews.Length > 0) { validViews.Remove(validViews.Length - separator.Length, separator.Length); msg = StringUtil.Format(FormatAndOut_format_xxx.InvalidViewNameError, viewName, formatTypeName, validViews.ToString()); foundValidViews = true; } } if (!foundValidViews) { StringBuilder unKnowViewFormatStringBuilder = new StringBuilder(); if (validViewFormats.Length > 0) { //unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameErrorSuffix, viewName, formatTypeName)); unKnowViewFormatStringBuilder.Append(validViewFormats.ToString()); } else { unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, formatTypeName, so.BaseObject.GetType())); } msg = unKnowViewFormatStringBuilder.ToString();; } ErrorRecord errorRecord = new ErrorRecord( new PipelineStoppedException(), "FormatViewNotFound", ErrorCategory.ObjectNotFound, viewName); errorRecord.ErrorDetails = new ErrorDetails(msg); errorContext.ThrowTerminatingError(errorRecord); }
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); }
private static Microsoft.PowerShell.Commands.Internal.Format.ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so, TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { if ((shape == FormatShape.Undefined) && (parameters == null)) { ConsolidatedString internalTypeNames = so.InternalTypeNames; shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, internalTypeNames); if (shape == FormatShape.Undefined) { List <MshExpression> defaultPropertySet = PSObjectHelper.GetDefaultPropertySet(so); if (defaultPropertySet.Count == 0) { foreach (MshResolvedExpressionParameterAssociation association in AssociationManager.ExpandAll(so)) { defaultPropertySet.Add(association.ResolvedExpression); } } shape = DisplayDataQuery.GetShapeFromPropertyCount(db, defaultPropertySet.Count); } } Microsoft.PowerShell.Commands.Internal.Format.ViewGenerator generator = null; if (shape == FormatShape.Table) { generator = new TableViewGenerator(); } else if (shape == FormatShape.List) { generator = new ListViewGenerator(); } else if (shape == FormatShape.Wide) { generator = new WideViewGenerator(); } else if (shape == FormatShape.Complex) { generator = new ComplexViewGenerator(); } generator.Initialize(errorContext, expressionFactory, so, db, parameters); return(generator); }
internal void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, FormatShape shape, FormattingCommandLineParameters parameters) { ViewDefinition view = null; try { DisplayDataQuery.SetTracer(formatViewBindingTracer); ConsolidatedString internalTypeNames = so.InternalTypeNames; if (shape == FormatShape.Undefined) { using (formatViewBindingTracer.TraceScope("FINDING VIEW TYPE: {0}", new object[] { PSObjectTypeName(so) })) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, internalTypeNames, null); } if (view != null) { this.viewGenerator = SelectViewGeneratorFromViewDefinition(errorContext, expressionFactory, db, view, parameters); formatViewBindingTracer.WriteLine("An applicable view has been found", new object[0]); PrepareViewForRemoteObjects(this.ViewGenerator, so); } else { formatViewBindingTracer.WriteLine("No applicable view has been found", new object[0]); this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null); PrepareViewForRemoteObjects(this.ViewGenerator, so); } } else if ((parameters != null) && (parameters.mshParameterList.Count > 0)) { this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); } else { if ((parameters != null) && !string.IsNullOrEmpty(parameters.viewName)) { using (formatViewBindingTracer.TraceScope("FINDING VIEW NAME: {0} TYPE: {1}", new object[] { parameters.viewName, PSObjectTypeName(so) })) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, internalTypeNames, parameters.viewName); } if (view != null) { this.viewGenerator = SelectViewGeneratorFromViewDefinition(errorContext, expressionFactory, db, view, parameters); formatViewBindingTracer.WriteLine("An applicable view has been found", new object[0]); return; } formatViewBindingTracer.WriteLine("No applicable view has been found", new object[0]); ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape); } using (formatViewBindingTracer.TraceScope("FINDING VIEW {0} TYPE: {1}", new object[] { shape, PSObjectTypeName(so) })) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, internalTypeNames, null); } if (view != null) { this.viewGenerator = SelectViewGeneratorFromViewDefinition(errorContext, expressionFactory, db, view, parameters); formatViewBindingTracer.WriteLine("An applicable view has been found", new object[0]); PrepareViewForRemoteObjects(this.ViewGenerator, so); } else { formatViewBindingTracer.WriteLine("No applicable view has been found", new object[0]); this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); PrepareViewForRemoteObjects(this.ViewGenerator, so); } } } finally { DisplayDataQuery.ResetTracer(); } }
private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db) { if (typeDefinition == null) { throw PSTraceSource.NewArgumentNullException("viewDefinition"); } if (db == null) { throw PSTraceSource.NewArgumentNullException("db"); } int num = 0; foreach (FormatViewDefinition definition in typeDefinition.FormatViewDefinition) { ViewDefinition item = this.LoadViewFromObjectModle(typeDefinition.TypeName, definition, num++); if (item != null) { base.ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from the 'FormatViewDefinition' at index {2} in 'ExtendedTypeDefinition' with type name {3}", new object[] { ControlBase.GetControlShapeName(item.mainControl), item.name, num - 1, typeDefinition.TypeName })); db.viewDefinitionsSection.viewDefinitionList.Add(item); } } }
private void LoadDefaultSettings(TypeInfoDataBase db, System.Xml.XmlNode defaultSettingsNode) { bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; using (base.StackFrame(defaultSettingsNode)) { foreach (System.Xml.XmlNode node in defaultSettingsNode.ChildNodes) { bool flag6; if (base.MatchNodeName(node, "ShowError")) { if (flag2) { base.ProcessDuplicateNode(node); } flag2 = true; if (this.ReadBooleanNode(node, out flag6)) { db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages = flag6; } } else if (base.MatchNodeName(node, "DisplayError")) { if (flag3) { base.ProcessDuplicateNode(node); } flag3 = true; if (this.ReadBooleanNode(node, out flag6)) { db.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput = flag6; } } else if (base.MatchNodeName(node, "PropertyCountForTable")) { int num; if (flag) { base.ProcessDuplicateNode(node); } flag = true; if (this.ReadPositiveIntegerValue(node, out num)) { db.defaultSettingsSection.shapeSelectionDirectives.PropertyCountForTable = num; } else { base.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNodeValue, new object[] { base.ComputeCurrentXPath(), base.FilePath, "PropertyCountForTable" })); } } else if (base.MatchNodeName(node, "WrapTables")) { if (flag5) { base.ProcessDuplicateNode(node); } flag5 = true; if (this.ReadBooleanNode(node, out flag6)) { db.defaultSettingsSection.MultilineTables = flag6; } else { base.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNodeValue, new object[] { base.ComputeCurrentXPath(), base.FilePath, "WrapTables" })); } } else if (base.MatchNodeName(node, "EnumerableExpansions")) { if (flag4) { base.ProcessDuplicateNode(node); } flag4 = true; db.defaultSettingsSection.enumerableExpansionDirectiveList = this.LoadEnumerableExpansionDirectiveList(node); } else { base.ProcessUnknownNode(node); } } } }
private void LoadTypeGroup(TypeInfoDataBase db, System.Xml.XmlNode typeGroupNode, int index) { using (base.StackFrame(typeGroupNode, index)) { TypeGroupDefinition typeGroupDefinition = new TypeGroupDefinition(); bool flag = false; foreach (System.Xml.XmlNode node in typeGroupNode.ChildNodes) { if (base.MatchNodeName(node, "Name")) { if (flag) { base.ProcessDuplicateNode(node); } else { flag = true; typeGroupDefinition.name = base.GetMandatoryInnerText(node); } } else if (base.MatchNodeName(node, "Types")) { this.LoadTypeGroupTypeRefs(node, typeGroupDefinition); } else { base.ProcessUnknownNode(node); } } if (!flag) { base.ReportMissingNode("Name"); } db.typeGroupSection.typeGroupDefinitionList.Add(typeGroupDefinition); } }
private void LoadViewDefinitions(TypeInfoDataBase db, System.Xml.XmlNode viewDefinitionsNode) { using (base.StackFrame(viewDefinitionsNode)) { int num = 0; foreach (System.Xml.XmlNode node in viewDefinitionsNode.ChildNodes) { if (base.MatchNodeName(node, "View")) { ViewDefinition item = this.LoadView(node, num++); if (item != null) { base.ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from file {2}", new object[] { ControlBase.GetControlShapeName(item.mainControl), item.name, item.loadingInfo.filePath })); db.viewDefinitionsSection.viewDefinitionList.Add(item); } } else { base.ProcessUnknownNode(node); } } } }
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(); } }
internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; }
private static Microsoft.PowerShell.Commands.Internal.Format.ViewGenerator SelectViewGeneratorFromViewDefinition(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters parameters) { Microsoft.PowerShell.Commands.Internal.Format.ViewGenerator generator = null; if (view.mainControl is TableControlBody) { generator = new TableViewGenerator(); } else if (view.mainControl is ListControlBody) { generator = new ListViewGenerator(); } else if (view.mainControl is WideControlBody) { generator = new WideViewGenerator(); } else if (view.mainControl is ComplexControlBody) { generator = new ComplexViewGenerator(); } generator.Initialize(errorContext, expressionFactory, db, view, parameters); return(generator); }
internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } }
private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string viewName, PSObject so, TypeInfoDataBase db, FormatShape formatShape) { string message = null; bool flag = false; string str2 = null; string str3 = ", "; StringBuilder builder = new StringBuilder(); if ((((so != null) && (so.BaseObject != null)) && ((db != null) && (db.viewDefinitionsSection != null))) && ((db.viewDefinitionsSection.viewDefinitionList != null) && (db.viewDefinitionsSection.viewDefinitionList.Count > 0))) { StringBuilder builder2 = new StringBuilder(); string a = so.BaseObject.GetType().ToString(); Type type = null; if (formatShape == FormatShape.Table) { type = typeof(TableControlBody); str2 = "Table"; } else if (formatShape == FormatShape.List) { type = typeof(ListControlBody); str2 = "List"; } else if (formatShape == FormatShape.Wide) { type = typeof(WideControlBody); str2 = "Wide"; } else if (formatShape == FormatShape.Complex) { type = typeof(ComplexControlBody); str2 = "Custom"; } if (type != null) { foreach (ViewDefinition definition in db.viewDefinitionsSection.viewDefinitionList) { if (definition.mainControl != null) { foreach (TypeOrGroupReference reference in definition.appliesTo.referenceList) { if (!string.IsNullOrEmpty(reference.name) && string.Equals(a, reference.name, StringComparison.OrdinalIgnoreCase)) { if (definition.mainControl.GetType() == type) { builder2.Append(definition.name); builder2.Append(str3); } else if (string.Equals(viewName, definition.name, StringComparison.OrdinalIgnoreCase)) { string str5 = null; if (definition.mainControl.GetType() == typeof(TableControlBody)) { str5 = "Format-Table"; } else if (definition.mainControl.GetType() == typeof(ListControlBody)) { str5 = "Format-List"; } else if (definition.mainControl.GetType() == typeof(WideControlBody)) { str5 = "Format-Wide"; } else if (definition.mainControl.GetType() == typeof(ComplexControlBody)) { str5 = "Format-Custom"; } if (builder.Length == 0) { string str6 = StringUtil.Format(FormatAndOut_format_xxx.SuggestValidViewNamePrefix, new object[0]); builder.Append(str6); } else { builder.Append(", "); } builder.Append(str5); } } } } } } if (builder2.Length > 0) { builder2.Remove(builder2.Length - str3.Length, str3.Length); message = StringUtil.Format(FormatAndOut_format_xxx.InvalidViewNameError, new object[] { viewName, str2, builder2.ToString() }); flag = true; } } if (!flag) { StringBuilder builder3 = new StringBuilder(); if (builder.Length > 0) { builder3.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameErrorSuffix, viewName, str2)); builder3.Append(builder.ToString()); } else { builder3.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); builder3.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, str2, so.BaseObject.GetType())); } message = builder3.ToString(); } ErrorRecord errorRecord = new ErrorRecord(new PipelineStoppedException(), "FormatViewNotFound", ErrorCategory.ObjectNotFound, viewName) { ErrorDetails = new ErrorDetails(message) }; errorContext.ThrowTerminatingError(errorRecord); }
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)); }
/// <summary> /// load the content of the XML document into the data instance. /// It assumes that the XML document has been successfully loaded /// </summary> /// <param name="doc">XML document to load from, cannot be null</param> /// <param name="db"> instance of the databaseto load into</param> private void LoadData(XmlDocument doc, TypeInfoDataBase db) { if (doc == null) throw PSTraceSource.NewArgumentNullException("doc"); if (db == null) throw PSTraceSource.NewArgumentNullException("db"); // create a new instance of the database to be loaded XmlElement documentElement = doc.DocumentElement; bool defaultSettingsNodeFound = false; bool typeGroupsFound = false; bool viewDefinitionsFound = false; bool controlDefinitionsFound = false; if (MatchNodeName(documentElement, XmlTags.ConfigurationNode)) { // load the various sections using (this.StackFrame(documentElement)) { foreach (XmlNode n in documentElement.ChildNodes) { if (MatchNodeName(n, XmlTags.DefaultSettingsNode)) { if (defaultSettingsNodeFound) { ProcessDuplicateNode(n); } defaultSettingsNodeFound = true; LoadDefaultSettings(db, n); } else if (MatchNodeName(n, XmlTags.SelectionSetsNode)) { if (typeGroupsFound) { ProcessDuplicateNode(n); } typeGroupsFound = true; LoadTypeGroups(db, n); } else if (MatchNodeName(n, XmlTags.ViewDefinitionsNode)) { if (viewDefinitionsFound) { ProcessDuplicateNode(n); } viewDefinitionsFound = true; LoadViewDefinitions(db, n); } else if (MatchNodeName(n, XmlTags.ControlsNode)) { if (controlDefinitionsFound) { ProcessDuplicateNode(n); } controlDefinitionsFound = true; LoadControlDefinitions(n, db.formatControlDefinitionHolder.controlDefinitionList); } else { ProcessUnknownNode(n); } } // foreach } // using } else { ProcessUnknownNode(documentElement); } }
internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; }
internal static EnumerableExpansion GetEnumerableExpansionFromType(PSPropertyExpressionFactory 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 (typesWithoutPrefix != null) { EnumerableExpansion result = GetEnumerableExpansionFromType(expressionFactory, db, typesWithoutPrefix); return(result); } // return a default value if no matches were found return(EnumerableExpansion.EnumOnly); } }
private void LoadTypeGroups(TypeInfoDataBase db, System.Xml.XmlNode typeGroupsNode) { using (base.StackFrame(typeGroupsNode)) { int num = 0; foreach (System.Xml.XmlNode node in typeGroupsNode.ChildNodes) { if (base.MatchNodeName(node, "SelectionSet")) { this.LoadTypeGroup(db, node, num++); } else { base.ProcessUnknownNode(node); } } } }
internal static FormatShape GetShapeFromType(PSPropertyExpressionFactory 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 (typesWithoutPrefix != null) { FormatShape result = GetShapeFromType(expressionFactory, db, typesWithoutPrefix); return(result); } // return a default value if no matches were found return(FormatShape.Undefined); } }
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 static ViewDefinition GetViewByShapeAndType(PSPropertyExpressionFactory 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, "unknown shape: this should never happen unless a new shape is added"); return(null); } return(GetView(expressionFactory, db, t, typeNames, viewName)); }
private void LoadData(XmlDocument doc, TypeInfoDataBase db) { if (doc == null) { throw PSTraceSource.NewArgumentNullException("doc"); } if (db == null) { throw PSTraceSource.NewArgumentNullException("db"); } XmlElement documentElement = doc.DocumentElement; bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; if (base.MatchNodeName(documentElement, "Configuration")) { using (base.StackFrame(documentElement)) { foreach (System.Xml.XmlNode node in documentElement.ChildNodes) { if (base.MatchNodeName(node, "DefaultSettings")) { if (flag) { base.ProcessDuplicateNode(node); } flag = true; this.LoadDefaultSettings(db, node); } else if (base.MatchNodeName(node, "SelectionSets")) { if (flag2) { base.ProcessDuplicateNode(node); } flag2 = true; this.LoadTypeGroups(db, node); } else if (base.MatchNodeName(node, "ViewDefinitions")) { if (flag3) { base.ProcessDuplicateNode(node); } flag3 = true; this.LoadViewDefinitions(db, node); } else if (base.MatchNodeName(node, "Controls")) { if (flag4) { base.ProcessDuplicateNode(node); } flag4 = true; this.LoadControlDefinitions(node, db.formatControlDefinitionHolder.controlDefinitionList); } else { base.ProcessUnknownNode(node); } } return; } } base.ProcessUnknownNode(documentElement); }
private static ViewDefinition GetView(PSPropertyExpressionFactory 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), (vd != null ? 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 (result == null) { Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) { result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName); } } return(result); }
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; }
private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory 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 (result == null) { Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) { result = GetDefaultView(expressionFactory, db, typesWithoutPrefix); } } return(result); }
/// <summary> /// it loads a database from file(s). /// </summary> /// <param name="files">*.formal.xml files to be loaded</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> /// <param name="logEntries">list of logger entries (errors, etc.) to return to the caller</param> /// <param name="success"> true if no error occurred</param> /// <returns>a database instance loaded from file(s)</returns> private static TypeInfoDataBase LoadFromFileHelper( Collection <PSSnapInTypeAndFormatErrors> files, PSPropertyExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, bool preValidated, out List <XmlLoaderLoggerEntry> logEntries, out bool success) { success = true; // Holds the aggregated log entries for all files... logEntries = new List <XmlLoaderLoggerEntry>(); // fresh instance of the database TypeInfoDataBase db = new TypeInfoDataBase(); // prepopulate the database with any necessary overriding data AddPreLoadIntrinsics(db); var etwEnabled = RunspaceEventSource.Log.IsEnabled(); // load the XML document into a copy of the // in memory database foreach (PSSnapInTypeAndFormatErrors file in files) { // Loads formatting data from ExtendedTypeDefinition instance if (file.FormatData != null) { LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: false, isForHelp: false); continue; } if (etwEnabled) { RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); } if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success)) { // Loads formatting data from formatting data XML file XmlFileLoadInfo info = new XmlFileLoadInfo(Path.GetPathRoot(file.FullPath), file.FullPath, file.Errors, file.PSSnapinName); using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader()) { if (!loader.LoadXmlFile(info, db, expressionFactory, authorizationManager, host, preValidated)) { 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, info.psSnapinName, entry.message); info.errors.Add(mshsnapinMessage); if (entry.failToLoadFile) { file.FailToLoadFile = true; } } } // now aggregate the entries... logEntries.AddRange(loader.LogEntries); } } if (etwEnabled) { RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); } } // add any sensible defaults to the database AddPostLoadIntrinsics(db); return(db); }
/// <summary> /// Helper method to process Unknown error message. /// It helps is creating appropriate error message to /// be displayed to the user. /// </summary> /// <param name="errorContext">Error context.</param> /// <param name="viewName">Uses supplied view name.</param> /// <param name="so">Source object.</param> /// <param name="db">Types info database.</param> /// <param name="formatShape">Requested format shape.</param> private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string viewName, PSObject so, TypeInfoDataBase db, FormatShape formatShape) { string msg = null; bool foundValidViews = false; string formatTypeName = null; string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && db != null && db.viewDefinitionsSection != null && db.viewDefinitionsSection.viewDefinitionList != null && db.viewDefinitionsSection.viewDefinitionList.Count > 0) { StringBuilder validViews = new StringBuilder(); string currentObjectTypeName = so.BaseObject.GetType().ToString(); Type formatType = null; if (formatShape == FormatShape.Table) { formatType = typeof(TableControlBody); formatTypeName = "Table"; } else if (formatShape == FormatShape.List) { formatType = typeof(ListControlBody); formatTypeName = "List"; } else if (formatShape == FormatShape.Wide) { formatType = typeof(WideControlBody); formatTypeName = "Wide"; } else if (formatShape == FormatShape.Complex) { formatType = typeof(ComplexControlBody); formatTypeName = "Custom"; } if (formatType != null) { foreach (ViewDefinition currentViewDefinition in db.viewDefinitionsSection.viewDefinitionList) { if (currentViewDefinition.mainControl != null) { foreach (TypeOrGroupReference currentTypeOrGroupReference in currentViewDefinition.appliesTo.referenceList) { if (!string.IsNullOrEmpty(currentTypeOrGroupReference.name) && String.Equals(currentObjectTypeName, currentTypeOrGroupReference.name, StringComparison.OrdinalIgnoreCase)) { if (currentViewDefinition.mainControl.GetType() == formatType) { validViews.Append(currentViewDefinition.name); validViews.Append(separator); } else if (String.Equals(viewName, currentViewDefinition.name, StringComparison.OrdinalIgnoreCase)) { string cmdletFormatName = null; if (currentViewDefinition.mainControl is TableControlBody) { cmdletFormatName = "Format-Table"; } else if (currentViewDefinition.mainControl is ListControlBody) { cmdletFormatName = "Format-List"; } else if (currentViewDefinition.mainControl is WideControlBody) { cmdletFormatName = "Format-Wide"; } else if (currentViewDefinition.mainControl is ComplexControlBody) { cmdletFormatName = "Format-Custom"; } if (validViewFormats.Length == 0) { string suggestValidViewNamePrefix = StringUtil.Format(FormatAndOut_format_xxx.SuggestValidViewNamePrefix); validViewFormats.Append(suggestValidViewNamePrefix); } else { validViewFormats.Append(", "); } validViewFormats.Append(cmdletFormatName); } } } } } } if (validViews.Length > 0) { validViews.Remove(validViews.Length - separator.Length, separator.Length); msg = StringUtil.Format(FormatAndOut_format_xxx.InvalidViewNameError, viewName, formatTypeName, validViews.ToString()); foundValidViews = true; } } if (!foundValidViews) { StringBuilder unKnowViewFormatStringBuilder = new StringBuilder(); if (validViewFormats.Length > 0) { //unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameErrorSuffix, viewName, formatTypeName)); unKnowViewFormatStringBuilder.Append(validViewFormats.ToString()); } else { unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName)); unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, formatTypeName, so.BaseObject.GetType())); } msg = unKnowViewFormatStringBuilder.ToString(); ; } ErrorRecord errorRecord = new ErrorRecord( new PipelineStoppedException(), "FormatViewNotFound", ErrorCategory.ObjectNotFound, viewName); errorRecord.ErrorDetails = new ErrorDetails(msg); errorContext.ThrowTerminatingError(errorRecord); }
/// <summary> /// helper to to add any pre-load intrinsics to the db /// </summary> /// <param name="db">db being initialized</param> private static void AddPreLoadIntrinsics(TypeInfoDataBase db) { // NOTE: nothing to add for the time being. Add here if needed. }
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; }
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(); } }
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; }
private static void AddPreLoadInstrinsics(TypeInfoDataBase db) { }
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; }
/// <summary> /// load the content of the ExtendedTypeDefinition instance into the db. /// Only support following view controls: /// TableControl /// ListControl /// WideControl /// CustomControl /// </summary> /// <param name="typeDefinition">ExtendedTypeDefinition instances to load from, cannot be null</param> /// <param name="db">instance of the database to load into</param> /// <param name="isForHelpOutput">true if the formatter is used for formatting help objects</param> private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db, bool isForHelpOutput) { if (typeDefinition == null) throw PSTraceSource.NewArgumentNullException("viewDefinition"); if (db == null) throw PSTraceSource.NewArgumentNullException("db"); int viewIndex = 0; foreach (FormatViewDefinition formatView in typeDefinition.FormatViewDefinition) { ViewDefinition view = LoadViewFromObjectModel(typeDefinition.TypeNames, formatView, viewIndex++); if (view != null) { ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from the 'FormatViewDefinition' at index {2} in 'ExtendedTypeDefinition' with type name {3}", ControlBase.GetControlShapeName(view.mainControl), view.name, viewIndex - 1, typeDefinition.TypeName)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); view.loadingInfo = this.LoadingInfo; view.isHelpFormatter = isForHelpOutput; } } }
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); }