/// <summary> /// Retrieve the display name. It looks for a well known property and, /// if not found, it uses some heuristics to get a "close" match. /// </summary> /// <param name="target">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>Resolved PSPropertyExpression; null if no match was found.</returns> internal static PSPropertyExpression GetDisplayNameExpression(PSObject target, PSPropertyExpressionFactory expressionFactory) { // first try to get the expression from the object (types.ps1xml data) PSPropertyExpression expressionFromObject = GetDefaultNameExpression(target); if (expressionFromObject != null) { return(expressionFromObject); } // we failed the default display name, let's try some well known names // trying to get something potentially useful string[] knownPatterns = new string[] { "name", "id", "key", "*key", "*name", "*id", }; // go over the patterns, looking for the first match foreach (string pattern in knownPatterns) { PSPropertyExpression ex = new PSPropertyExpression(pattern); List <PSPropertyExpression> exprList = ex.ResolveNames(target); while ((exprList.Count > 0) && ( exprList[0].ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase))) { exprList.RemoveAt(0); } if (exprList.Count == 0) { continue; } // if more than one match, just return the first one return(exprList[0]); } // we did not find anything return(null); }
internal ComplexViewObjectBrowser(FormatErrorManager resultErrorManager, PSPropertyExpressionFactory mshExpressionFactory, int enumerationLimit) { _errorManager = resultErrorManager; _expressionFactory = mshExpressionFactory; _enumerationLimit = enumerationLimit; }
/// <summary> /// Helper to convert an PSObject into a string /// It takes into account enumerations (use display name) /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Stores errors during string conversion.</param> /// <returns>String representation.</returns> internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) { return(string.Empty); } try { IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { StringBuilder sb = new StringBuilder(); sb.Append('{'); bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator <object> be = enumerator as IBlockingEnumerator <object>; if (be != null) { while (be.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) { first = false; } } } else { foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(x, expressionFactory)); if (first) { first = false; } } } } sb.Append('}'); return(sb.ToString()); } // take care of the case there is no base object return(so.ToString()); } catch (Exception e) when(e is ExtendedTypeSystemException || e is InvalidOperationException) { // These exceptions are being caught and handled by returning an empty string when // the object cannot be stringified due to ETS or an instance in the collection has been modified s_tracer.TraceWarning($"SmartToString method: Exception during conversion to string, emitting empty string: {e.Message}"); if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } return(string.Empty); } }
/// <summary> /// Helper to convert an PSObject into a string /// It takes into account enumerations (use display name) /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Stores errors during string conversion.</param> /// <returns>String representation.</returns> internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) { return(string.Empty); } try { IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { StringBuilder sb = new StringBuilder(); sb.Append("{"); bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator <object> be = enumerator as IBlockingEnumerator <object>; if (be != null) { while (be.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) { first = false; } } } else { foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(x, expressionFactory)); if (first) { first = false; } } } } sb.Append("}"); return(sb.ToString()); } // take care of the case there is no base object return(so.ToString()); } catch (ExtendedTypeSystemException e) { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } return(string.Empty); } }
internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; }
internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) { _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } }
/// <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); }
internal void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory 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 static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, PSPropertyExpressionFactory 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) || !HasNonRemotingProperties(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 PSPropertyExpression("*").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.writeStream = so.WriteStream; errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList(); return(fed); }
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 static List <MshResolvedExpressionParameterAssociation> SetupActiveProperties(List <MshParameter> rawMshParameterList, PSObject target, PSPropertyExpressionFactory 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 PSPropertyExpression(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); }
internal static List <MshResolvedExpressionParameterAssociation> ExpandDefaultPropertySet(PSObject target, PSPropertyExpressionFactory expressionFactory) { List <MshResolvedExpressionParameterAssociation> retVal = new List <MshResolvedExpressionParameterAssociation>(); List <PSPropertyExpression> expandedExpressionList = PSObjectHelper.GetDefaultPropertySet(target); foreach (PSPropertyExpression ex in expandedExpressionList) { retVal.Add(new MshResolvedExpressionParameterAssociation(null, ex)); } return(retVal); }