Exemplo n.º 1
0
 internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable)
 {
     if (this.props != null)
     {
         CommandParameterDefinition definition;
         if (isTable)
         {
             definition = new FormatTableParameterDefinition();
         }
         else
         {
             definition = new FormatListParameterDefinition();
         }
         ParameterProcessor processor = new ParameterProcessor(definition);
         TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
         parameters.mshParameterList = processor.ProcessParameters(this.props, invocationContext);
     }
     if (!string.IsNullOrEmpty(base.View))
     {
         if (parameters.mshParameterList.Count != 0)
         {
             base.ReportCannotSpecifyViewAndProperty();
         }
         parameters.viewName = base.View;
     }
 }
Exemplo n.º 2
0
 internal override FormattingCommandLineParameters GetCommandLineParameters()
 {
     FormattingCommandLineParameters parameters = new FormattingCommandLineParameters();
     if (this.props != null)
     {
         ParameterProcessor processor = new ParameterProcessor(new FormatObjectParameterDefinition());
         TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
         parameters.mshParameterList = processor.ProcessParameters(this.props, invocationContext);
     }
     if (!string.IsNullOrEmpty(base.View))
     {
         if (parameters.mshParameterList.Count != 0)
         {
             base.ReportCannotSpecifyViewAndProperty();
         }
         parameters.viewName = base.View;
     }
     parameters.groupByParameter = base.ProcessGroupByParameter();
     parameters.forceFormattingAlsoOnOutOfBand = (bool) base.Force;
     if (this.showErrorsAsMessages.HasValue)
     {
         parameters.showErrorsAsMessages = base.showErrorsAsMessages;
     }
     if (this.showErrorsInFormattedOutput.HasValue)
     {
         parameters.showErrorsInFormattedOutput = base.showErrorsInFormattedOutput;
     }
     parameters.expansion = base.ProcessExpandParameter();
     ComplexSpecificParameters parameters2 = new ComplexSpecificParameters {
         maxDepth = this.depth
     };
     parameters.shapeParameters = parameters2;
     return parameters;
 }
Exemplo n.º 3
0
 internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
 {
     if (!originalParameterWasHashTable)
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     string str = val as string;
     if (!string.IsNullOrEmpty(str))
     {
         for (int i = 0; i < legalValues.Length; i++)
         {
             if (CommandParameterDefinition.FindPartialMatch(str, legalValues[i]))
             {
                 if (i == 0)
                 {
                     return 1;
                 }
                 if (i == 1)
                 {
                     return 2;
                 }
                 return 3;
             }
         }
     }
     this.ProcessIllegalValue(str, invocationContext);
     return null;
 }
Exemplo n.º 4
0
 internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, bool lineWrap, TerminatingErrorContext errorContext)
 {
     if (hostConsole == null)
     {
         throw PSTraceSource.NewArgumentNullException("hostConsole");
     }
     if (errorContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("errorContext");
     }
     this.console = hostConsole;
     this.errorContext = errorContext;
     if (paging)
     {
         tracer.WriteLine("paging is needed", new object[0]);
         string s = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt, new object[0]);
         this.prompt = new PromptHandler(s, this);
     }
     PSHostRawUserInterface rawUI = this.console.RawUI;
     if (rawUI != null)
     {
         tracer.WriteLine("there is a valid raw interface", new object[0]);
         this._displayCellsPSHost = new DisplayCellsPSHost(rawUI);
     }
     WriteLineHelper.WriteCallback wlc = new WriteLineHelper.WriteCallback(this.OnWriteLine);
     WriteLineHelper.WriteCallback wc = new WriteLineHelper.WriteCallback(this.OnWrite);
     if (this.forceNewLine)
     {
         this.writeLineHelper = new WriteLineHelper(lineWrap, wlc, null, this.DisplayCells);
     }
     else
     {
         this.writeLineHelper = new WriteLineHelper(lineWrap, wlc, wc, this.DisplayCells);
     }
 }
Exemplo n.º 5
0
 internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
 {
     if (val == null)
     {
         throw PSTraceSource.NewArgumentNullException("val");
     }
     ScriptBlock scriptBlock = val as ScriptBlock;
     if (scriptBlock != null)
     {
         return new MshExpression(scriptBlock);
     }
     string str = val as string;
     if (str != null)
     {
         if (string.IsNullOrEmpty(str))
         {
             this.ProcessEmptyStringError(originalParameterWasHashTable, invocationContext);
         }
         MshExpression expression2 = new MshExpression(str);
         if (this._noGlobbing && expression2.HasWildCardCharacters)
         {
             this.ProcessGlobbingCharactersError(originalParameterWasHashTable, str, invocationContext);
         }
         return expression2;
     }
     PSTraceSource.NewArgumentException("val");
     return null;
 }
Exemplo n.º 6
0
 internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorContext invocationContext)
 {
     if (string.IsNullOrEmpty(keyName))
     {
         PSTraceSource.NewArgumentNullException("keyName");
     }
     HashtableEntryDefinition matchingEntry = null;
     for (int i = 0; i < this.hashEntries.Count; i++)
     {
         if (this.hashEntries[i].IsKeyMatch(keyName))
         {
             if (matchingEntry == null)
             {
                 matchingEntry = this.hashEntries[i];
             }
             else
             {
                 ProcessAmbiguousKey(invocationContext, keyName, matchingEntry, this.hashEntries[i]);
             }
         }
     }
     if (matchingEntry != null)
     {
         return matchingEntry;
     }
     ProcessIllegalKey(invocationContext, keyName);
     return null;
 }
Exemplo n.º 7
0
 internal override void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters)
 {
     base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters);
     if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
     {
         _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl;
     }
 }
Exemplo n.º 8
0
 private void VerifyRange(int width, TerminatingErrorContext invocationContext)
 {
     if (width <= 0)
     {
         string msg = StringUtil.Format(FormatAndOut_MshParameter.OutOfRangeWidthValueError, width, base.KeyName);
         ParameterProcessor.ThrowParameterBindingException(invocationContext, "WidthOutOfRange", msg);
     }
 }
Exemplo n.º 9
0
 internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
 {
     if (!originalParameterWasHashTable)
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     return LanguagePrimitives.IsTrue(val);
 }
Exemplo n.º 10
0
 internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
 {
     if (!originalParameterWasHashTable)
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     this.VerifyRange((int) val, invocationContext);
     return null;
 }
Exemplo n.º 11
0
 internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List<ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext)
 {
     this.db = dataBase;
     this.loadingInfo = loadingInfo;
     this.expressionFactory = expressionFactory;
     this.controlDefinitionList = controlDefinitionList;
     this.errorManager = resultErrorManager;
     this.enumerationLimit = enumerationLimit;
     this.errorContext = errorContext;
 }
Exemplo n.º 12
0
        internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                                    PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
        {
            base.Initialize(errorContext, expressionFactory, so, db, parameters);
            if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view))
            {
                _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl;
            }

            this.inputParameters = parameters;
            SetUpActiveProperties(so);
        }
Exemplo n.º 13
0
        internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
                                            MshExpressionFactory mshExpressionFactory,
                                            PSObject so,
                                            TypeInfoDataBase db,
                                            FormattingCommandLineParameters formatParameters)
        {
            errorContext = terminatingErrorContext;
            expressionFactory = mshExpressionFactory;
            parameters = formatParameters;
            dataBaseInfo.db = db;

            InitializeHelper();
        }
Exemplo n.º 14
0
 internal MshParameter ProcessGroupByParameter()
 {
     if (this.groupByParameter != null)
     {
         TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
         List<MshParameter> list = new ParameterProcessor(new FormatGroupByParameterDefinition()).ProcessParameters(new object[] { this.groupByParameter }, invocationContext);
         if (list.Count != 0)
         {
             return list[0];
         }
     }
     return null;
 }
Exemplo n.º 15
0
        internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                                        PSObject so, TypeInfoDataBase db,
            FormattingCommandLineParameters parameters)
        {
            base.Initialize(errorContext, expressionFactory, so, db, parameters);

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

            List<MshParameter> rawMshParameterList = null;

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

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

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

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

            // we were unable to retrieve any properties, so we leave an empty list
            this.activeAssociationList = new List<MshResolvedExpressionParameterAssociation>();
        }
Exemplo n.º 16
0
 internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
 {
     if (!originalParameterWasHashTable)
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     string str = val as string;
     if (string.IsNullOrEmpty(str))
     {
         string msg = StringUtil.Format(FormatAndOut_MshParameter.EmptyFormatStringValueError, base.KeyName);
         ParameterProcessor.ThrowParameterBindingException(invocationContext, "FormatStringEmpty", msg);
     }
     return new FieldFormattingDirective { formatString = str };
 }
Exemplo n.º 17
0
 internal override FormattingCommandLineParameters GetCommandLineParameters()
 {
     FormattingCommandLineParameters parameters = new FormattingCommandLineParameters();
     if (this.prop != null)
     {
         ParameterProcessor processor = new ParameterProcessor(new FormatWideParameterDefinition());
         TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
         parameters.mshParameterList = processor.ProcessParameters(new object[] { this.prop }, invocationContext);
     }
     if (!string.IsNullOrEmpty(base.View))
     {
         if (parameters.mshParameterList.Count != 0)
         {
             base.ReportCannotSpecifyViewAndProperty();
         }
         parameters.viewName = base.View;
     }
     if ((this.autosize.HasValue && this.column.HasValue) && this.autosize.Value)
     {
         string message = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyAutosizeAndColumnsError, new object[0]);
         ErrorRecord errorRecord = new ErrorRecord(new InvalidDataException(), "FormatCannotSpecifyAutosizeAndColumns", ErrorCategory.InvalidArgument, null) {
             ErrorDetails = new ErrorDetails(message)
         };
         base.ThrowTerminatingError(errorRecord);
     }
     parameters.groupByParameter = base.ProcessGroupByParameter();
     parameters.forceFormattingAlsoOnOutOfBand = (bool) base.Force;
     if (this.showErrorsAsMessages.HasValue)
     {
         parameters.showErrorsAsMessages = base.showErrorsAsMessages;
     }
     if (this.showErrorsInFormattedOutput.HasValue)
     {
         parameters.showErrorsInFormattedOutput = base.showErrorsInFormattedOutput;
     }
     parameters.expansion = base.ProcessExpandParameter();
     if (this.autosize.HasValue)
     {
         parameters.autosize = new bool?(this.autosize.Value);
     }
     WideSpecificParameters parameters2 = new WideSpecificParameters();
     parameters.shapeParameters = parameters2;
     if (this.column.HasValue)
     {
         parameters2.columns = new int?(this.column.Value);
     }
     return parameters;
 }
Exemplo n.º 18
0
 private void ProcessEmptyStringError(bool originalParameterWasHashTable, TerminatingErrorContext invocationContext)
 {
     string str;
     string str2;
     if (originalParameterWasHashTable)
     {
         str = StringUtil.Format(FormatAndOut_MshParameter.MshExEmptyStringHashError, base.KeyName);
         str2 = "ExpressionEmptyString1";
     }
     else
     {
         str = StringUtil.Format(FormatAndOut_MshParameter.MshExEmptyStringError, new object[0]);
         str2 = "ExpressionEmptyString2";
     }
     ParameterProcessor.ThrowParameterBindingException(invocationContext, str2, str);
 }
Exemplo n.º 19
0
 private void ProcessGlobbingCharactersError(bool originalParameterWasHashTable, string expression, TerminatingErrorContext invocationContext)
 {
     string str;
     string str2;
     if (originalParameterWasHashTable)
     {
         str = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingHashError, base.KeyName, expression);
         str2 = "ExpressionGlobbing1";
     }
     else
     {
         str = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingStringError, expression);
         str2 = "ExpressionGlobbing2";
     }
     ParameterProcessor.ThrowParameterBindingException(invocationContext, str2, str);
 }
Exemplo n.º 20
0
 private static void ProcessIllegalHashTableKeyValue(TerminatingErrorContext invocationContext, string key, Type actualType, Type[] allowedTypes)
 {
     string str;
     string str2;
     if (allowedTypes.Length > 1)
     {
         string str3 = CatenateTypeArray(allowedTypes);
         str = StringUtil.Format(FormatAndOut_MshParameter.IllegalTypeMultiError, new object[] { key, actualType.FullName, str3 });
         str2 = "DictionaryKeyIllegalValue1";
     }
     else
     {
         str = StringUtil.Format(FormatAndOut_MshParameter.IllegalTypeSingleError, new object[] { key, actualType.FullName, allowedTypes[0] });
         str2 = "DictionaryKeyIllegalValue2";
     }
     ThrowParameterBindingException(invocationContext, str2, str);
 }
Exemplo n.º 21
0
        internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
                                        MshExpressionFactory mshExpressionFactory,
                                        TypeInfoDataBase db,
                                        ViewDefinition view,
                                        FormattingCommandLineParameters formatParameters)
        {
            Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null");
            Diagnostics.Assert(db != null, "db cannot be null");
            Diagnostics.Assert(view != null, "view cannot be null");

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

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

            InitializeHelper();
        }
Exemplo n.º 22
0
 internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors)
 {
     ViewGenerator generator;
     errors = null;
     ConsolidatedString internalTypeNames = so.InternalTypeNames;
     ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, internalTypeNames);
     if (view != null)
     {
         if (view.mainControl is ComplexControlBody)
         {
             generator = new ComplexViewGenerator();
         }
         else
         {
             generator = new ListViewGenerator();
         }
         generator.Initialize(errorContext, expressionFactory, db, view, null);
     }
     else
     {
         if (DefaultScalarTypes.IsTypeInList(internalTypeNames) || IsPropertyLessObject(so))
         {
             return GenerateOutOfBandObjectAsToString(so);
         }
         if (!useToStringFallback)
         {
             return null;
         }
         if (new MshExpression("*").ResolveNames(so).Count <= 0)
         {
             return null;
         }
         generator = new ListViewGenerator();
         generator.Initialize(errorContext, expressionFactory, so, db, null);
     }
     FormatEntryData data = generator.GeneratePayload(so, enumerationLimit);
     data.outOfBand = true;
     data.SetStreamTypeFromPSObject(so);
     errors = generator.ErrorManager.DrainFailedResultList();
     return data;
 }
Exemplo n.º 23
0
        /// <exception cref="ArgumentException"></exception>
        private void VerifyAndNormalizeParameter(MshParameter parameter,
                                                 TerminatingErrorContext invocationContext,
                                                 bool originalParameterWasHashTable)
        {
            for (int k = 0; k < _paramDef.hashEntries.Count; k++)
            {
                if (parameter.hash.ContainsKey(_paramDef.hashEntries[k].KeyName))
                {
                    // we have a key, just do some post processing normalization
                    // retrieve the value
                    object val    = parameter.hash[_paramDef.hashEntries[k].KeyName];
                    object newVal = _paramDef.hashEntries[k].Verify(val, invocationContext, originalParameterWasHashTable);

                    if (newVal != null)
                    {
                        // if a new value is provided, we need to update the hash entry
                        parameter.hash[_paramDef.hashEntries[k].KeyName] = newVal;
                    }
                }
                else
                {
                    // we do not have the key, we might want to have a default value
                    object defaultValue = _paramDef.hashEntries[k].ComputeDefaultValue();

                    if (defaultValue != AutomationNull.Value)
                    {
                        // we have a default value, add it
                        parameter.hash[_paramDef.hashEntries[k].KeyName] = defaultValue;
                    }
                    else if (_paramDef.hashEntries[k].Mandatory)
                    {
                        // no default value and mandatory: we cannot proceed
                        ProcessMissingMandatoryKey(invocationContext, _paramDef.hashEntries[k].KeyName);
                    }
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// for a key name, verify it is a legal entry:
        ///     1. it must match (partial match allowed)
        ///     2. it must be unambiguous (if partial match)
        /// If an error condition occurs, an exception will be thrown
        /// </summary>
        /// <param name="keyName">key to verify</param>
        /// <param name="invocationContext">invocation context for error reporting</param>
        /// <returns>matching hash table entry</returns>
        /// <exception cref="ArgumentException"></exception>
        internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorContext invocationContext)
        {
            if (string.IsNullOrEmpty(keyName))
            {
                PSTraceSource.NewArgumentNullException("keyName");
            }

            HashtableEntryDefinition matchingEntry = null;

            for (int k = 0; k < this.hashEntries.Count; k++)
            {
                if (this.hashEntries[k].IsKeyMatch(keyName))
                {
                    // we have a match
                    if (matchingEntry == null)
                    {
                        // this is the first match, we save the entry
                        // and we keep going for ambiguity check
                        matchingEntry = this.hashEntries[k];
                    }
                    else
                    {
                        // we already had a match, we have an ambiguous key
                        ProcessAmbiguousKey(invocationContext, keyName, matchingEntry, this.hashEntries[k]);
                    }
                }
            }

            if (matchingEntry != null)
            {
                // we found an unambiguous match
                return(matchingEntry);
            }
            // we did not have a match
            ProcessIllegalKey(invocationContext, keyName);
            return(null);
        }
Exemplo n.º 25
0
        internal override FormattingCommandLineParameters GetCommandLineParameters()
        {
            FormattingCommandLineParameters parameters = new FormattingCommandLineParameters();

            if (_props != null)
            {
                ParameterProcessor processor = new ParameterProcessor(new FormatObjectParameterDefinition());
                TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
                parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext);
            }

            if (!string.IsNullOrEmpty(this.View))
            {
                // we have a view command line switch
                if (parameters.mshParameterList.Count != 0)
                {
                    ReportCannotSpecifyViewAndProperty();
                }
                parameters.viewName = this.View;
            }

            parameters.groupByParameter = this.ProcessGroupByParameter();
            parameters.forceFormattingAlsoOnOutOfBand = this.Force;
            if (this.showErrorsAsMessages.HasValue)
                parameters.showErrorsAsMessages = this.showErrorsAsMessages;
            if (this.showErrorsInFormattedOutput.HasValue)
                parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput;

            parameters.expansion = ProcessExpandParameter();

            ComplexSpecificParameters csp = new ComplexSpecificParameters();
            csp.maxDepth = _depth;
            parameters.shapeParameters = csp;

            return parameters;
        }
Exemplo n.º 26
0
        internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, bool lineWrap, TerminatingErrorContext errorContext)
        {
            if (hostConsole == null)
            {
                throw PSTraceSource.NewArgumentNullException("hostConsole");
            }
            if (errorContext == null)
            {
                throw PSTraceSource.NewArgumentNullException("errorContext");
            }
            this.console      = hostConsole;
            this.errorContext = errorContext;
            if (paging)
            {
                tracer.WriteLine("paging is needed", new object[0]);
                string s = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt, new object[0]);
                this.prompt = new PromptHandler(s, this);
            }
            PSHostRawUserInterface rawUI = this.console.RawUI;

            if (rawUI != null)
            {
                tracer.WriteLine("there is a valid raw interface", new object[0]);
                this._displayCellsPSHost = new DisplayCellsPSHost(rawUI);
            }
            WriteLineHelper.WriteCallback wlc = new WriteLineHelper.WriteCallback(this.OnWriteLine);
            WriteLineHelper.WriteCallback wc  = new WriteLineHelper.WriteCallback(this.OnWrite);
            if (this.forceNewLine)
            {
                this.writeLineHelper = new WriteLineHelper(lineWrap, wlc, null, this.DisplayCells);
            }
            else
            {
                this.writeLineHelper = new WriteLineHelper(lineWrap, wlc, wc, this.DisplayCells);
            }
        }
Exemplo n.º 27
0
        /// <exception cref="ArgumentException"></exception>
        private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invocationContext)
        {
            // full blown hash, need to:
            // 1. verify names(keys) and expand names if there are partial matches
            // 2. verify value types
            Hashtable retVal = new Hashtable();

            foreach (DictionaryEntry e in hash)
            {
                if (e.Key is null)
                {
                    ProcessNullHashTableKey(invocationContext);
                }

                string currentStringKey = e.Key as string;
                if (currentStringKey is null)
                {
                    ProcessNonStringHashTableKey(invocationContext, e.Key);
                }

                // find a match for the key
                HashtableEntryDefinition def = _paramDef.MatchEntry(currentStringKey, invocationContext);
                if (retVal.Contains(def.KeyName))
                {
                    // duplicate key error
                    ProcessDuplicateHashTableKey(invocationContext, currentStringKey, def.KeyName);
                }

                // now the key is verified, need to check the type
                bool matchType = false;

                if (def.AllowedTypes is null || def.AllowedTypes.Length == 0)
                {
                    // we match on any type, it will be up to the entry to further check
                    matchType = true;
                }
Exemplo n.º 28
0
        internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable)
        {
            if (Property != null)
            {
                CommandParameterDefinition def;

                if (isTable)
                    def = new FormatTableParameterDefinition();
                else
                    def = new FormatListParameterDefinition();
                ParameterProcessor processor = new ParameterProcessor(def);
                TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);

                parameters.mshParameterList = processor.ProcessParameters(Property, invocationContext);
            }

            if (!string.IsNullOrEmpty(this.View))
            {
                // we have a view command line switch
                if (parameters.mshParameterList.Count != 0)
                {
                    ReportCannotSpecifyViewAndProperty();
                }
                parameters.viewName = this.View;
            }
        }
Exemplo n.º 29
0
 internal void CreateTerminatingErrorContext()
 {
     TerminatingErrorContext = new TerminatingErrorContext(this.OuterCmdlet());
 }
Exemplo n.º 30
0
        private void ProcessGlobbingCharactersError(bool originalParameterWasHashTable, string expression, TerminatingErrorContext invocationContext)
        {
            string msg;
            string errorID;

            if (originalParameterWasHashTable)
            {
                msg = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingHashError,
                                        this.KeyName, expression);
                errorID = "ExpressionGlobbing1";
            }
            else
            {
                msg = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingStringError,
                                        expression);
                errorID = "ExpressionGlobbing2";
            }

            ParameterProcessor.ThrowParameterBindingException(invocationContext, errorID, msg);
        }
Exemplo n.º 31
0
        private void ProcessIllegalValue(string s, TerminatingErrorContext invocationContext)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalAlignmentValueError, new object[] { s, base.KeyName, ParameterProcessor.CatenateStringArray(legalValues) });

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "AlignmentIllegalValue", msg);
        }
Exemplo n.º 32
0
        internal void Initialize(TerminatingErrorContext errorContext,
                                    MshExpressionFactory expressionFactory,
                                    TypeInfoDataBase db,
                                    PSObject so,
                                    FormatShape shape,
                                    FormattingCommandLineParameters parameters)
        {
            ViewDefinition view = null;
            const string findViewType = "FINDING VIEW  TYPE: {0}";
            const string findViewShapeType = "FINDING VIEW {0} TYPE: {1}";
            const string findViewNameType = "FINDING VIEW NAME: {0}  TYPE: {1}";
            const string viewFound = "An applicable view has been found";
            const string viewNotFound = "No applicable view has been found";
            try
            {
                DisplayDataQuery.SetTracer(s_formatViewBindingTracer);

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

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

                    return;
                }

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

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

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

                    return;
                }
                s_formatViewBindingTracer.WriteLine(viewNotFound);
                // we just select properties out of the object itself
                _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
                PrepareViewForRemoteObjects(ViewGenerator, so);
            }
            finally
            {
                DisplayDataQuery.ResetTracer();
            }
        }
Exemplo n.º 33
0
        private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so,
                                    TerminatingErrorContext errorContext,
                                    MshExpressionFactory expressionFactory,
                                    TypeInfoDataBase db,
                                    FormattingCommandLineParameters parameters)
        {
            // use some heuristics to determine the shape if none is specified
            if (shape == FormatShape.Undefined && parameters == null)
            {
                // check first if we have a known shape for a type
                var typeNames = so.InternalTypeNames;
                shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames);

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

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

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

            viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters);
            return viewGenerator;
        }
Exemplo n.º 34
0
        private static void ProcessMissingMandatoryKey(TerminatingErrorContext invocationContext, string keyName)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyMandatoryEntryError, keyName);

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyMandatoryEntry", msg);
        }
Exemplo n.º 35
0
        private static void ProcessNullHashTableKey(TerminatingErrorContext invocationContext)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNullError);

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNull", msg);
        }
Exemplo n.º 36
0
 internal FormatObjectDeserializer(TerminatingErrorContext errorContext)
 {
     TerminatingErrorContext = errorContext;
 }
Exemplo n.º 37
0
        private void ProcessGlobbingCharactersError(bool originalParameterWasHashTable, string expression, TerminatingErrorContext invocationContext)
        {
            string str;
            string str2;

            if (originalParameterWasHashTable)
            {
                str  = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingHashError, base.KeyName, expression);
                str2 = "ExpressionGlobbing1";
            }
            else
            {
                str  = StringUtil.Format(FormatAndOut_MshParameter.MshExGlobbingStringError, expression);
                str2 = "ExpressionGlobbing2";
            }
            ParameterProcessor.ThrowParameterBindingException(invocationContext, str2, str);
        }
Exemplo n.º 38
0
        private static void ProcessAmbiguousKey(TerminatingErrorContext invocationContext, string keyName, HashtableEntryDefinition matchingEntry, HashtableEntryDefinition currentEntry)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.AmbiguousKeyError, new object[] { keyName, matchingEntry.KeyName, currentEntry.KeyName });

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyAmbiguous", msg);
        }
Exemplo n.º 39
0
 internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List <ControlDefinition> controlDefinitionList, FormatErrorManager resultErrorManager, int enumerationLimit, TerminatingErrorContext errorContext)
 {
     this.db                    = dataBase;
     this.loadingInfo           = loadingInfo;
     this.expressionFactory     = expressionFactory;
     this.controlDefinitionList = controlDefinitionList;
     this.errorManager          = resultErrorManager;
     this.enumerationLimit      = enumerationLimit;
     this.errorContext          = errorContext;
 }
Exemplo n.º 40
0
        /// <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);
        }
Exemplo n.º 41
0
        private static ViewGenerator SelectViewGeneratorFromViewDefinition(
                                        TerminatingErrorContext errorContext,
                                        MshExpressionFactory expressionFactory,
                                        TypeInfoDataBase db,
                                        ViewDefinition view,
                                        FormattingCommandLineParameters parameters)
        {
            ViewGenerator viewGenerator = null;
            if (view.mainControl is TableControlBody)
            {
                viewGenerator = new TableViewGenerator();
            }
            else if (view.mainControl is ListControlBody)
            {
                viewGenerator = new ListViewGenerator();
            }
            else if (view.mainControl is WideControlBody)
            {
                viewGenerator = new WideViewGenerator();
            }
            else if (view.mainControl is ComplexControlBody)
            {
                viewGenerator = new ComplexViewGenerator();
            }

            Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");
            viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters);
            return viewGenerator;
        }
Exemplo n.º 42
0
 internal override void Initialize(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory,
                                   PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
 {
     base.Initialize(errorContext, expressionFactory, so, db, parameters);
     this.inputParameters = parameters;
 }
Exemplo n.º 43
0
        internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                    TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors)
        {
            errors = null;

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

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

                if (!useToStringFallback)
                {
                    return null;
                }

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

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

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

            errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList();

            return fed;
        }
Exemplo n.º 44
0
        /// <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);
        }
Exemplo n.º 45
0
 internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory,
                         PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters)
 {
     base.Initialize(errorContext, expressionFactory, so, db, parameters);
     this.inputParameters = parameters;
 }
Exemplo n.º 46
0
        private static void ProcessIllegalKey(TerminatingErrorContext invocationContext, string keyName)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalKeyError, keyName);

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyIllegal", msg);
        }
Exemplo n.º 47
0
        internal void Initialize(TerminatingErrorContext errorContext,
                                 MshExpressionFactory expressionFactory,
                                 TypeInfoDataBase db,
                                 PSObject so,
                                 FormatShape shape,
                                 FormattingCommandLineParameters parameters)
        {
            ViewDefinition view              = null;
            const string   findViewType      = "FINDING VIEW TYPE: {0}";
            const string   findViewShapeType = "FINDING VIEW {0} TYPE: {1}";
            const string   findViewNameType  = "FINDING VIEW NAME: {0} TYPE: {1}";
            const string   viewFound         = "An applicable view has been found";
            const string   viewNotFound      = "No applicable view has been found";

            try
            {
                DisplayDataQuery.SetTracer(s_formatViewBindingTracer);

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

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

                    return;
                }

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

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

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

                    return;
                }
                s_formatViewBindingTracer.WriteLine(viewNotFound);
                // we just select properties out of the object itself
                _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
                PrepareViewForRemoteObjects(ViewGenerator, so);
            }
            finally
            {
                DisplayDataQuery.ResetTracer();
            }
        }
Exemplo n.º 48
0
        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);
        }
Exemplo n.º 49
0
        /// <exception cref="ArgumentException"></exception>
        private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invocationContext)
        {
            // full blown hash, need to:
            // 1. verify names(keys) and expand names if there are partial matches
            // 2. verify value types
            Hashtable retVal = new Hashtable();

            foreach (DictionaryEntry e in hash)
            {
                if (e.Key == null)
                {
                    ProcessNullHashTableKey(invocationContext);
                }

                string currentStringKey = e.Key as string;
                if (currentStringKey == null)
                {
                    ProcessNonStringHashTableKey(invocationContext, e.Key);
                }

                // find a match for the key
                HashtableEntryDefinition def = _paramDef.MatchEntry(currentStringKey, invocationContext);
                if (retVal.Contains(def.KeyName))
                {
                    // duplicate key error
                    ProcessDuplicateHashTableKey(invocationContext, currentStringKey, def.KeyName);
                }

                // now the key is verified, need to check the type
                bool matchType = false;

                if (def.AllowedTypes == null || def.AllowedTypes.Length == 0)
                {
                    // we match on any type, it will be up to the entry to further check
                    matchType = true;
                }
                else
                {
                    for (int t = 0; t < def.AllowedTypes.Length; t++)
                    {
                        if (e.Value == null)
                        {
                            ProcessMissingKeyValue(invocationContext, currentStringKey);
                        }

                        if (def.AllowedTypes[t].IsAssignableFrom(e.Value.GetType()))
                        {
                            matchType = true;
                            break;
                        }
                    }
                }

                if (!matchType)
                {
                    // bad type error
                    ProcessIllegalHashTableKeyValue(invocationContext, currentStringKey, e.Value.GetType(), def.AllowedTypes);
                }

                retVal.Add(def.KeyName, e.Value);
            }

            return(retVal);
        }
Exemplo n.º 50
0
        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();
            }
        }
Exemplo n.º 51
0
        private static void ProcessNonStringHashTableKey(TerminatingErrorContext invocationContext, object key)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNonStringError, key.GetType().Name);

            ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNonString", msg);
        }
Exemplo n.º 52
0
        private static void ProcessDuplicateHashTableKey(TerminatingErrorContext invocationContext, string duplicateKey, string existingKey)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.DuplicateKeyError, duplicateKey, existingKey);

            ThrowParameterBindingException(invocationContext, "DictionaryKeyDuplicate", msg);
        }
Exemplo n.º 53
0
 internal virtual object Verify(object val,
                                TerminatingErrorContext invocationContext,
                                bool originalParameterWasHashTable)
 {
     return(null);
 }
Exemplo n.º 54
0
 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);
 }
Exemplo n.º 55
0
 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);
 }
Exemplo n.º 56
0
        private static void ProcessMissingKeyValue(TerminatingErrorContext invocationContext, string keyName)
        {
            string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyValueError, keyName);

            ThrowParameterBindingException(invocationContext, "DictionaryKeyMissingValue", msg);
        }