/// <summary>
        /// Get suggestion text from suggestion scriptblock with arguments.
        /// </summary>
        private static string GetSuggestionText(Object suggestion, object[] suggestionArgs, PSModuleInfo invocationModule)
        {
            if (suggestion is ScriptBlock)
            {
                ScriptBlock suggestionScript = (ScriptBlock)suggestion;

                object result = null;
                try
                {
                    result = invocationModule.Invoke(suggestionScript, suggestionArgs);
                }
                catch (Exception)
                {
                    // Catch-all OK. This is a third-party call-out.
                    return(String.Empty);
                }

                return((string)LanguagePrimitives.ConvertTo(result, typeof(string), CultureInfo.CurrentCulture));
            }
            else
            {
                return((string)LanguagePrimitives.ConvertTo(suggestion, typeof(string), CultureInfo.CurrentCulture));
            }
        }
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException ex)
            {
            }
            catch (ProviderNotFoundException ex)
            {
            }
            catch (DriveNotFoundException ex)
            {
            }
            catch (ProviderInvocationException ex)
            {
            }
            Command command = (Command)null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                command = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                command = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (command == null)
            {
                return;
            }
            HostInfo hostInfo = this.remoteHost.HostInfo;

            command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            PowerShell powershell = PowerShell.Create();

            powershell.AddCommand(command).AddCommand("out-default");
            IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, (PowerShell)null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start();

            powershell.EndInvoke(asyncResult);
            ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable;

            if (dollarErrorVariable.Count > 0)
            {
                string str = (dollarErrorVariable[0] as ErrorRecord).ToString();
                throw ServerRunspacePoolDriver.tracer.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), (object)str);
            }
            if (this.localRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opening)
            {
                return;
            }
            object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");

            if (valueToConvert == null)
            {
                return;
            }
            this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, (IFormatProvider)CultureInfo.InvariantCulture, (TypeTable)null);
        }
        private static T ConvertPropertyValueTo <T>(string propertyName, object propertyValue)
        {
            using (RemotingDecoder._trace.TraceMethod())
            {
                if (propertyName == null)
                {
                    throw RemotingDecoder._trace.NewArgumentNullException(nameof(propertyName));
                }
                if (typeof(T).IsEnum)
                {
                    if (propertyValue is string)
                    {
                        try
                        {
                            return((T)Enum.Parse(typeof(T), (string)propertyValue, true));
                        }
                        catch (ArgumentException ex)
                        {
                            throw new PSRemotingDataStructureException(PSRemotingErrorId.CantCastPropertyToExpectedType, new object[3]
                            {
                                (object)propertyName,
                                (object)typeof(T).FullName,
                                (object)propertyValue.GetType().FullName
                            });
                        }
                    }
                    else
                    {
                        try
                        {
                            Type underlyingType = Enum.GetUnderlyingType(typeof(T));
                            return((T)LanguagePrimitives.ConvertTo(propertyValue, underlyingType, (IFormatProvider)CultureInfo.InvariantCulture));
                        }
                        catch (InvalidCastException ex)
                        {
                            throw new PSRemotingDataStructureException(PSRemotingErrorId.CantCastPropertyToExpectedType, new object[3]
                            {
                                (object)propertyName,
                                (object)typeof(T).FullName,
                                (object)propertyValue.GetType().FullName
                            });
                        }
                    }
                }
                else
                {
                    if (typeof(T).Equals(typeof(PSObject)))
                    {
                        return(propertyValue == null ? default(T) : (T)PSObject.AsPSObject(propertyValue));
                    }
                    switch (propertyValue)
                    {
                    case null:
                        if (!typeof(T).IsValueType)
                        {
                            return(default(T));
                        }
                        if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                        {
                            return(default(T));
                        }
                        throw new PSRemotingDataStructureException(PSRemotingErrorId.CantCastPropertyToExpectedType, new object[3]
                        {
                            (object)propertyName,
                            (object)typeof(T).FullName,
                            propertyValue != null ? (object)propertyValue.GetType().FullName : (object)"null"
                        });

                    case T obj:
                        return(obj);

                    case PSObject _:
                        PSObject psObject = (PSObject)propertyValue;
                        return(RemotingDecoder.ConvertPropertyValueTo <T>(propertyName, psObject.BaseObject));

                    case Hashtable _:
                        if (typeof(T).Equals(typeof(PSPrimitiveDictionary)))
                        {
                            try
                            {
                                return((T) new PSPrimitiveDictionary((Hashtable)propertyValue));
                            }
                            catch (ArgumentException ex)
                            {
                                throw new PSRemotingDataStructureException(PSRemotingErrorId.CantCastPropertyToExpectedType, new object[3]
                                {
                                    (object)propertyName,
                                    (object)typeof(T).FullName,
                                    propertyValue != null ? (object)propertyValue.GetType().FullName : (object)"null"
                                });
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    throw new PSRemotingDataStructureException(PSRemotingErrorId.CantCastPropertyToExpectedType, new object[3]
                    {
                        (object)propertyName,
                        (object)typeof(T).FullName,
                        (object)propertyValue.GetType().FullName
                    });
                }
            }
        }
Exemple #4
0
        internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp)
        {
            // this object knows Maml format...
            // So retrieve Uri information as per the format..
            if ((commandFullHelp == null) ||
                (commandFullHelp.Properties["relatedLinks"] == null) ||
                (commandFullHelp.Properties["relatedLinks"].Value == null))
            {
                // return the default..
                return(null);
            }

            PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value);

            if (relatedLinks.Properties["navigationLink"] == null)
            {
                return(null);
            }

            object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo(
                relatedLinks.Properties["navigationLink"].Value,
                typeof(object[]),
                CultureInfo.InvariantCulture);
            foreach (object navigationLinkAsObject in navigationLinks)
            {
                if (navigationLinkAsObject == null)
                {
                    continue;
                }

                PSObject       navigationLink = PSObject.AsPSObject(navigationLinkAsObject);
                PSNoteProperty uriNP          = navigationLink.Properties["uri"] as PSNoteProperty;
                if (null != uriNP)
                {
                    string uriString = string.Empty;
                    LanguagePrimitives.TryConvertTo <string>(uriNP.Value, CultureInfo.InvariantCulture, out uriString);
                    if (!string.IsNullOrEmpty(uriString))
                    {
                        if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
                        {
                            // WinBlue: 545315 Online help links are broken with localized help
                            // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (möglicherwei se auf Englisch)
                            // Split the string based on <s> (space). We decided to go with this approach as
                            // UX localization authors use spaces. Correctly extracting only the wellformed URI
                            // is out-of-scope for this fix.
                            string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space);
                            uriString = tempUriSplitArray[0];
                        }

                        try
                        {
                            return(new System.Uri(uriString));
                            // return only the first Uri (ignore other uris)
                        }
                        catch (UriFormatException)
                        {
                            throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, uriString);
                        }
                    }
                }
            }

            return(null);
        }
Exemple #5
0
 public string ToString(string format, IFormatProvider formatProvider)
 {
     return((string)LanguagePrimitives.ConvertTo(ImmediateBaseObject, typeof(string), formatProvider));
 }
        internal static ArrayList GetSuggestion(HistoryInfo lastHistory, Object lastError, ArrayList errorList)
        {
            ArrayList returnSuggestions = new ArrayList();

            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory);
            invocationModule.SessionState.PSVariable.Set("lastError", lastError);

            int initialErrorCount = 0;

            // Go through all of the suggestions
            foreach (Hashtable suggestion in s_suggestions)
            {
                initialErrorCount = errorList.Count;

                // Make sure the rule is enabled
                if (!LanguagePrimitives.IsTrue(suggestion["Enabled"]))
                {
                    continue;
                }

                SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(
                    suggestion["MatchType"],
                    typeof(SuggestionMatchType),
                    CultureInfo.InvariantCulture);

                // If this is a dynamic match, evaluate the ScriptBlock
                if (matchType == SuggestionMatchType.Dynamic)
                {
                    object result = null;

                    ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock;
                    if (evaluator == null)
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.RuleMustBeScriptBlock, "Rule");
                    }

                    try
                    {
                        result = invocationModule.Invoke(evaluator, null);
                    }
                    catch (Exception)
                    {
                        // Catch-all OK. This is a third-party call-out.
                        suggestion["Enabled"] = false;
                        continue;
                    }

                    // If it returned results, evaluate its suggestion
                    if (LanguagePrimitives.IsTrue(result))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!String.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = String.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }
                else
                {
                    string matchText = String.Empty;

                    // Otherwise, this is a Regex match against the
                    // command or error
                    if (matchType == SuggestionMatchType.Command)
                    {
                        matchText = lastHistory.CommandLine;
                    }
                    else if (matchType == SuggestionMatchType.Error)
                    {
                        if (lastError != null)
                        {
                            Exception lastException = lastError as Exception;
                            if (lastException != null)
                            {
                                matchText = lastException.Message;
                            }
                            else
                            {
                                matchText = lastError.ToString();
                            }
                        }
                    }
                    else
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.InvalidMatchType,
                                  "MatchType");
                    }

                    // If the text matches, evaluate the suggestion
                    if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!String.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = String.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }

                // If the rule generated an error, disable it
                if (errorList.Count != initialErrorCount)
                {
                    suggestion["Enabled"] = false;
                }
            }

            return(returnSuggestions);
        }
        private static ConcurrentDictionary <string, CommandTypes> AnalyzeManifestModule(string modulePath, ExecutionContext context, DateTime lastWriteTime, bool etwEnabled)
        {
            ConcurrentDictionary <string, CommandTypes> result = null;

            try
            {
                var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
                if (moduleManifestProperties != null)
                {
                    Version version;
                    if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
                    {
                        var versionInManifest = LanguagePrimitives.ConvertTo <Version>(moduleManifestProperties["ModuleVersion"]);
                        if (version != versionInManifest)
                        {
                            ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
                            return(null);
                        }
                    }

                    result = new ConcurrentDictionary <string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);

                    var sawWildcard  = false;
                    var hadCmdlets   = AddPsd1EntryToResult(result, moduleManifestProperties["CmdletsToExport"], CommandTypes.Cmdlet, ref sawWildcard);
                    var hadFunctions = AddPsd1EntryToResult(result, moduleManifestProperties["FunctionsToExport"], CommandTypes.Function, ref sawWildcard);
                    var hadAliases   = AddPsd1EntryToResult(result, moduleManifestProperties["AliasesToExport"], CommandTypes.Alias, ref sawWildcard);

                    var analysisSucceeded = hadCmdlets && hadFunctions && hadAliases;

                    if (!analysisSucceeded && !sawWildcard && (hadCmdlets || hadFunctions))
                    {
                        // If we're missing CmdletsToExport, that might still be OK, but only if we have a script module.
                        // Likewise, if we're missing FunctionsToExport, that might be OK, but only if we have a binary module.

                        analysisSucceeded = !CheckModulesTypesInManifestAgainstExportedCommands(moduleManifestProperties, hadCmdlets, hadFunctions, hadAliases);
                    }

                    if (analysisSucceeded)
                    {
                        var moduleCacheEntry = new ModuleCacheEntry
                        {
                            ModulePath    = modulePath,
                            LastWriteTime = lastWriteTime,
                            Commands      = result,
                            TypesAnalyzed = false,
                            Types         = new ConcurrentDictionary <string, TypeAttributes>(1, 8, StringComparer.OrdinalIgnoreCase)
                        };
                        s_cacheData.Entries[modulePath] = moduleCacheEntry;
                    }
                    else
                    {
                        result = null;
                    }
                }
            }
            catch (Exception e)
            {
                if (etwEnabled)
                {
                    CommandDiscoveryEventSource.Log.ModuleManifestAnalysisException(modulePath, e.Message);
                }
                // Ignore the errors, proceed with the usual module analysis
                ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath);
            }

            if (etwEnabled)
            {
                CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null);
            }

            return(result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime));
        }
        protected override void SetValueImpl(int index, object value)
        {
            switch (index)
            {
            case 0:
                base.Item000 = LanguagePrimitives.ConvertTo <T0>(value);
                return;

            case 1:
                base.Item001 = LanguagePrimitives.ConvertTo <T1>(value);
                return;

            case 2:
                base.Item002 = LanguagePrimitives.ConvertTo <T2>(value);
                return;

            case 3:
                base.Item003 = LanguagePrimitives.ConvertTo <T3>(value);
                return;

            case 4:
                base.Item004 = LanguagePrimitives.ConvertTo <T4>(value);
                return;

            case 5:
                base.Item005 = LanguagePrimitives.ConvertTo <T5>(value);
                return;

            case 6:
                base.Item006 = LanguagePrimitives.ConvertTo <T6>(value);
                return;

            case 7:
                base.Item007 = LanguagePrimitives.ConvertTo <T7>(value);
                return;

            case 8:
                base.Item008 = LanguagePrimitives.ConvertTo <T8>(value);
                return;

            case 9:
                base.Item009 = LanguagePrimitives.ConvertTo <T9>(value);
                return;

            case 10:
                base.Item010 = LanguagePrimitives.ConvertTo <T10>(value);
                return;

            case 11:
                base.Item011 = LanguagePrimitives.ConvertTo <T11>(value);
                return;

            case 12:
                base.Item012 = LanguagePrimitives.ConvertTo <T12>(value);
                return;

            case 13:
                base.Item013 = LanguagePrimitives.ConvertTo <T13>(value);
                return;

            case 14:
                base.Item014 = LanguagePrimitives.ConvertTo <T14>(value);
                return;

            case 15:
                base.Item015 = LanguagePrimitives.ConvertTo <T15>(value);
                return;

            case 0x10:
                this.Item016 = LanguagePrimitives.ConvertTo <T16>(value);
                return;

            case 0x11:
                this.Item017 = LanguagePrimitives.ConvertTo <T17>(value);
                return;

            case 0x12:
                this.Item018 = LanguagePrimitives.ConvertTo <T18>(value);
                return;

            case 0x13:
                this.Item019 = LanguagePrimitives.ConvertTo <T19>(value);
                return;

            case 20:
                this.Item020 = LanguagePrimitives.ConvertTo <T20>(value);
                return;

            case 0x15:
                this.Item021 = LanguagePrimitives.ConvertTo <T21>(value);
                return;

            case 0x16:
                this.Item022 = LanguagePrimitives.ConvertTo <T22>(value);
                return;

            case 0x17:
                this.Item023 = LanguagePrimitives.ConvertTo <T23>(value);
                return;

            case 0x18:
                this.Item024 = LanguagePrimitives.ConvertTo <T24>(value);
                return;

            case 0x19:
                this.Item025 = LanguagePrimitives.ConvertTo <T25>(value);
                return;

            case 0x1a:
                this.Item026 = LanguagePrimitives.ConvertTo <T26>(value);
                return;

            case 0x1b:
                this.Item027 = LanguagePrimitives.ConvertTo <T27>(value);
                return;

            case 0x1c:
                this.Item028 = LanguagePrimitives.ConvertTo <T28>(value);
                return;

            case 0x1d:
                this.Item029 = LanguagePrimitives.ConvertTo <T29>(value);
                return;

            case 30:
                this.Item030 = LanguagePrimitives.ConvertTo <T30>(value);
                return;

            case 0x1f:
                this.Item031 = LanguagePrimitives.ConvertTo <T31>(value);
                return;
            }
            throw new ArgumentOutOfRangeException("index");
        }
Exemple #9
0
        private void ReadXml()
        {
            try
            {
                Deserializer deserializer = new Deserializer((XmlReader) new XmlTextReader((TextReader)this.streamReader));
                while (!deserializer.Done())
                {
                    string          streamName;
                    object          obj    = deserializer.Deserialize(out streamName);
                    MinishellStream stream = MinishellStream.Unknown;
                    if (streamName != null)
                    {
                        stream = StringToMinishellStreamConverter.ToMinishellStream(streamName);
                    }
                    if (stream == MinishellStream.Unknown)
                    {
                        stream = this.isOutput ? MinishellStream.Output : MinishellStream.Error;
                    }
                    if (stream == MinishellStream.Output || obj != null)
                    {
                        switch (stream)
                        {
                        case MinishellStream.Error:
                            if (obj is PSObject)
                            {
                                obj = (object)ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj));
                                break;
                            }
                            string message;
                            try
                            {
                                message = (string)LanguagePrimitives.ConvertTo(obj, typeof(string), (IFormatProvider)CultureInfo.InvariantCulture);
                            }
                            catch (PSInvalidCastException ex)
                            {
                                ProcessStreamReader.tracer.TraceException((Exception)ex);
                                continue;
                            }
                            obj = (object)new ErrorRecord((Exception) new RemoteException(message), "NativeCommandError", ErrorCategory.NotSpecified, (object)message);
                            break;

                        case MinishellStream.Verbose:
                        case MinishellStream.Warning:
                        case MinishellStream.Debug:
                            try
                            {
                                obj = LanguagePrimitives.ConvertTo(obj, typeof(string), (IFormatProvider)CultureInfo.InvariantCulture);
                                break;
                            }
                            catch (PSInvalidCastException ex)
                            {
                                ProcessStreamReader.tracer.TraceException((Exception)ex);
                                continue;
                            }
                        }
                        this.AddObjectToWriter(obj, stream);
                    }
                }
            }
            catch (XmlException ex)
            {
                ProcessStreamReader.tracer.TraceException((Exception)ex);
                this.AddObjectToWriter((object)new ErrorRecord((Exception) new XmlException(string.Format((IFormatProvider)null, ResourceManagerCache.GetResourceString("NativeCP", "CliXmlError"), (object)(MinishellStream)(this.isOutput ? 0 : 1), (object)this.processPath, (object)ex.Message), (Exception)ex), "ProcessStreamReader_CliXmlError", ErrorCategory.SyntaxError, (object)this.processPath), MinishellStream.Error);
            }
        }
        private static object ConvertToNumber(string str, Tokenizer tokenizer)
        {
            bool flag1 = false;
            bool flag2 = false;
            bool flag3 = false;
            bool flag4 = false;
            long num   = 1;

            str = NumberTokenReader.ConvertDash(str);
            if (str.IndexOf("0x", 0, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                flag1 = true;
            }
            if (!flag1 && (str.IndexOf('.', 0) >= 0 || str.IndexOf("e", 0, StringComparison.OrdinalIgnoreCase) >= 0))
            {
                flag4 = true;
            }
            if (NumberTokenReader.IsMultiplier(str, str.Length - 2))
            {
                switch (char.ToUpperInvariant(str[str.Length - 2]))
                {
                case 'G':
                    num = 1073741824L;
                    str = str.Substring(0, str.Length - 2);
                    break;

                case 'K':
                    num = 1024L;
                    str = str.Substring(0, str.Length - 2);
                    break;

                case 'M':
                    num = 1048576L;
                    str = str.Substring(0, str.Length - 2);
                    break;

                case 'P':
                    num = 1125899906842624L;
                    str = str.Substring(0, str.Length - 2);
                    break;

                case 'T':
                    num = 1099511627776L;
                    str = str.Substring(0, str.Length - 2);
                    break;
                }
            }
            char upperInvariant = char.ToUpperInvariant(str[str.Length - 1]);

            if (upperInvariant == 'L')
            {
                flag2 = true;
                str   = str.Substring(0, str.Length - 1);
            }
            else if (!flag1 && upperInvariant == 'D')
            {
                flag3 = true;
                str   = str.Substring(0, str.Length - 1);
            }
            Exception innerException;

            try
            {
                if (flag3)
                {
                    return((object)(Decimal.Parse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, (IFormatProvider)NumberFormatInfo.InvariantInfo) * (Decimal)num));
                }
                if (flag2)
                {
                    return((object)checked ((long)LanguagePrimitives.ConvertTo((object)str, typeof(long), (IFormatProvider)NumberFormatInfo.InvariantInfo) * num));
                }
                if (flag4)
                {
                    return((object)(double.Parse(str, (IFormatProvider)NumberFormatInfo.InvariantInfo) * (double)num));
                }
                try
                {
                    return((object)checked ((int)LanguagePrimitives.ConvertTo((object)str, typeof(int), (IFormatProvider)NumberFormatInfo.InvariantInfo) * (int)num));
                }
                catch (Exception ex)
                {
                    CommandProcessorBase.CheckForSevereException(ex);
                }
                try
                {
                    return((object)checked ((long)LanguagePrimitives.ConvertTo((object)str, typeof(long), (IFormatProvider)NumberFormatInfo.InvariantInfo) * num));
                }
                catch (Exception ex)
                {
                    CommandProcessorBase.CheckForSevereException(ex);
                }
                try
                {
                    return((object)((Decimal)LanguagePrimitives.ConvertTo((object)str, typeof(Decimal), (IFormatProvider)NumberFormatInfo.InvariantInfo) * (Decimal)num));
                }
                catch (Exception ex)
                {
                    CommandProcessorBase.CheckForSevereException(ex);
                }
                return((object)((double)LanguagePrimitives.ConvertTo((object)str, typeof(double), (IFormatProvider)NumberFormatInfo.InvariantInfo) * (double)num));
            }
            catch (OverflowException ex)
            {
                innerException = (Exception)ex;
            }
            catch (FormatException ex)
            {
                innerException = (Exception)ex;
            }
            catch (PSInvalidCastException ex)
            {
                innerException = (Exception)ex;
            }
            if (innerException != null)
            {
                if (tokenizer != null)
                {
                    tokenizer.Parser.ReportExceptionWithInnerException((object)str, typeof(ParseException), tokenizer.PositionToken(), "BadNumericConstant", innerException, (object)innerException.Message);
                }
                else
                {
                    throw InterpreterError.NewInterpreterExceptionWithInnerException((object)str, typeof(RuntimeException), (Token)null, "BadNumericConstant", innerException, (object)innerException.Message);
                }
            }
            return((object)null);
        }
Exemple #11
0
 private static T ConvertPropertyValueTo <T>(string propertyName, object propertyValue)
 {
     if (propertyName == null)
     {
         throw PSTraceSource.NewArgumentNullException("propertyName");
     }
     if (typeof(T).IsEnum)
     {
         if (propertyValue is string)
         {
             try
             {
                 string str = (string)propertyValue;
                 return((T)Enum.Parse(typeof(T), str, true));
             }
             catch (ArgumentException)
             {
                 throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastPropertyToExpectedType, new object[] { propertyName, typeof(T).FullName, propertyValue.GetType().FullName });
             }
         }
         try
         {
             Type underlyingType = Enum.GetUnderlyingType(typeof(T));
             return((T)LanguagePrimitives.ConvertTo(propertyValue, underlyingType, CultureInfo.InvariantCulture));
         }
         catch (InvalidCastException)
         {
             throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastPropertyToExpectedType, new object[] { propertyName, typeof(T).FullName, propertyValue.GetType().FullName });
         }
     }
     if (typeof(T).Equals(typeof(PSObject)))
     {
         if (propertyValue == null)
         {
             return(default(T));
         }
         return((T)Convert.ChangeType(PSObject.AsPSObject(propertyValue), typeof(T)));
     }
     if (propertyValue == null)
     {
         if (typeof(T).IsValueType && (!typeof(T).IsGenericType || !typeof(T).GetGenericTypeDefinition().Equals(typeof(Nullable <>))))
         {
             throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastPropertyToExpectedType, new object[] { propertyName, typeof(T).FullName, (propertyValue != null) ? propertyValue.GetType().FullName : "null" });
         }
         return(default(T));
     }
     if (propertyValue is T)
     {
         return((T)propertyValue);
     }
     if (propertyValue is PSObject)
     {
         PSObject obj3 = (PSObject)propertyValue;
         return(ConvertPropertyValueTo <T>(propertyName, obj3.BaseObject));
     }
     if ((propertyValue is Hashtable) && typeof(T).Equals(typeof(PSPrimitiveDictionary)))
     {
         try
         {
             return((T)Convert.ChangeType(new PSPrimitiveDictionary((Hashtable)propertyValue), typeof(T)));
         }
         catch (ArgumentException)
         {
             throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastPropertyToExpectedType, new object[] { propertyName, typeof(T).FullName, (propertyValue != null) ? propertyValue.GetType().FullName : "null" });
         }
     }
     throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastPropertyToExpectedType, new object[] { propertyName, typeof(T).FullName, propertyValue.GetType().FullName });
 }
Exemple #12
0
        protected override void SetValueImpl(int index, object value)
        {
            switch (index)
            {
            case 0:
                base.Item000 = LanguagePrimitives.ConvertTo <T0>(value);
                return;

            case 1:
                base.Item001 = LanguagePrimitives.ConvertTo <T1>(value);
                return;

            case 2:
                base.Item002 = LanguagePrimitives.ConvertTo <T2>(value);
                return;

            case 3:
                base.Item003 = LanguagePrimitives.ConvertTo <T3>(value);
                return;

            case 4:
                base.Item004 = LanguagePrimitives.ConvertTo <T4>(value);
                return;

            case 5:
                base.Item005 = LanguagePrimitives.ConvertTo <T5>(value);
                return;

            case 6:
                base.Item006 = LanguagePrimitives.ConvertTo <T6>(value);
                return;

            case 7:
                base.Item007 = LanguagePrimitives.ConvertTo <T7>(value);
                return;

            case 8:
                base.Item008 = LanguagePrimitives.ConvertTo <T8>(value);
                return;

            case 9:
                base.Item009 = LanguagePrimitives.ConvertTo <T9>(value);
                return;

            case 10:
                base.Item010 = LanguagePrimitives.ConvertTo <T10>(value);
                return;

            case 11:
                base.Item011 = LanguagePrimitives.ConvertTo <T11>(value);
                return;

            case 12:
                base.Item012 = LanguagePrimitives.ConvertTo <T12>(value);
                return;

            case 13:
                base.Item013 = LanguagePrimitives.ConvertTo <T13>(value);
                return;

            case 14:
                base.Item014 = LanguagePrimitives.ConvertTo <T14>(value);
                return;

            case 15:
                base.Item015 = LanguagePrimitives.ConvertTo <T15>(value);
                return;

            case 0x10:
                base.Item016 = LanguagePrimitives.ConvertTo <T16>(value);
                return;

            case 0x11:
                base.Item017 = LanguagePrimitives.ConvertTo <T17>(value);
                return;

            case 0x12:
                base.Item018 = LanguagePrimitives.ConvertTo <T18>(value);
                return;

            case 0x13:
                base.Item019 = LanguagePrimitives.ConvertTo <T19>(value);
                return;

            case 20:
                base.Item020 = LanguagePrimitives.ConvertTo <T20>(value);
                return;

            case 0x15:
                base.Item021 = LanguagePrimitives.ConvertTo <T21>(value);
                return;

            case 0x16:
                base.Item022 = LanguagePrimitives.ConvertTo <T22>(value);
                return;

            case 0x17:
                base.Item023 = LanguagePrimitives.ConvertTo <T23>(value);
                return;

            case 0x18:
                base.Item024 = LanguagePrimitives.ConvertTo <T24>(value);
                return;

            case 0x19:
                base.Item025 = LanguagePrimitives.ConvertTo <T25>(value);
                return;

            case 0x1a:
                base.Item026 = LanguagePrimitives.ConvertTo <T26>(value);
                return;

            case 0x1b:
                base.Item027 = LanguagePrimitives.ConvertTo <T27>(value);
                return;

            case 0x1c:
                base.Item028 = LanguagePrimitives.ConvertTo <T28>(value);
                return;

            case 0x1d:
                base.Item029 = LanguagePrimitives.ConvertTo <T29>(value);
                return;

            case 30:
                base.Item030 = LanguagePrimitives.ConvertTo <T30>(value);
                return;

            case 0x1f:
                base.Item031 = LanguagePrimitives.ConvertTo <T31>(value);
                return;

            case 0x20:
                this.Item032 = LanguagePrimitives.ConvertTo <T32>(value);
                return;

            case 0x21:
                this.Item033 = LanguagePrimitives.ConvertTo <T33>(value);
                return;

            case 0x22:
                this.Item034 = LanguagePrimitives.ConvertTo <T34>(value);
                return;

            case 0x23:
                this.Item035 = LanguagePrimitives.ConvertTo <T35>(value);
                return;

            case 0x24:
                this.Item036 = LanguagePrimitives.ConvertTo <T36>(value);
                return;

            case 0x25:
                this.Item037 = LanguagePrimitives.ConvertTo <T37>(value);
                return;

            case 0x26:
                this.Item038 = LanguagePrimitives.ConvertTo <T38>(value);
                return;

            case 0x27:
                this.Item039 = LanguagePrimitives.ConvertTo <T39>(value);
                return;

            case 40:
                this.Item040 = LanguagePrimitives.ConvertTo <T40>(value);
                return;

            case 0x29:
                this.Item041 = LanguagePrimitives.ConvertTo <T41>(value);
                return;

            case 0x2a:
                this.Item042 = LanguagePrimitives.ConvertTo <T42>(value);
                return;

            case 0x2b:
                this.Item043 = LanguagePrimitives.ConvertTo <T43>(value);
                return;

            case 0x2c:
                this.Item044 = LanguagePrimitives.ConvertTo <T44>(value);
                return;

            case 0x2d:
                this.Item045 = LanguagePrimitives.ConvertTo <T45>(value);
                return;

            case 0x2e:
                this.Item046 = LanguagePrimitives.ConvertTo <T46>(value);
                return;

            case 0x2f:
                this.Item047 = LanguagePrimitives.ConvertTo <T47>(value);
                return;

            case 0x30:
                this.Item048 = LanguagePrimitives.ConvertTo <T48>(value);
                return;

            case 0x31:
                this.Item049 = LanguagePrimitives.ConvertTo <T49>(value);
                return;

            case 50:
                this.Item050 = LanguagePrimitives.ConvertTo <T50>(value);
                return;

            case 0x33:
                this.Item051 = LanguagePrimitives.ConvertTo <T51>(value);
                return;

            case 0x34:
                this.Item052 = LanguagePrimitives.ConvertTo <T52>(value);
                return;

            case 0x35:
                this.Item053 = LanguagePrimitives.ConvertTo <T53>(value);
                return;

            case 0x36:
                this.Item054 = LanguagePrimitives.ConvertTo <T54>(value);
                return;

            case 0x37:
                this.Item055 = LanguagePrimitives.ConvertTo <T55>(value);
                return;

            case 0x38:
                this.Item056 = LanguagePrimitives.ConvertTo <T56>(value);
                return;

            case 0x39:
                this.Item057 = LanguagePrimitives.ConvertTo <T57>(value);
                return;

            case 0x3a:
                this.Item058 = LanguagePrimitives.ConvertTo <T58>(value);
                return;

            case 0x3b:
                this.Item059 = LanguagePrimitives.ConvertTo <T59>(value);
                return;

            case 60:
                this.Item060 = LanguagePrimitives.ConvertTo <T60>(value);
                return;

            case 0x3d:
                this.Item061 = LanguagePrimitives.ConvertTo <T61>(value);
                return;

            case 0x3e:
                this.Item062 = LanguagePrimitives.ConvertTo <T62>(value);
                return;

            case 0x3f:
                this.Item063 = LanguagePrimitives.ConvertTo <T63>(value);
                return;
            }
            throw new ArgumentOutOfRangeException("index");
        }
Exemple #13
0
        private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue)
        {
            if (argument == null)
            {
                throw PSTraceSource.NewArgumentNullException("argument");
            }
            if (toType == null)
            {
                throw PSTraceSource.NewArgumentNullException("toType");
            }
            if (collectionTypeInfo == null)
            {
                collectionTypeInfo = new ParameterCollectionTypeInformation(toType);
            }
            object result = currentValue;

            using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType }))
            {
                Type c = null;
                try
                {
                    if (IsNullParameterValue(currentValue))
                    {
                        return(this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue));
                    }
                    c = currentValue.GetType();
                    if (toType.IsAssignableFrom(c))
                    {
                        bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]);
                        return(currentValue);
                    }
                    bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType });
                    if (toType == typeof(PSObject))
                    {
                        if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject))
                        {
                            currentValue = this.command.CurrentPipelineObject;
                        }
                        bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType });
                        return(LanguagePrimitives.AsPSObjectOrNull(currentValue));
                    }
                    if ((toType == typeof(string)) && (c == typeof(PSObject)))
                    {
                        PSObject obj3 = (PSObject)currentValue;
                        if (obj3 == AutomationNull.Value)
                        {
                            bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]);
                            return(null);
                        }
                    }
                    if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?)))
                    {
                        Type type = null;
                        if (c == typeof(PSObject))
                        {
                            PSObject obj4 = (PSObject)currentValue;
                            currentValue = obj4.BaseObject;
                            if (currentValue is SwitchParameter)
                            {
                                SwitchParameter parameter = (SwitchParameter)currentValue;
                                currentValue = parameter.IsPresent;
                            }
                            type = currentValue.GetType();
                        }
                        else
                        {
                            type = c;
                        }
                        if (type == typeof(bool))
                        {
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject((bool)currentValue));
                            }
                            return(new SwitchParameter((bool)currentValue));
                        }
                        if (type == typeof(int))
                        {
                            if (((int)LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(true));
                                }
                                return(new SwitchParameter(true));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(false));
                            }
                            return(new SwitchParameter(false));
                        }
                        if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type)))
                        {
                            double num = (double)LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture);
                            if (num == 0.0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(false));
                                }
                                return(new SwitchParameter(false));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(true));
                            }
                            return(new SwitchParameter(true));
                        }
                        ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" });
                        throw exception;
                    }
                    if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList))
                    {
                        object obj5 = PSObject.Base(currentValue);
                        if (obj5 != null)
                        {
                            ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType);
                            if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result))
                            {
                                return(result);
                            }
                        }
                    }
                    if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
                    {
                        bindingTracer.WriteLine("ENCODING arg into collection", new object[0]);
                        bool coercionRequired = false;
                        return(this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired));
                    }
                    if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier <>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression <>))))) && !toType.IsEnum)
                    {
                        throw new NotSupportedException();
                    }
                    bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]);
                    bool flag2 = false;
                    if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                    {
                        object obj6  = PSObject.Base(currentValue);
                        bool   flag3 = obj6 is PSObject;
                        bool   flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType());
                        flag2 = ((((PSLanguageMode)this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4;
                    }
                    try
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.FullLanguage;
                        }
                        result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture);
                    }
                    finally
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                        }
                    }
                    bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() });
                    return(result);
                }
                catch (NotSupportedException exception2)
                {
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType });
                    ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message });
                    throw exception3;
                }
                catch (PSInvalidCastException exception4)
                {
                    object[] args = new object[] { result ?? "null", toType };
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args);
                    ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message });
                    throw exception5;
                }
            }
            return(result);
        }
Exemple #14
0
        protected override void SetValueImpl(int index, object value)
        {
            switch (index)
            {
            case 0:
                base.Item000 = LanguagePrimitives.ConvertTo <T0>(value);
                return;

            case 1:
                base.Item001 = LanguagePrimitives.ConvertTo <T1>(value);
                return;

            case 2:
                base.Item002 = LanguagePrimitives.ConvertTo <T2>(value);
                return;

            case 3:
                base.Item003 = LanguagePrimitives.ConvertTo <T3>(value);
                return;

            case 4:
                base.Item004 = LanguagePrimitives.ConvertTo <T4>(value);
                return;

            case 5:
                base.Item005 = LanguagePrimitives.ConvertTo <T5>(value);
                return;

            case 6:
                base.Item006 = LanguagePrimitives.ConvertTo <T6>(value);
                return;

            case 7:
                base.Item007 = LanguagePrimitives.ConvertTo <T7>(value);
                return;

            case 8:
                this.Item008 = LanguagePrimitives.ConvertTo <T8>(value);
                return;

            case 9:
                this.Item009 = LanguagePrimitives.ConvertTo <T9>(value);
                return;

            case 10:
                this.Item010 = LanguagePrimitives.ConvertTo <T10>(value);
                return;

            case 11:
                this.Item011 = LanguagePrimitives.ConvertTo <T11>(value);
                return;

            case 12:
                this.Item012 = LanguagePrimitives.ConvertTo <T12>(value);
                return;

            case 13:
                this.Item013 = LanguagePrimitives.ConvertTo <T13>(value);
                return;

            case 14:
                this.Item014 = LanguagePrimitives.ConvertTo <T14>(value);
                return;

            case 15:
                this.Item015 = LanguagePrimitives.ConvertTo <T15>(value);
                return;
            }
            throw new ArgumentOutOfRangeException("index");
        }
Exemple #15
0
        internal void AppendDollarError(object obj)
        {
            ErrorRecord record = obj as ErrorRecord;

            if ((record != null) || (obj is Exception))
            {
                ArrayList dollarErrorVariable = this.DollarErrorVariable as ArrayList;
                if (dollarErrorVariable != null)
                {
                    if (dollarErrorVariable.Count > 0)
                    {
                        if (dollarErrorVariable[0] == obj)
                        {
                            return;
                        }
                        ErrorRecord record2 = dollarErrorVariable[0] as ErrorRecord;
                        if (((record2 != null) && (record != null)) && (record2.Exception == record.Exception))
                        {
                            return;
                        }
                    }
                    object fastValue = this.EngineSessionState.CurrentScope.ErrorCapacity.FastValue;
                    if (fastValue != null)
                    {
                        try
                        {
                            fastValue = LanguagePrimitives.ConvertTo(fastValue, typeof(int), CultureInfo.InvariantCulture);
                        }
                        catch (PSInvalidCastException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                    int num = (fastValue is int) ? ((int)fastValue) : 0x100;
                    if (0 > num)
                    {
                        num = 0;
                    }
                    else if (0x8000 < num)
                    {
                        num = 0x8000;
                    }
                    if (0 >= num)
                    {
                        dollarErrorVariable.Clear();
                    }
                    else
                    {
                        int count = dollarErrorVariable.Count - (num - 1);
                        if (0 < count)
                        {
                            dollarErrorVariable.RemoveRange(num - 1, count);
                        }
                        dollarErrorVariable.Insert(0, obj);
                    }
                }
            }
        }
Exemple #16
0
        internal static ArrayList GetSuggestion(
            HistoryInfo lastHistory,
            object lastError,
            ArrayList errorList)
        {
            ArrayList    arrayList        = new ArrayList();
            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set(nameof(lastHistory), (object)lastHistory);
            invocationModule.SessionState.PSVariable.Set(nameof(lastError), lastError);
            foreach (Hashtable suggestion in HostUtilities.suggestions)
            {
                int count = errorList.Count;
                if (LanguagePrimitives.IsTrue(suggestion[(object)"Enabled"]))
                {
                    SuggestionMatchType suggestionMatchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(suggestion[(object)"MatchType"], typeof(SuggestionMatchType), (IFormatProvider)CultureInfo.InvariantCulture);
                    if (suggestionMatchType == SuggestionMatchType.Dynamic)
                    {
                        if (!(suggestion[(object)"Rule"] is ScriptBlock sb))
                        {
                            suggestion[(object)"Enabled"] = (object)false;
                            throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "RuleMustBeScriptBlock"), "Rule");
                        }
                        object obj;
                        try
                        {
                            obj = invocationModule.Invoke(sb, (object[])null);
                        }
                        catch (Exception ex)
                        {
                            CommandProcessorBase.CheckForSevereException(ex);
                            suggestion[(object)"Enabled"] = (object)false;
                            continue;
                        }
                        if (LanguagePrimitives.IsTrue(obj))
                        {
                            string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(suggestionText))
                            {
                                string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText);
                                arrayList.Add((object)str);
                            }
                        }
                    }
                    else
                    {
                        string input = string.Empty;
                        if (suggestionMatchType == SuggestionMatchType.Command)
                        {
                            input = lastHistory.CommandLine;
                        }
                        else if (suggestionMatchType == SuggestionMatchType.Error)
                        {
                            if (lastError != null)
                            {
                                input = !(lastError is Exception exception) ? lastError.ToString() : exception.Message;
                            }
                        }
                        else
                        {
                            suggestion[(object)"Enabled"] = (object)false;
                            throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "InvalidMatchType"), "MatchType");
                        }
                        if (Regex.IsMatch(input, (string)suggestion[(object)"Rule"], RegexOptions.IgnoreCase))
                        {
                            string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(suggestionText))
                            {
                                string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText);
                                arrayList.Add((object)str);
                            }
                        }
                    }
                    if (errorList.Count != count)
                    {
                        suggestion[(object)"Enabled"] = (object)false;
                    }
                }
            }
            return(arrayList);
        }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (this._convertTypes == null)
            {
                return(inputData);
            }
            object obj2 = inputData;

            try
            {
                for (int i = 0; i < this._convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        if (this._convertTypes[i].Equals(typeof(PSReference)))
                        {
                            object   baseObject;
                            PSObject obj4 = obj2 as PSObject;
                            if (obj4 != null)
                            {
                                baseObject = obj4.BaseObject;
                            }
                            else
                            {
                                baseObject = obj2;
                            }
                            if (!(baseObject is PSReference))
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected, new object[0]);
                            }
                        }
                        else
                        {
                            object   obj5;
                            PSObject obj6 = obj2 as PSObject;
                            if (obj6 != null)
                            {
                                obj5 = obj6.BaseObject;
                            }
                            else
                            {
                                obj5 = obj2;
                            }
                            PSReference reference2 = obj5 as PSReference;
                            if (reference2 != null)
                            {
                                obj2 = reference2.Value;
                            }
                            if (bindingScriptCmdlet && (this._convertTypes[i] == typeof(string)))
                            {
                                obj5 = PSObject.Base(obj2);
                                if ((obj5 != null) && obj5.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString, new object[0]);
                                }
                            }
                        }
                    }
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(this._convertTypes[i]))
                    {
                        CheckBoolValue(obj2, this._convertTypes[i]);
                    }
                    if (bindingScriptCmdlet)
                    {
                        ParameterCollectionTypeInformation information = new ParameterCollectionTypeInformation(this._convertTypes[i]);
                        if ((information.ParameterCollectionType != ParameterCollectionType.NotCollection) && LanguagePrimitives.IsBoolOrSwitchParameterType(information.ElementType))
                        {
                            IList iList = ParameterBinderBase.GetIList(obj2);
                            if (iList != null)
                            {
                                foreach (object obj7 in iList)
                                {
                                    CheckBoolValue(obj7, information.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(obj2, information.ElementType);
                            }
                        }
                    }
                    obj2 = LanguagePrimitives.ConvertTo(obj2, this._convertTypes[i], CultureInfo.InvariantCulture);
                }
            }
            catch (PSInvalidCastException exception)
            {
                throw new ArgumentTransformationMetadataException(exception.Message, exception);
            }
            return(obj2);
        }
Exemple #18
0
        internal static ArrayList GetSuggestion(HistoryInfo lastHistory, object lastError, ArrayList errorList)
        {
            ArrayList    list             = new ArrayList();
            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory);
            invocationModule.SessionState.PSVariable.Set("lastError", lastError);
            int count = 0;

            foreach (Hashtable hashtable in suggestions)
            {
                count = errorList.Count;
                if (LanguagePrimitives.IsTrue(hashtable["Enabled"]))
                {
                    SuggestionMatchType type = (SuggestionMatchType)LanguagePrimitives.ConvertTo(hashtable["MatchType"], typeof(SuggestionMatchType), CultureInfo.InvariantCulture);
                    if (type == SuggestionMatchType.Dynamic)
                    {
                        object      obj2 = null;
                        ScriptBlock sb   = hashtable["Rule"] as ScriptBlock;
                        if (sb == null)
                        {
                            hashtable["Enabled"] = false;
                            throw new ArgumentException(SuggestionStrings.RuleMustBeScriptBlock, "Rule");
                        }
                        try
                        {
                            obj2 = invocationModule.Invoke(sb, null);
                        }
                        catch (Exception exception)
                        {
                            CommandProcessorBase.CheckForSevereException(exception);
                            hashtable["Enabled"] = false;
                            continue;
                        }
                        if (LanguagePrimitives.IsTrue(obj2))
                        {
                            string suggestionText = GetSuggestionText(hashtable["Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(suggestionText))
                            {
                                string str2 = string.Format(Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", new object[] { (int)hashtable["Id"], (string)hashtable["Category"], suggestionText });
                                list.Add(str2);
                            }
                        }
                    }
                    else
                    {
                        string input = string.Empty;
                        switch (type)
                        {
                        case SuggestionMatchType.Command:
                            input = lastHistory.CommandLine;
                            break;

                        case SuggestionMatchType.Error:
                            if (lastError != null)
                            {
                                Exception exception2 = lastError as Exception;
                                if (exception2 != null)
                                {
                                    input = exception2.Message;
                                }
                                else
                                {
                                    input = lastError.ToString();
                                }
                            }
                            break;

                        default:
                            hashtable["Enabled"] = false;
                            throw new ArgumentException(SuggestionStrings.InvalidMatchType, "MatchType");
                        }
                        if (Regex.IsMatch(input, (string)hashtable["Rule"], RegexOptions.IgnoreCase))
                        {
                            string str4 = GetSuggestionText(hashtable["Suggestion"], invocationModule);
                            if (!string.IsNullOrEmpty(str4))
                            {
                                string str5 = string.Format(Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", new object[] { (int)hashtable["Id"], (string)hashtable["Category"], str4 });
                                list.Add(str5);
                            }
                        }
                    }
                    if (errorList.Count != count)
                    {
                        hashtable["Enabled"] = false;
                    }
                }
            }
            return(list);
        }
Exemple #19
0
 private void ReadXml()
 {
     try
     {
         Deserializer deserializer = new Deserializer(XmlReader.Create(this.streamReader, InternalDeserializer.XmlReaderSettingsForCliXml));
         while (!deserializer.Done())
         {
             string          str;
             object          obj2    = deserializer.Deserialize(out str);
             MinishellStream unknown = MinishellStream.Unknown;
             if (str != null)
             {
                 unknown = StringToMinishellStreamConverter.ToMinishellStream(str);
             }
             if (unknown == MinishellStream.Unknown)
             {
                 unknown = this.isOutput ? MinishellStream.Output : MinishellStream.Error;
             }
             if ((unknown == MinishellStream.Output) || (obj2 != null))
             {
                 if (unknown == MinishellStream.Error)
                 {
                     if (obj2 is PSObject)
                     {
                         obj2 = ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj2));
                     }
                     else
                     {
                         string targetObject = null;
                         try
                         {
                             targetObject = (string)LanguagePrimitives.ConvertTo(obj2, typeof(string), CultureInfo.InvariantCulture);
                         }
                         catch (PSInvalidCastException)
                         {
                             continue;
                         }
                         obj2 = new ErrorRecord(new RemoteException(targetObject), "NativeCommandError", ErrorCategory.NotSpecified, targetObject);
                     }
                 }
                 else if (((unknown == MinishellStream.Debug) || (unknown == MinishellStream.Verbose)) || (unknown == MinishellStream.Warning))
                 {
                     try
                     {
                         obj2 = LanguagePrimitives.ConvertTo(obj2, typeof(string), CultureInfo.InvariantCulture);
                     }
                     catch (PSInvalidCastException)
                     {
                         continue;
                     }
                 }
                 this.AddObjectToWriter(obj2, unknown);
             }
         }
     }
     catch (XmlException exception)
     {
         string       cliXmlError = NativeCP.CliXmlError;
         XmlException exception2  = new XmlException(string.Format(null, cliXmlError, new object[] { this.isOutput ? MinishellStream.Output : MinishellStream.Error, this.processPath, exception.Message }), exception);
         ErrorRecord  data        = new ErrorRecord(exception2, "ProcessStreamReader_CliXmlError", ErrorCategory.SyntaxError, this.processPath);
         this.AddObjectToWriter(data, MinishellStream.Error);
     }
 }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (_convertTypes == null)
            {
                return(inputData);
            }

            object result = inputData;

            try
            {
                for (int i = 0; i < _convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        // We should not be doing a conversion here if [ref] is the last type.
                        // When [ref] appears in an argument list, it is used for checking only.
                        // No Conversion should be done.
                        if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            PSReference reference = temp as PSReference;

                            if (reference == null)
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
                                                                 ExtendedTypeSystem.ReferenceTypeExpected);
                            }
                        }
                        else
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
                            PSReference reference = temp as PSReference;

                            if (reference != null)
                            {
                                result = reference.Value;
                            }

                            if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
                            {
                                // Don't allow conversion from array to string in script w/ cmdlet binding.  Allow
                                // the conversion for ordinary script parameter binding for V1 compatibility.
                                temp = PSObject.Base(result);
                                if (temp != null && temp.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
                                                                     ExtendedTypeSystem.InvalidCastCannotRetrieveString);
                                }
                            }
                        }
                    }

                    //BUGBUG
                    //NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
                    //handling special case for boolean, switchparameter and Nullable<bool>
                    //These parameter types will not be converted if the incoming value types are not
                    //one of the accepted categories - $true/$false or numbers (0 or otherwise)
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
                    {
                        CheckBoolValue(result, _convertTypes[i]);
                    }

                    if (bindingScriptCmdlet)
                    {
                        // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
                        // to stay compatible with V1.
                        ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
                        if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection &&
                            LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
                        {
                            IList currentValueAsIList = ParameterBinderBase.GetIList(result);
                            if (currentValueAsIList != null)
                            {
                                foreach (object val in currentValueAsIList)
                                {
                                    CheckBoolValue(val, collectionTypeInfo.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(result, collectionTypeInfo.ElementType);
                            }
                        }
                    }

                    result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);

                    // Do validation of invalid direct variable assignments which are allowed to
                    // be used for parameters.
                    //
                    // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
                    if ((!bindingScriptCmdlet) && (!bindingParameters))
                    {
                        // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
                        // during variable assignment (here) - "Ignore" is blocked during variable retrieval.
                        if (_convertTypes[i] == typeof(ActionPreference))
                        {
                            ActionPreference resultPreference = (ActionPreference)result;

                            if (resultPreference == ActionPreference.Suspend)
                            {
                                throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
                            }
                        }
                    }
                }
            }
            catch (PSInvalidCastException e)
            {
                throw new ArgumentTransformationMetadataException(e.Message, e);
            }

            return(result);
        }
Exemple #21
0
        internal bool ExistsInExpression(T flagName)
        {
            object enumVal = LanguagePrimitives.ConvertTo(flagName, this._underType, CultureInfo.InvariantCulture);

            return(this._root.ExistEnum(enumVal));
        }
Exemple #22
0
 public override string ToString()
 {
     return((string)LanguagePrimitives.ConvertTo(ImmediateBaseObject, typeof(string), Thread.CurrentThread.CurrentCulture));
 }
Exemple #23
0
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            bool flag = false;

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                flag = true;
            }
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            if (this.configHash != null)
            {
                if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables))
                {
                    Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable;
                    if (hashtable != null)
                    {
                        foreach (DictionaryEntry entry in hashtable)
                        {
                            string introduced76 = entry.Key.ToString();
                            this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args);
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
                {
                    Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                    if (hashtableArray != null)
                    {
                        foreach (Hashtable hashtable2 in hashtableArray)
                        {
                            if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken))
                            {
                                string      str2  = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken);
                                ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock;
                                if (!string.IsNullOrEmpty(str2) && (block != null))
                                {
                                    block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState;
                                    PowerShell powershell = PowerShell.Create();
                                    powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope");
                                    powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2);
                                    this.InvokePowerShell(powershell, args);
                                }
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess))
                {
                    string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]);
                    if (strArray != null)
                    {
                        foreach (string str3 in strArray)
                        {
                            if (!string.IsNullOrEmpty(str3))
                            {
                                this.InvokeScript(new Command(str3, true, false), args);
                            }
                        }
                    }
                }
                bool flag2 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases))
                {
                    string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]);
                    if (strArray2 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable())
                        {
                            bool flag3 = false;
                            foreach (string str4 in strArray2)
                            {
                                if (!string.IsNullOrEmpty(str4))
                                {
                                    IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4);
                                    if (this.MatchKeyPattern(patternList, pair.Key))
                                    {
                                        pair.Value.Visibility = SessionStateEntryVisibility.Public;
                                        flag3 = true;
                                    }
                                }
                            }
                            if (!flag3)
                            {
                                pair.Value.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets))
                {
                    string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]);
                    if (strArray3 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable())
                        {
                            bool flag4 = false;
                            foreach (string str5 in strArray3)
                            {
                                if (!string.IsNullOrEmpty(str5))
                                {
                                    IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5);
                                    if (this.MatchKeyPattern(enumerable2, pair2.Key))
                                    {
                                        foreach (CmdletInfo info in pair2.Value)
                                        {
                                            info.Visibility = SessionStateEntryVisibility.Public;
                                            flag4           = true;
                                        }
                                    }
                                }
                            }
                            if (!flag4)
                            {
                                foreach (CmdletInfo info2 in pair2.Value)
                                {
                                    info2.Visibility = SessionStateEntryVisibility.Private;
                                }
                            }
                        }
                    }
                }
                List <string> list  = new List <string>();
                bool          flag5 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions))
                {
                    string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]);
                    if (strArray4 != null)
                    {
                        flag2 = true;
                        flag5 = true;
                        list.AddRange(strArray4);
                    }
                }
                if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
                {
                    Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                    if (hashtableArray2 != null)
                    {
                        foreach (Hashtable hashtable3 in hashtableArray2)
                        {
                            string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken);
                            if (!string.IsNullOrEmpty(str6))
                            {
                                list.Add(str6);
                            }
                        }
                    }
                }
                string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType);
                if (!string.IsNullOrEmpty(str7))
                {
                    SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true);
                    if (type == SessionType.RestrictedRemoteServer)
                    {
                        list.Add("Get-Command");
                        list.Add("Get-FormatData");
                        list.Add("Select-Object");
                        list.Add("Get-Help");
                        list.Add("Measure-Object");
                        list.Add("Out-Default");
                        list.Add("Exit-PSSession");
                    }
                }
                if (list.Count > 0)
                {
                    foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable())
                    {
                        bool         flag6 = false;
                        string       key   = entry2.Key.ToString();
                        FunctionInfo info3 = entry2.Value as FunctionInfo;
                        if (info3 != null)
                        {
                            foreach (string str9 in list)
                            {
                                if (!string.IsNullOrEmpty(str9))
                                {
                                    IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9);
                                    if (this.MatchKeyPattern(enumerable3, key))
                                    {
                                        info3.Visibility = SessionStateEntryVisibility.Public;
                                        flag6            = true;
                                    }
                                }
                            }
                            if (!flag6 && flag5)
                            {
                                info3.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders))
                {
                    string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]);
                    if (strArray5 != null)
                    {
                        flag2 = true;
                        IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers;
                        Collection <string> collection = new Collection <string>();
                        foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers)
                        {
                            bool flag7 = false;
                            foreach (string str10 in strArray5)
                            {
                                if (!string.IsNullOrEmpty(str10))
                                {
                                    IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10);
                                    if (this.MatchKeyPattern(enumerable4, pair3.Key))
                                    {
                                        flag7 = true;
                                    }
                                }
                            }
                            if (!flag7)
                            {
                                collection.Add(pair3.Key);
                            }
                        }
                        foreach (string str11 in collection)
                        {
                            args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11);
                        }
                    }
                }
                if (flag2)
                {
                    CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
                    IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable();
                    PSModuleAutoLoadingPreference   preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private);
                    bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private);
                    if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None))
                    {
                        throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders }));
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode))
                {
                    PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true);
                    if (flag && (mode != PSLanguageMode.ConstrainedLanguage))
                    {
                        throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState);
                    }
                    args.Runspace.ExecutionContext.LanguageMode = mode;
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy))
                {
                    ExecutionPolicy policy  = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true);
                    string          shellID = args.Runspace.ExecutionContext.ShellID;
                    SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID);
                }
            }
            Command cmdToRun = null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                cmdToRun = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (cmdToRun != null)
            {
                this.InvokeScript(cmdToRun, args);
                if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
                {
                    object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
                    if (valueToConvert != null)
                    {
                        this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null);
                    }
                }
            }
        }
Exemple #24
0
        internal static object GetMDArrayValueOrSlice(Array array, object indexes)
        {
            Exception whyFailed = null;

            int[] indexArray = null;
            try
            {
                indexArray = (int[])LanguagePrimitives.ConvertTo(indexes, typeof(int[]), NumberFormatInfo.InvariantInfo);
            }
            catch (InvalidCastException ice)
            {
                // Ignore an exception here as we may actually be looking at an array of arrays
                // which could still be ok. Save the exception as we may use it later...
                whyFailed = ice;
            }

            if (indexArray != null)
            {
                if (indexArray.Length != array.Rank)
                {
                    // rank failed to match so error...
                    ReportIndexingError(array, indexes, null);
                }

                return(GetMDArrayValue(array, indexArray, false));
            }

            var indexList = new List <int[]>();

            var ie = LanguagePrimitives.GetEnumerator(indexes);

            while (EnumerableOps.MoveNext(null, ie))
            {
                var currentIndex = EnumerableOps.Current(ie);
                try
                {
                    indexArray = LanguagePrimitives.ConvertTo <int[]>(currentIndex);
                }
                catch (InvalidCastException)
                {
                    indexArray = null;
                }

                if (indexArray == null || indexArray.Length != array.Rank)
                {
                    if (whyFailed != null)
                    {
                        // If the first fails, report the original exception and all indices
                        ReportIndexingError(array, indexes, whyFailed);
                        Diagnostics.Assert(false, "ReportIndexingError must throw");
                    }
                    // If the second or subsequent index fails, report the failure for just that index
                    ReportIndexingError(array, currentIndex, null);
                    Diagnostics.Assert(false, "ReportIndexingError must throw");
                }

                // Only use whyFailed the first time through, otherwise
                whyFailed = null;
                indexList.Add(indexArray);
            }

            // Optimistically assume all indices are valid so the result array is the same size.
            // If that turns out to be wrong, we'll just copy the elements produced.
            var result = new object[indexList.Count];
            int j      = 0;

            foreach (var i in indexList)
            {
                var value = GetMDArrayValue(array, i, true);
                if (value != AutomationNull.Value)
                {
                    result[j++] = value;
                }
            }

            if (j != indexList.Count)
            {
                var shortResult = new object[j];
                Array.Copy(result, shortResult, j);
                return(shortResult);
            }

            return(result);
        }
 //todo: do something with ignoreCase
 public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
 {
     return(LanguagePrimitives.ConvertTo(
                (LanguagePrimitives.ConvertTo(sourceValue, typeof(string), formatProvider) as String),
                destinationType, formatProvider));
 }
Exemple #26
0
        /// <summary>
        /// Evaluate a given flag enum value against the expression.
        /// </summary>
        /// <param name="value">
        /// The flag enum value to be evaluated.
        /// </param>
        /// <returns>
        /// Whether the enum value satisfy the expression.
        /// </returns>
        public bool Evaluate(T value)
        {
            object val = LanguagePrimitives.ConvertTo(value, _underType, CultureInfo.InvariantCulture);

            return(Root.Eval(val));
        }
Exemple #27
0
        internal static object GetMDArrayValueOrSlice(Array array, object indexes)
        {
            Exception reason = null;

            int[] numArray = null;
            try
            {
                numArray = (int[])LanguagePrimitives.ConvertTo(indexes, typeof(int[]), NumberFormatInfo.InvariantInfo);
            }
            catch (InvalidCastException exception2)
            {
                reason = exception2;
            }
            if (numArray != null)
            {
                if (numArray.Length != array.Rank)
                {
                    ReportIndexingError(array, indexes, null);
                }
                return(GetMDArrayValue(array, numArray, false));
            }
            List <int[]> list       = new List <int[]>();
            IEnumerator  enumerator = LanguagePrimitives.GetEnumerator(indexes);

            while (EnumerableOps.MoveNext(null, enumerator))
            {
                object valueToConvert = EnumerableOps.Current(enumerator);
                try
                {
                    numArray = LanguagePrimitives.ConvertTo <int[]>(valueToConvert);
                }
                catch (InvalidCastException)
                {
                    numArray = null;
                }
                if ((numArray == null) || (numArray.Length != array.Rank))
                {
                    if (reason != null)
                    {
                        ReportIndexingError(array, indexes, reason);
                    }
                    ReportIndexingError(array, valueToConvert, null);
                }
                reason = null;
                list.Add(numArray);
            }
            object[] sourceArray = new object[list.Count];
            int      length      = 0;

            foreach (int[] numArray2 in list)
            {
                object obj3 = GetMDArrayValue(array, numArray2, true);
                if (obj3 != AutomationNull.Value)
                {
                    sourceArray[length++] = obj3;
                }
            }
            if (length != list.Count)
            {
                object[] destinationArray = new object[length];
                Array.Copy(sourceArray, destinationArray, length);
                return(destinationArray);
            }
            return(sourceArray);
        }