예제 #1
0
        private static string ObjectToWqlLiteral(object o)
        {
            if (LanguagePrimitives.IsNull(o))
            {
                return("null"); // based on an example at http://msdn.microsoft.com/en-us/library/aa394054(VS.85).aspx
            }

            o = CimValueConverter.ConvertFromDotNetToCim(o);
            PSObject pso      = PSObject.AsPSObject(o);
            Type     type     = pso.BaseObject.GetType();
            TypeCode typeCode = LanguagePrimitives.GetTypeCode(type);

            if (typeCode == TypeCode.String)
            {
                string s = o.ToString();
                s = s.Replace("\\", "\\\\");
                s = s.Replace("'", "\\'");
                return("'" + s + "'");
            }

            if (typeCode == TypeCode.Char)
            {
                return(ObjectToWqlLiteral(LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture)));
            }

            if (typeCode == TypeCode.DateTime)
            {
                var    dateTime = (DateTime)LanguagePrimitives.ConvertTo(o, typeof(DateTime), CultureInfo.InvariantCulture);
                string result   = ClrFacade.ToDmtfDateTime(dateTime);
                return("'" + result + "'");
            }

            if (type == typeof(TimeSpan))
            {
                // WMIv1 does not support using interval literals in a WQL query
                return(null);
            }

            if (LanguagePrimitives.IsNumeric(typeCode))
            {
                return((string)LanguagePrimitives.ConvertTo(o, typeof(string), CultureInfo.InvariantCulture));
            }

            if (LanguagePrimitives.IsBooleanType(type))
            {
                if ((bool)LanguagePrimitives.ConvertTo(o, typeof(bool), CultureInfo.InvariantCulture))
                {
                    return("TRUE"); // based on http://msdn.microsoft.com/en-us/library/aa394054(VS.85).aspx
                }
                return("FALSE");    // based on http://msdn.microsoft.com/en-us/library/aa394054(VS.85).aspx
            }

            throw CimValueConverter.GetInvalidCastException(
                      null, /* inner exception */
                      "InvalidCimQueryCast",
                      o,
                      CmdletizationResources.CimConversion_WqlQuery);
        }
예제 #2
0
        public void TestParamsLengthZero()
        {
            var obj = new MyTestClass();
            // Check that passing no parameters to the 'params' parameter (empty array) works
            var result = ClrFacade.CallInstanceMethod(obj, "UniqueNameStrStrParams", new[] { "", "" });

            // However, if it means that there are more than one candidate methods:
            Assert.Throws <AmbiguousMatchException>(() => { ClrFacade.CallInstanceMethod(obj, "StringSameNameParams", new[] { "" }); });
        }
예제 #3
0
        private bool IsLocalFile(string filename)
        {
            SecurityZone zone = ClrFacade.GetFileSecurityZone(filename);

            if (zone == SecurityZone.MyComputer ||
                zone == SecurityZone.Intranet ||
                zone == SecurityZone.Trusted)
            {
                return(true);
            }

            return(false);
        }
예제 #4
0
            internal void Copy(SecureString source, int offset)
            {
                IntPtr plainTextString = ClrFacade.SecureStringToCoTaskMemUnicode(source);

                try
                {
                    unsafe
                    {
                        Copy((char *)plainTextString, offset, source.Length);
                    }
                }
                finally
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(plainTextString);
                }
            }
예제 #5
0
            private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName)
            {
                Assembly result = null;

#if false
                // This should be re-enabled once the default assembly list contains the
                // assemblies referenced by the S.M.A.dll.

                // First we need to get the execution context from thread-local storage.

                ExecutionContext context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();

                if (context != null)
                {
                    context.AssemblyCache.GetAtKey(assemblyName, out result);
                }
#else
                foreach (Assembly a in ClrFacade.GetAssemblies())
                {
                    AssemblyName aName = null;
                    try
                    {
                        aName = a.GetName();
                    }
                    catch (System.Security.SecurityException)
                    {
                        continue;
                    }

                    string nameToCompare = fullName ? aName.FullName : aName.Name;

                    if (string.Equals(nameToCompare, assemblyName, StringComparison.Ordinal))
                    {
                        return(a);
                    }
                }
#endif
                return(result);
            }
예제 #6
0
        internal static void Compile(EnumMetadataEnum enumMetadata)
        {
            string fullEnumName = GetEnumFullName(enumMetadata);

            Type underlyingType;

            if (enumMetadata.UnderlyingType != null)
            {
                underlyingType = (Type)LanguagePrimitives.ConvertTo(enumMetadata.UnderlyingType, typeof(Type), CultureInfo.InvariantCulture);
            }
            else
            {
                underlyingType = typeof(Int32);
            }

            ModuleBuilder mb = s_moduleBuilder.Value;
            EnumBuilder   eb;

            lock (s_moduleBuilderUsageLock)
            {
                eb = mb.DefineEnum(fullEnumName, TypeAttributes.Public, underlyingType);
            }

            if (enumMetadata.BitwiseFlagsSpecified && enumMetadata.BitwiseFlags)
            {
                var cab = new CustomAttributeBuilder(typeof(FlagsAttribute).GetConstructor(PSTypeExtensions.EmptyTypes), new object[0]);
                eb.SetCustomAttribute(cab);
            }

            foreach (var value in enumMetadata.Value)
            {
                string name         = value.Name;
                object integerValue = LanguagePrimitives.ConvertTo(value.Value, underlyingType, CultureInfo.InvariantCulture);
                eb.DefineLiteral(name, integerValue);
            }

            ClrFacade.CreateEnumType(eb);
        }
예제 #7
0
        public void TestOptionalParametersMethodInvocation()
        {
            // TODO tighter checks. Start with: it does not bomb...
            var obj = new MyTestClass();

            ClrFacade.CallInstanceMethod(obj, "OptionalInt", new object[] { });
            ClrFacade.CallInstanceMethod(obj, "OptionalInt", new object[] { 3 });

            ClrFacade.CallInstanceMethod(obj, "IntOptionalInt", new object[] { 3 });
            ClrFacade.CallInstanceMethod(obj, "IntOptionalInt", new object[] { 3, 5 });

            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalInt", new object[] { 3.0 });
            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalInt", new object[] { 3.0, 5 });

            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalIntDoubleString", new object[] { 3.0, 5, 4.5, "blah" });
            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalIntDoubleString", new object[] { 3.0, 5, 4.5 });
            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalIntDoubleString", new object[] { 3.0, 5 });
            ClrFacade.CallInstanceMethod(obj, "DoubleOptionalIntDoubleString", new object[] { 3.0 });

            Assert.Equal("LevelOneClass", ClrFacade.CallInstanceMethod(obj, "OptionalArgsMatch", new object[] { new LevelOneClass() }));
            Assert.Equal("LevelTwoClass", ClrFacade.CallInstanceMethod(obj, "OptionalArgsMatch", new object[] { new LevelTwoClass() }));
            Assert.Equal("IMyInterface", ClrFacade.CallInstanceMethod(obj, "OptionalArgsMatch", new object[] { new OtherLevelOneClass() }));
        }
        /// <summary>
        /// Decode class or struct.
        /// </summary>
        private static object DecodeClassOrStruct(PSObject psObject, Type type)
        {
            object obj = ClrFacade.GetUninitializedObject(type);

            // Field values cannot be null - because for null fields we simply don't transport them.
            foreach (PSPropertyInfo propertyInfo in psObject.Properties)
            {
                FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (propertyInfo.Value == null)
                {
                    throw RemoteHostExceptions.NewDecodingFailedException();
                }
                object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType);
                if (fieldValue == null)
                {
                    throw RemoteHostExceptions.NewDecodingFailedException();
                }

                fieldInfo.SetValue(obj, fieldValue);
            }

            return(obj);
        }
        internal static byte[] GetData(SecureString s)
        {
            //
            // each unicode char is 2 bytes.
            //
            byte[] data = new byte[s.Length * 2];

            if (s.Length > 0)
            {
                IntPtr ptr = ClrFacade.SecureStringToCoTaskMemUnicode(s);

                try
                {
                    Marshal.Copy(ptr, data, 0, data.Length);
                }
                finally
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(ptr);
                }
            }

            return(data);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="powerShellVersion"></param>
        /// <param name="credential"></param>
        /// <param name="initializationScript"></param>
        /// <param name="useWow64"></param>
        public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64)
        {
            string psWow64Path = s_PSExePath;

            if (useWow64)
            {
                string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

                if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) ||
                                                          procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase)))
                {
                    psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");

                    if (!File.Exists(psWow64Path))
                    {
                        string message =
                            PSRemotingErrorInvariants.FormatResourceString(
                                RemotingErrorIdStrings.IPCWowComponentNotPresent,
                                psWow64Path);
                        throw new PSInvalidOperationException(message);
                    }
                }
            }

            string processArguments = string.Empty;
            // Adding Version parameter to powershell.exe
            // Version parameter needs to go before all other parameters because the native layer looks for Version or
            // PSConsoleFile parameters before parsing other parameters.
            // The other parameters get parsed in the managed layer.
            Version tempVersion = powerShellVersion ?? PSVersionInfo.PSVersion;

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "-Version {0}", new Version(tempVersion.Major, tempVersion.Minor));

            processArguments = string.Format(CultureInfo.InvariantCulture,
                                             "{0} -s -NoLogo -NoProfile", processArguments);

            if (initializationScript != null)
            {
                string scripBlockAsString = initializationScript.ToString();
                if (!string.IsNullOrEmpty(scripBlockAsString))
                {
                    string encodedCommand =
                        Convert.ToBase64String(Encoding.Unicode.GetBytes(scripBlockAsString));
                    processArguments = string.Format(CultureInfo.InvariantCulture,
                                                     "{0} -EncodedCommand {1}", processArguments, encodedCommand);
                }
            }

            // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set
            // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below.
            _startInfo = new ProcessStartInfo
            {
                FileName               = useWow64 ? psWow64Path : s_PSExePath,
                Arguments              = processArguments,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
                LoadUserProfile        = true,
            };

            if (credential != null)
            {
                Net.NetworkCredential netCredential = credential.GetNetworkCredential();

                _startInfo.UserName = netCredential.UserName;
                _startInfo.Domain   = string.IsNullOrEmpty(netCredential.Domain) ? "." : netCredential.Domain;
#if CORECLR
                _startInfo.PasswordInClearText = ClrFacade.ConvertSecureStringToString(credential.Password);
#else
                _startInfo.Password = credential.Password;
#endif
            }

            Process = new Process {
                StartInfo = _startInfo, EnableRaisingEvents = true
            };
        }
예제 #11
0
        } // ProcessRecord

        private string GetFilePath()
        {
            if (String.IsNullOrEmpty(_fileName))
            {
                if (InvocationExtent == null || String.IsNullOrEmpty(InvocationExtent.File))
                {
                    throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.NotCalledFromAScriptFile);
                }
            }

            string dir = _baseDirectory;

            if (String.IsNullOrEmpty(dir))
            {
                if (InvocationExtent != null && !String.IsNullOrEmpty(InvocationExtent.File))
                {
                    dir = Path.GetDirectoryName(InvocationExtent.File);
                }
                else
                {
                    dir = ".";
                }
            }

            dir = PathUtils.ResolveFilePath(dir, this);

            string fileName = _fileName;

            if (String.IsNullOrEmpty(fileName))
            {
                fileName = InvocationExtent.File;
            }
            else
            {
                if (!String.IsNullOrEmpty(Path.GetDirectoryName(fileName)))
                {
                    throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.FileNameParameterCannotHavePath);
                }
            }

            fileName = Path.GetFileNameWithoutExtension(fileName);

            CultureInfo culture = null;

            if (_uiculture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }
            else
            {
                try
                {
                    culture = ClrFacade.GetCultureInfo(_uiculture);
                }
                catch (ArgumentException)
                {
                    throw PSTraceSource.NewArgumentException("Culture");
                }
            }

            CultureInfo currentCulture = culture;
            string      filePath;
            string      fullFileName = fileName + ".psd1";

            while (currentCulture != null && !String.IsNullOrEmpty(currentCulture.Name))
            {
                filePath = Path.Combine(dir, currentCulture.Name, fullFileName);

                if (File.Exists(filePath))
                {
                    return(filePath);
                }

                currentCulture = currentCulture.Parent;
            }

            filePath = Path.Combine(dir, fullFileName);

            if (File.Exists(filePath))
            {
                return(filePath);
            }

            InvalidOperationException ioe =
                PSTraceSource.NewInvalidOperationException(
                    ImportLocalizedDataStrings.CannotFindPsd1File,
                    fullFileName,
                    Path.Combine(dir, culture.Name)
                    );

            WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound,
                                       Path.Combine(dir, culture.Name, fullFileName)));
            return(null);
        }
예제 #12
0
        /// <summary>
        /// Get the path of reference assembly where the type is declared.
        /// </summary>
        private static string GetReferenceAssemblyPathBasedOnType(Type type)
        {
            string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location);

            return(PathType.Combine(s_netcoreAppRefFolder, refAsmFileName));
        }
예제 #13
0
#pragma warning restore 1573
#else
        public int Start(string consoleFilePath, string[] args)
#endif
        {
#if !CORECLR
            // For long-path support, Full .NET requires some AppContext switches;
            // (for CoreCLR this is Not needed, because CoreCLR supports long paths by default)
            // internally in .NET they are cached once retrieved and are typically hit very early during an application run;
            // so per .NET team's recommendation, we are setting them as soon as we enter managed code.
            EnableLongPathsInDotNetIfAvailable();
#endif
            System.Management.Automation.Runspaces.EarlyStartup.Init();

            // Set ETW activity Id
            Guid activityId = EtwActivity.GetActivityId();

            if (activityId == Guid.Empty)
            {
                EtwActivity.SetActivityId(EtwActivity.CreateActivityId());
            }

            PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart,
                                               PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);

#if !CORECLR
            // Register crash reports in non-server mode
            WindowsErrorReporting.RegisterWindowsErrorReporting(false);
#endif

            try
            {
                // Windows Vista and later support non-traditional UI fallback ie., a
                // user on an Arabic machine can choose either French or English(US) as
                // UI fallback language.
                // CLR does not support this (non-traditional) fallback mechanism.
                // The currentUICulture returned NativeCultureResolver supports this non
                // traditional fallback on Vista. So it is important to set currentUICulture
                // in the beginning before we do anything.
                ClrFacade.SetCurrentThreadUiCulture(NativeCultureResolver.UICulture);
                ClrFacade.SetCurrentThreadCulture(NativeCultureResolver.Culture);

                RunspaceConfigForSingleShell configuration = null;
                PSConsoleLoadException       warning       = null;
                //      PSSnapInException will cause the control to return back to the native code
                //      and stuff the EXCEPINFO field with the message of the exception.
                //      The native code will print this out and exit the process.
                if (string.IsNullOrEmpty(consoleFilePath))
                {
#if DEBUG
                    // Special switches for debug mode to allow self-hosting on InitialSessionState instead
                    // of runspace configuration...
                    if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase))
                    {
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
                    else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("Attach the debugger and hit enter to continue:");
                        Console.ReadLine();
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
                    else
                    {
                        ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                        configuration = null;
                    }
#else
                    ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2();
                    configuration = null;
#endif
                }
                else
                {
                    //TODO : Deprecate RunspaceConfiguration and use InitialSessionState
                    configuration =
                        RunspaceConfigForSingleShell.Create(consoleFilePath, out warning);
                }
                int exitCode = 0;
                try
                {
#if CORECLR
                    var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell;
#else
                    var banner = ManagedEntranceStrings.ShellBanner;
#endif
                    exitCode = Microsoft.PowerShell.ConsoleShell.Start(
                        configuration,
                        banner,
                        ManagedEntranceStrings.ShellHelp,
                        warning == null ? null : warning.Message,
                        args);
                }
                catch (System.Management.Automation.Host.HostException e)
                {
                    if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception))
                    {
                        System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception;

                        // These exceptions are caused by killing conhost.exe
                        // 1236, network connection aborted by local system
                        // 0x6, invalid console handle
                        if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236)
                        {
                            return(exitCode);
                        }
                    }
#if CORECLR
                    System.Environment.FailFast(e.Message);
#else
                    WindowsErrorReporting.FailFast(e);
#endif
                }
                catch (Exception e)
                {
#if CORECLR
                    System.Management.Automation.Environment.FailFast(e.Message);
#else
                    // exceptions caught here should cause Watson.
                    // Must call FailFast; otherwise the exception will be returned to the native code
                    // which will just print out the exception message without Watson
                    WindowsErrorReporting.FailFast(e);
#endif
                }
                return(exitCode);
            }
            finally
            {
#if !CORECLR
                WindowsErrorReporting.WaitForPendingReports();
#endif
            }
        }
        internal bool EnableTransportManagerSendDataToClient(
            WSManNativeApi.WSManPluginRequest requestDetails,
            WSManPluginOperationShutdownContext ctxtToReport)
        {
            _shutDownContext = ctxtToReport;
            bool isRegisterWaitForSingleObjectSucceeded = true;
            lock (_syncObject)
            {
                if (_isRequestPending)
                {
                    // if a request is already pending..ignore this.
                    WSManPluginInstance.ReportWSManOperationComplete(
                        requestDetails,
                        WSManPluginErrorCodes.NoError);
                    return false;
                }

                if (_isClosed)
                {
                    WSManPluginInstance.ReportWSManOperationComplete(requestDetails, _lastErrorReported);
                    return false;
                }

                _isRequestPending = true;
                _requestDetails = requestDetails;

                if (Platform.IsWindows)
                {
                    // Wrap the provided handle so it can be passed to the registration function
                    SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                    EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                    ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle);

                    _registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                            eventWaitHandle,
                            new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                            _shutDownContext,
                            -1, // INFINITE
                            true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                    if (null == _registeredShutDownWaitHandle)
                    {
                        isRegisterWaitForSingleObjectSucceeded = false;
                    }
                }
                // release thread waiting to send data to the client.
                _waitHandle.Set();
            }

            if (!isRegisterWaitForSingleObjectSucceeded)
            {
                WSManPluginInstance.PerformCloseOperation(ctxtToReport);
                WSManPluginInstance.ReportOperationComplete(
                    requestDetails,
                    WSManPluginErrorCodes.ShutdownRegistrationFailed,
                    StringUtil.Format(
                        RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed));
                return false;
            }

            return true;
        }
        /// <summary>
        /// Creates an instance of the FileSystemContentStream class, opens
        /// the specified file for reading, and returns the IContentReader interface
        /// to it.
        /// </summary>
        /// <param name="path">
        /// The path of the file to be opened for reading.
        /// </param>
        /// <returns>
        /// An IContentReader for the specified file.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        public IContentReader GetContentReader(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            path = NormalizePath(path);

            // Defaults for the file read operation
            string delimiter = "\n";

            // Encoding encoding = Encoding.Default;
            Encoding encoding = ClrFacade.GetDefaultEncoding();

            bool streamTypeSpecified = false;
            bool usingByteEncoding   = false;
            bool delimiterSpecified  = false;
            bool isRawStream         = false;

            // Get the dynamic parameters.
            // They override the defaults specified above.
            if (DynamicParameters != null)
            {
                StreamContentReaderDynamicParameters dynParams = DynamicParameters as StreamContentReaderDynamicParameters;
                if (dynParams != null)
                {
                    // -raw is not allowed when -first,-last or -wait is specified
                    // this call will validate that and throws.
                    ValidateParameters(dynParams.Raw);

                    isRawStream = dynParams.Raw;

                    // Get the delimiter
                    delimiterSpecified = dynParams.DelimiterSpecified;
                    if (delimiterSpecified)
                    {
                        delimiter = dynParams.Delimiter;
                    }

                    // Get the stream type
                    usingByteEncoding   = dynParams.AsByteStream;
                    streamTypeSpecified = dynParams.WasStreamTypeSpecified;

                    if (usingByteEncoding && streamTypeSpecified)
                    {
                        WriteWarning(FileSystemProviderStrings.EncodingNotUsed);
                    }

                    if (streamTypeSpecified)
                    {
                        encoding = dynParams.Encoding;
                    }
                }
            }
            StreamContentReaderWriter stream = null;

            ZipFileItemInfo archiveFile = GetItemHelper(path);

            //Archive.FileStream archiveStream = archiveFile.Open(FileMode.Append);

            try
            {
                // Users can't both read as bytes, and specify a delimiter
                if (delimiterSpecified)
                {
                    if (usingByteEncoding)
                    {
                        Exception e =
                            new ArgumentException(FileSystemProviderStrings.DelimiterError, "delimiter");
                        WriteError(new ErrorRecord(
                                       e,
                                       "GetContentReaderArgumentError",
                                       ErrorCategory.InvalidArgument,
                                       path));
                    }
                    else
                    {
                        //Console.WriteLine("Get-Content : Delimiter");
                        stream = new ZipFileContentStream(archiveFile, FileMode.Append, delimiter, encoding, usingByteEncoding, this, isRawStream);
                    }
                }
                else
                {
                    //Console.WriteLine("Get-Content : Default");
                    stream = new ZipFileContentStream(archiveFile, FileMode.Append, encoding, usingByteEncoding, this, isRawStream);
                }
            }
            catch (PathTooLongException pathTooLong)
            {
                WriteError(new ErrorRecord(pathTooLong, "GetContentReaderPathTooLongError", ErrorCategory.InvalidArgument, path));
            }
            catch (FileNotFoundException fileNotFound)
            {
                WriteError(new ErrorRecord(fileNotFound, "GetContentReaderFileNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (DirectoryNotFoundException directoryNotFound)
            {
                WriteError(new ErrorRecord(directoryNotFound, "GetContentReaderDirectoryNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (ArgumentException argException)
            {
                WriteError(new ErrorRecord(argException, "GetContentReaderArgumentError", ErrorCategory.InvalidArgument, path));
            }
            catch (IOException ioException)
            {
                // IOException contains specific message about the error occured and so no need for errordetails.
                WriteError(new ErrorRecord(ioException, "GetContentReaderIOError", ErrorCategory.ReadError, path));
            }
            catch (System.Security.SecurityException securityException)
            {
                WriteError(new ErrorRecord(securityException, "GetContentReaderSecurityError", ErrorCategory.PermissionDenied, path));
            }
            catch (UnauthorizedAccessException unauthorizedAccess)
            {
                WriteError(new ErrorRecord(unauthorizedAccess, "GetContentReaderUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
            }
            catch (Exception e)
            {
                WriteError(
                    new ErrorRecord(e, "Unhandled Error", ErrorCategory.InvalidArgument, path)
                    );
            }

            if (stream == null)
            {
                throw new Exception("Invalid stream");
            }

            return(stream);
        }
예제 #16
0
 /// <summary>
 /// Load an assembly given its byte stream
 /// </summary>
 /// <param name="assembly">The byte stream of assembly</param>
 /// <returns>The loaded assembly</returns>
 public static Assembly LoadFrom(Stream assembly)
 {
     return(ClrFacade.LoadFrom(assembly));
 }
예제 #17
0
        public void TestMethodBindingOptionalParameters()
        {
            var    tname    = typeof(TestMethodBinding).FullName;
            int    anInt    = 1;
            double aDouble  = Math.PI;
            object anObject = new Object();

            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anObject, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anObject, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anObject, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anObject, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anObject, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anObject, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anObject, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anInt, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anInt, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anInt, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anInt, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anInt, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anInt, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anObject, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anObject, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anObject, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anObject, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anObject, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anObject, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anObject, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anObject, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anObject, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anInt, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anInt, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anInt, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anInt, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anInt, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anInt, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anObject, anInt, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anObject, anInt, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anObject, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anObject, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anObject, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anObject, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anObject, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anObject, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anObject, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anInt, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anInt, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anInt, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anInt, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anInt, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anInt, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anObject, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anObject, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anObject, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anObject, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anObject, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anObject, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anObject, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anObject, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anObject, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anObject, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anObject, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anObject, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anInt, anObject),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anInt, anObject }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, aDouble, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, aDouble, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, aDouble, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, aDouble, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, aDouble, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, aDouble, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, aDouble, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, aDouble, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, anInt, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, anInt, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, anInt, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, anInt, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, anInt, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, anInt, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, aDouble, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, aDouble, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, aDouble, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, aDouble, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, aDouble, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, aDouble, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, aDouble, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, aDouble, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, aDouble, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, aDouble, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, anInt, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, anInt, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, anInt, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, anInt, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, anInt, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, anInt, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(aDouble, anInt, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { aDouble, anInt, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, aDouble, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, aDouble, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, aDouble, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, aDouble, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, aDouble, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, aDouble, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, aDouble, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, aDouble, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, anInt, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, anInt, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, anInt, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, anInt, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, anInt, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, anInt, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, aDouble, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, aDouble, anInt, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, aDouble, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, aDouble, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, aDouble, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, aDouble, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, aDouble, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, aDouble, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, aDouble, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, aDouble, anInt, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, aDouble, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, aDouble, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, aDouble, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, aDouble, anInt }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anInt, aDouble),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anInt, aDouble }));
            Assert.Equal(
                TestMethodBinding.SomeMethodWithVarArgs(anInt, anInt, anInt, anInt, anInt),
                ClrFacade.CallStaticMethod(tname, "SomeMethodWithVarArgs", new object[] { anInt, anInt, anInt, anInt, anInt }));

            Assert.Equal(
                TestMethodBinding.MultipleMatchVarArgs(anObject, new LevelOneClass(), anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "MultipleMatchVarArgs", new object[] { anObject, new LevelOneClass(), anObject, anObject, anObject }));

            Assert.Equal(
                TestMethodBinding.MultipleMatchVarArgs(anObject, new LevelTwoClass(), anObject, anObject, anObject),
                ClrFacade.CallStaticMethod(tname, "MultipleMatchVarArgs", new object[] { anObject, new LevelTwoClass(), anObject, anObject, anObject }));

            Assert.Throws <AmbiguousMatchException>(
                () => { ClrFacade.CallStaticMethod(tname, "MultipleMatchVarArgs", new object[] { anObject, new LevelThreeClass(), anObject, anObject, anObject }); });
        }
        private Assembly LoadMshSnapinAssembly(PSSnapInInfo mshsnapinInfo)
        {
            Assembly assembly = null;

            s_mshsnapinTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", mshsnapinInfo.AssemblyName);

            try
            {
                // WARNING: DUPLICATE CODE see InitialSessionState
                assembly = Assembly.Load(new AssemblyName(mshsnapinInfo.AssemblyName));
            }
            catch (FileLoadException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }
            catch (BadImageFormatException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }
            catch (FileNotFoundException e)
            {
                s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
            }

            if (assembly != null)
            {
                return(assembly);
            }

            s_mshsnapinTracer.WriteLine("Loading assembly from path: {0}", mshsnapinInfo.AssemblyName);

            try
            {
                AssemblyName assemblyName = ClrFacade.GetAssemblyName(mshsnapinInfo.AbsoluteModulePath);
                if (string.Compare(assemblyName.FullName, mshsnapinInfo.AssemblyName, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInAssemblyNameMismatch, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo.AssemblyName);
                    s_mshsnapinTracer.TraceError(message);
                    throw new PSSnapInException(mshsnapinInfo.Name, message);
                }

                assembly = ClrFacade.LoadFrom(mshsnapinInfo.AbsoluteModulePath);
            }
            catch (FileLoadException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }
            catch (BadImageFormatException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }
            catch (FileNotFoundException e)
            {
                s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message);
                throw new PSSnapInException(mshsnapinInfo.Name, e.Message);
            }

            return(assembly);
        }
예제 #19
0
        /// <summary>
        /// Process a single module with a given culture
        /// </summary>
        /// <param name="module">module to process</param>
        /// <param name="culture">culture to use</param>
        /// <returns>true if the module has been processed, false if not</returns>
        internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
        {
            UpdatableHelpInfo currentHelpInfo = null;
            UpdatableHelpInfo newHelpInfo = null;
            string helpInfoUri = null;

            // reading the xml file even if force is specified
            // Reason: we need the current version for ShouldProcess
            string xml = UpdatableHelpSystem.LoadStringFromPath(this,
                 SessionState.Path.Combine(module.ModuleBase, module.GetHelpInfoName()),
                 null);

            if (xml != null)
            {
                // constructing the helpinfo object from previous update help log xml..
                // no need to resolve the uri's in this case.
                currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid,
                                                             currentCulture: null, pathOverride: null, verbose: false,
                                                             shouldResolveUri: false,
                                                             // ignore validation exception if _force is true
                                                             ignoreValidationException: _force);
            }

            // Don't update too frequently
            if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force))
            {
                return true;
            }

            _alreadyCheckedOncePerDayPerModule = true;

            if (_path != null)
            {
                UpdatableHelpSystemDrive helpInfoDrive = null;
                try
                {
                    Collection<string> resolvedPaths = new Collection<string>();

                    // Search for the HelpInfo XML
                    foreach (string path in _path)
                    {
                        if (String.IsNullOrEmpty(path))
                        {
                            PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.PathNullOrEmpty));
                            WriteError(e.ErrorRecord);
                            return false;
                        }

                        try
                        {
                            string sourcePath = path;

                            if (_credential != null)
                            {
                                UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, path, _credential);
                                sourcePath = drive.DriveName;
                            }

                            // Expand wildcard characters
                            foreach (string tempPath in ResolvePath(sourcePath, _recurse, _isLiteralPath))
                            {
                                resolvedPaths.Add(tempPath);
                            }
                        }
                        catch (System.Management.Automation.DriveNotFoundException e)
                        {
                            ThrowPathMustBeValidContainersException(path, e);
                        }
                        catch (ItemNotFoundException e)
                        {
                            ThrowPathMustBeValidContainersException(path, e);
                        }
                    }

                    if (resolvedPaths.Count == 0)
                    {
                        return true;
                    }

                    // Everything in resolvedPaths is a container
                    foreach (string resolvedPath in resolvedPaths)
                    {
                        string literalPath = SessionState.Path.Combine(resolvedPath, module.GetHelpInfoName());

                        xml = UpdatableHelpSystem.LoadStringFromPath(this, literalPath, _credential);

                        if (xml != null)
                        {
                            newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath,
                                                                     verbose: false, shouldResolveUri: true, ignoreValidationException: false);
                            helpInfoUri = resolvedPath;
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    CommandProcessorBase.CheckForSevereException(e);

                    throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
                        StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable,
                        null, e);
                }
                finally
                {
                    if (helpInfoDrive != null)
                    {
                        helpInfoDrive.Dispose();
                    }
                }
            }
            else
            {
                // Form the actual HelpInfo.xml uri
                helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri;
                string uri = helpInfoUri + module.GetHelpInfoName();

                newHelpInfo = _helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, uri, module.ModuleName, module.ModuleGuid, culture);
            }

            if (newHelpInfo == null)
            {
                throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
                    StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable,
                    null, null);
            }

            bool installed = false;

            foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection)
            {
                Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null;
                string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture,
                    HelpDisplayStrings.UpdateHelpShouldProcessActionMessage,
                    module.ModuleName,
                    (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0",
                    newHelpInfo.GetCultureVersion(contentUri.Culture),
                    contentUri.Culture);
                if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help"))
                {
                    continue;
                }

                if (Utils.IsUnderProductFolder(module.ModuleBase) && (!Utils.IsAdministrator()))
                {
                    string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation);
                    ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation",
                            message, ErrorCategory.InvalidOperation, null, null));
                    return false;
                }

                if (!IsUpdateNecessary(module, _force ? null : currentHelpInfo, newHelpInfo, contentUri.Culture, _force))
                {
                    WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName, HelpDisplayStrings.NewestContentAlreadyInstalled,
                        contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture)));

                    installed = true;
                    continue;
                }
                else
                {
                    try
                    {
                        Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null");

                        string helpContentUri = contentUri.ResolvedUri;
                        string xsdPath = SessionState.Path.Combine(Utils.GetApplicationBase(Context.ShellID), "Schemas\\PSMaml\\maml.xsd"); // TODO: Edit the maml XSDs and change this

                        // Gather destination paths
                        Collection<string> destPaths = new Collection<string>();

                        destPaths.Add(module.ModuleBase);

#if !CORECLR // Side-By-Side directories are not present in OneCore environments.
                        if (IsSystemModule(module.ModuleName) && ClrFacade.Is64BitOperatingSystem())
                        {
                            string path = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID).Replace("System32", "SysWOW64");

                            destPaths.Add(path);
                        }
#endif

                        Collection<string> filesInstalled;

                        if (Directory.Exists(helpContentUri))
                        {
                            if (_credential != null)
                            {
                                string helpContentName = module.GetHelpContentName(contentUri.Culture);
                                string tempContentPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

                                try
                                {
                                    using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, helpContentUri, _credential))
                                    {
                                        if (!Directory.Exists(tempContentPath))
                                        {
                                            Directory.CreateDirectory(tempContentPath);
                                        }

                                        InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, helpContentName) },
                                            Path.Combine(tempContentPath, helpContentName), false, CopyContainers.CopyTargetContainer, true, true);

                                        // Local
                                        _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, tempContentPath,
                                            destPaths, module.GetHelpContentName(contentUri.Culture),
                                            Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())),
                                            contentUri.Culture, xsdPath, out filesInstalled);
                                    }
                                }
                                catch (Exception e)
                                {
                                    CommandProcessorBase.CheckForSevereException(e);

                                    throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound),
                                        ErrorCategory.ResourceUnavailable, null, e);
                                }
                            }
                            else
                            {
                                _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, helpContentUri,
                                    destPaths, module.GetHelpContentName(contentUri.Culture),
                                    Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())),
                                    contentUri.Culture, xsdPath, out filesInstalled);
                            }
                        }
                        else
                        {
                            // Remote

                            // Download and install help content
                            if (!_helpSystem.DownloadAndInstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context,
                                destPaths, module.GetHelpContentName(contentUri.Culture), contentUri.Culture, helpContentUri, xsdPath, out filesInstalled))
                            {
                                installed = false;
                                continue;
                            }
                        }

                        _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture),
                            module.ModuleBase, module.GetHelpInfoName(), _force);

                        foreach (string fileInstalled in filesInstalled)
                        {
                            WriteVerbose(StringUtil.Format(HelpDisplayStrings.SuccessfullyUpdatedHelpContent, module.ModuleName,
                                StringUtil.Format(HelpDisplayStrings.UpdatedHelpContent, fileInstalled), contentUri.Culture.Name,
                                newHelpInfo.GetCultureVersion(contentUri.Culture)));
                        }

                        LogMessage(StringUtil.Format(HelpDisplayStrings.UpdateHelpCompleted));

                        installed = true;
                    }
                    catch (Exception e)
                    {
                        CommandProcessorBase.CheckForSevereException(e);

                        ProcessException(module.ModuleName, contentUri.Culture.Name, e);
                    }
                }
            }

            return installed;
        }
        /// <summary>
        /// Report session context to WSMan..this will let WSMan send ACK to
        /// client and client can send data.
        /// </summary>
        internal void ReportContext()
        {
            int  result = 0;
            bool isRegisterWaitForSingleObjectFailed = false;

            lock (_syncObject)
            {
                if (true == isClosed)
                {
                    return;
                }

                if (!isContextReported)
                {
                    isContextReported = true;
                    PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext,
                                                      PSOpcode.Connect, PSTask.None,
                                                      PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
                                                      creationRequestDetails.ToString(), creationRequestDetails.ToString());

                    //RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime
                    // If Signal comes and executes before registering the notification handle, cleanup will be messed
                    result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle);
                    if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result))
                    {
                        registeredShutdownNotification = 1;

                        // Wrap the provided handle so it can be passed to the registration function
                        SafeWaitHandle  safeWaitHandle  = new SafeWaitHandle(creationRequestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                        EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                        ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle);

                        // Register shutdown notification handle
                        this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                            eventWaitHandle,
                            new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                            shutDownContext,
                            -1,    // INFINITE
                            true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                        if (null == this.registeredShutDownWaitHandle)
                        {
                            isRegisterWaitForSingleObjectFailed = true;
                            registeredShutdownNotification      = 0;
                        }
                    }
                }
            }

            if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed))
            {
                string errorMessage;
                if (isRegisterWaitForSingleObjectFailed)
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed);
                }
                else
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginReportContextFailed);
                }

                // Report error and close the session
                Exception mgdException = new InvalidOperationException(errorMessage);
                Close(mgdException);
            }
        }
        /// <summary>
        /// Creates an instance of the FileSystemContentStream class, opens
        /// the specified file for writing, and returns the IContentReader interface
        /// to it.
        /// </summary>
        /// <param name="path">
        /// The path of the file to be opened for writing.
        /// </param>
        /// <returns>
        /// An IContentWriter for the specified file.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        public IContentWriter GetContentWriter(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            path = NormalizePath(path);

            // If this is true, then the content will be read as bytes
            bool     usingByteEncoding   = false;
            bool     streamTypeSpecified = false;
            Encoding encoding            = ClrFacade.GetDefaultEncoding();
            FileMode filemode            = FileMode.OpenOrCreate;
            bool     suppressNewline     = false;

            // Get the dynamic parameters
            if (DynamicParameters != null)
            {
                // [BUG] Regardless of override DynamicParameters is of type FileSystemContentWriterDynamicParameters
                // StreamContentWriterDynamicParameters dynParams = DynamicParameters as StreamContentWriterDynamicParameters;
                FileSystemContentWriterDynamicParameters dynParams = DynamicParameters as FileSystemContentWriterDynamicParameters;

                if (dynParams != null)
                {
                    usingByteEncoding   = dynParams.AsByteStream;
                    streamTypeSpecified = dynParams.WasStreamTypeSpecified;

                    if (usingByteEncoding && streamTypeSpecified)
                    {
                        WriteWarning(FileSystemProviderStrings.EncodingNotUsed);
                    }

                    if (streamTypeSpecified)
                    {
                        encoding = dynParams.Encoding;
                    }

                    suppressNewline = dynParams.NoNewline.IsPresent;
                }
            }

            StreamContentReaderWriter stream = null;

            ZipFileItemInfo archiveFile;

            if (ItemExists(path))
            {
                archiveFile = GetItemHelper(path);
            }
            else
            {
                // Set-Item should create an item if not exists.
                archiveFile = NewItemHelper(path);
            }

            try
            {
                stream = new ZipFileContentStream(archiveFile, FileMode.Append, encoding, usingByteEncoding, this, false, suppressNewline);
            }
            catch (PathTooLongException pathTooLong)
            {
                WriteError(new ErrorRecord(pathTooLong, "GetContentWriterPathTooLongError", ErrorCategory.InvalidArgument, path));
            }
            catch (FileNotFoundException fileNotFound)
            {
                WriteError(new ErrorRecord(fileNotFound, "GetContentWriterFileNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (DirectoryNotFoundException directoryNotFound)
            {
                WriteError(new ErrorRecord(directoryNotFound, "GetContentWriterDirectoryNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (ArgumentException argException)
            {
                WriteError(new ErrorRecord(argException, "GetContentWriterArgumentError", ErrorCategory.InvalidArgument, path));
            }
            catch (IOException ioException)
            {
                // IOException contains specific message about the error occured and so no need for errordetails.
                WriteError(new ErrorRecord(ioException, "GetContentWriterIOError", ErrorCategory.WriteError, path));
            }
            catch (System.Security.SecurityException securityException)
            {
                WriteError(new ErrorRecord(securityException, "GetContentWriterSecurityError", ErrorCategory.PermissionDenied, path));
            }
            catch (UnauthorizedAccessException unauthorizedAccess)
            {
                WriteError(new ErrorRecord(unauthorizedAccess, "GetContentWriterUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
            }

            return(stream);
        }
예제 #22
0
        internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception exception, Assembly[] assemblies, TypeResolutionState typeResolutionState)
        {
            ExecutionContext context = null;

            exception = null;

            if (typeResolutionState == null)
            {
                // Usings from script scope (and if no script scope, fall back to default 'using namespace system')
                context             = LocalPipeline.GetExecutionContextFromTLS();
                typeResolutionState = TypeResolutionState.GetDefaultUsingState(context);
            }

            // We can do the cache lookup only if we don't define type in the current scope (cache would be invalid in this case).
            var result = typeResolutionState.ContainsTypeDefined(typeName.Name)
                ? null
                : TypeCache.Lookup(typeName, typeResolutionState);

            if (result != null)
            {
                return(result);
            }

            if (typeName.AssemblyName != null)
            {
                result = ResolveAssemblyQualifiedTypeName(typeName, out exception);
                TypeCache.Add(typeName, typeResolutionState, result);
                return(result);
            }

            // Simple typename (no generics, no arrays, no assembly name)
            // We use the following search order, using the specified name (assumed to be fully namespace qualified):
            //
            //     * Search scope table (includes 'using type x = ...' aliases)
            //     * Built in type accelerators (implicit 'using type x = ...' aliases that are effectively in global scope
            //     * typeResolutionState.assemblies, which contains:
            //          - Assemblies with PS types, added by 'using module'
            //          - Assemblies added by 'using assembly'.
            //          For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
            //     * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
            //          IGNORE ambiguity. It mimics PS v4. There are two reasons:
            //          1) If we report ambiguity, we need to fix our caching logic accordingly.
            //             Consider this code
            //                  Add-Type 'public class Q {}' # ok
            //                  Add-Type 'public class Q { }' # get error about the same name
            //                  [Q] # we would get error about ambiguous type, because we added assembly with duplicated type
            //                      # before we can report TYPE_ALREADY_EXISTS error.
            //
            //                  Add-Type 'public class Q2 {}' # ok
            //                  [Q2] # caching Q2 type
            //                  Add-Type 'public class Q2 { }' # get error about the same name
            //                  [Q2] # we don't get an error about ambiguous type, because it's cached already
            //          2) NuGet (VS Package Management console) uses MEF extensibility model.
            //             Different assemblies includes same interface (i.e. NuGet.VisualStudio.IVsPackageInstallerServices),
            //             where they include only methods that they are interested in the interface declaration (result interfaces are different!).
            //             Then, at runtime VS provides an instance. Everything work as far as instance has compatible API.
            //             So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
            //     * User defined type accelerators (rare - interface was never public)
            //
            // If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
            // We must search all using aliases and REPORT an error if there is an ambiguity.

            // If this is TypeDefinition we should not cache anything in TypeCache.
            if (typeName._typeDefinitionAst != null)
            {
                return(typeName._typeDefinitionAst.Type);
            }

            if (context == null)
            {
                context = LocalPipeline.GetExecutionContextFromTLS();
            }

            // Use the explicitly passed-in assembly list when it's specified by the caller.
            // Otherwise, retrieve all currently loaded assemblies.
            var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);
            var isAssembliesExplicitlyPassedIn = assemblies != null;

            result = CallResolveTypeNameWorkerHelper(typeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception);

            if (result != null)
            {
                TypeCache.Add(typeName, typeResolutionState, result);
                return(result);
            }

            if (exception == null)
            {
                foreach (var ns in typeResolutionState.namespaces)
                {
                    var newTypeNameToSearch = ns + "." + typeName.Name;
                    newTypeNameToSearch = typeResolutionState.GetAlternateTypeName(newTypeNameToSearch) ??
                                          newTypeNameToSearch;
                    var newTypeName = new TypeName(typeName.Extent, newTypeNameToSearch);
#if CORECLR
                    if (!isAssembliesExplicitlyPassedIn)
                    {
                        // We called 'ClrFacade.GetAssemblies' to get assemblies. That means the assemblies to search from
                        // are not pre-defined, and thus we have to refetch assembly again based on the new type name.
                        assemList = ClrFacade.GetAssemblies(typeResolutionState, newTypeName);
                    }
#endif
                    var newResult = CallResolveTypeNameWorkerHelper(newTypeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception);

                    if (exception != null)
                    {
                        break;
                    }

                    if (newResult != null)
                    {
                        if (result == null)
                        {
                            result = newResult;
                        }
                        else
                        {
                            exception = new AmbiguousTypeException(typeName, new string[] { result.FullName, newResult.FullName });
                            result    = null;
                            break;
                        }
                    }
                }
            }

            if (exception != null)
            {
                // AmbiguousTypeException is for internal representation only.
                var ambiguousException = exception as AmbiguousTypeException;
                if (ambiguousException != null)
                {
                    exception = new PSInvalidCastException("AmbiguousTypeReference", exception,
                                                           ParserStrings.AmbiguousTypeReference, ambiguousException.TypeName.Name,
                                                           ambiguousException.Candidates[0], ambiguousException.Candidates[1]);
                }
            }

            if (result != null)
            {
                TypeCache.Add(typeName, typeResolutionState, result);
            }

            return(result);
        }
예제 #23
0
 /// <summary>
 /// Load an assembly given its file path.
 /// </summary>
 /// <param name="assemblyPath">The path of the file that contains the manifest of the assembly.</param>
 /// <returns>The loaded assembly.</returns>
 public static Assembly LoadFrom(string assemblyPath)
 {
     return(ClrFacade.LoadFrom(assemblyPath));
 }