/// <summary>
        /// Allow lower integrity applications to send specified window messages
        /// in case we are elevated. Failure is non-fatal and on down-level
        /// platforms this call will result in a no-op.
        /// </summary>
        private void ChangeWindowMessageFilter(WindowMessage message, uint flag)
        {
            // Find the address of ChangeWindowMessageFilter in user32.dll.
            IntPtr user32Module = UnsafeNativeMethods.GetModuleHandle("user32.dll");

            // Get the address of the function. If this fails it means the OS
            // doesn't support this function, in which case we don't
            // need to do anything further.
            IntPtr functionAddress = UnsafeNativeMethods.GetProcAddressNoThrow(
                new HandleRef(null, user32Module),
                "ChangeWindowMessageFilter");

            if (functionAddress != IntPtr.Zero)
            {
                // Convert the function pointer into a callable delegate and then call it
                ChangeWindowMessageFilterNative function = Marshal.GetDelegateForFunctionPointer(
                    functionAddress,
                    typeof(ChangeWindowMessageFilterNative)) as ChangeWindowMessageFilterNative;

                // In order to call the function we need unmanaged code access,
                // because the function is native code.
                (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
                try
                {
                    function(message, flag);
                }
                finally
                {
                    SecurityPermission.RevertAssert();
                }
            }
        }
Esempio n. 2
0
            internal PinnedByteArrayStream(byte [] bits)
            {
                _memoryHandle = GCHandle.Alloc(bits, GCHandleType.Pinned);

                unsafe
                {
                    // Initialize() method demands UnmanagedCode permission, and PinnedByteArrayStream is already marked as critical.

                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //Blessed Assert

                    try
                    {
                        Initialize(
                            (byte *)_memoryHandle.AddrOfPinnedObject(),
                            bits.Length,
                            bits.Length,
                            FileAccess.Read
                            );
                    }
                    finally
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
        private static TraceSource CreateTraceSource(string sourceName)
        {
            // Create the trace source.  Whether or not it will actually
            // trace anything is a decision of the trace source, e.g. it
            // depends on the app.config file settings.

            TraceSource source = new TraceSource(sourceName);

            // If we're attached to the debugger, ensure that at least
            // warnings/errors are getting traced.

            if (source.Switch.Level == SourceLevels.Off
                &&
                AvTrace.IsDebuggerAttached())
            {
                // we need to assert as PT callers under a debugger can invoke this code path
                // with out having the needed permission to peform this action
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
                try
                {
                    source.Switch.Level = SourceLevels.Warning;
                }
                finally
                {
                    SecurityPermission.RevertAssert();
                }
            }

            // returning source after reverting the assert to avoid
            // using exposed elements under the assert
            return(source);
        }
Esempio n. 4
0
        internal static Win32Exception CreateSafeWin32Exception(int error)
        {
            Win32Exception newException = null;
            // Need to assert SecurtiyPermission, otherwise Win32Exception
            // will not be able to get the error message. At this point the right
            // permissions have already been demanded.
            SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);

            securityPermission.Assert();
            try {
                if (error == 0)
                {
                    newException = new Win32Exception();
                }
                else
                {
                    newException = new Win32Exception(error);
                }
            }
            finally {
                SecurityPermission.RevertAssert();
            }

            return(newException);
        }
Esempio n. 5
0
 ShowMessageBoxHelper(
     System.Windows.Window parent,
     string text,
     string title,
     System.Windows.MessageBoxButton buttons,
     System.Windows.MessageBoxImage image
     )
 {
     (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
     try
     {
         // if we have a known parent window set, let's use it when alerting the user.
         if (parent != null)
         {
             System.Windows.MessageBox.Show(parent, text, title, buttons, image);
         }
         else
         {
             System.Windows.MessageBox.Show(text, title, buttons, image);
         }
     }
     finally
     {
         SecurityPermission.RevertAssert();
     }
 }
Esempio n. 6
0
 internal virtual object CreateWebOC()
 {
     (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
     try
     {
         return(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID.WebBrowser))));
     }
     finally
     {
         SecurityPermission.RevertAssert();
     }
 }
Esempio n. 7
0
 private static void PrivilegedStopLogicalOperation()
 {
     _unmanagedCodePermission.Assert();
     try
     {
         Trace.CorrelationManager.StopLogicalOperation();
     }
     finally
     {
         SecurityPermission.RevertAssert();
     }
 }
        private static void Initialise()
        {
            if (null == m_Application)
            {
                try
                {
                    SecurityPermission secper = new SecurityPermission(PermissionState.Unrestricted);
                    secper.Assert();
                    object olApplicationInstance = null;
                    try
                    {
                        olApplicationInstance = Marshal.GetActiveObject("Outlook.Application");
                    }
                    catch (COMException comException)
                    {
                        if ((uint)comException.ErrorCode == 0x800401e3)
                        {
                            Console.WriteLine("No running instance of Outlook found.");
                        }
                    }
                    SecurityPermission.RevertAssert();

                    if (null != olApplicationInstance)
                    {
                        if (olApplicationInstance is Outlook.Application)
                        {
                            Console.WriteLine("Binding to existing Outlook instance.");
                            m_Application = olApplicationInstance as Outlook.Application;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Creating a new Outlook instance.");
                        m_Application      = new Outlook.Application();
                        newOutlookInstance = true;
                    }
                    if (null != m_Application)
                    {
                        m_NameSpace = m_Application.GetNamespace("MAPI");
                    }
                    else
                    {
                        Console.WriteLine("ERROR: Unable to start Outlook!");
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Unable to initialise application object. Error: " + exception.ToString());
                }
            }
        }
        protected override void CheckPermissionsToShowDialog()
        {
            SecurityHelper.DemandFileDialogOpenPermission();

            new UIPermission(UIPermissionWindow.AllWindows).Assert();
            try
            {
                base.CheckPermissionsToShowDialog();
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }
        }
Esempio n. 10
0
        private static string GetCurrentOEMCPEncoding(int code)
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

            sp.Assert();//Blessed Assert
            try
            {
                int cp = UnsafeNativeMethods.GetOEMCP();
                return(CharacterEncoding(cp, code));
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }
        }
Esempio n. 11
0
 ShowMessageBoxHelper(
     IntPtr parentHwnd,
     string text,
     string title,
     System.Windows.MessageBoxButton buttons,
     System.Windows.MessageBoxImage image
     )
 {
     (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
     try
     {
         // NOTE: the last param must always be MessageBoxOptions.None for this to be considered TreatAsSafe
         System.Windows.MessageBox.ShowCore(parentHwnd, text, title, buttons, image, MessageBoxResult.None, MessageBoxOptions.None);
     }
     finally
     {
         SecurityPermission.RevertAssert();
     }
 }
Esempio n. 12
0
        //------------------------------------------------------
        //
        //  Internal Events
        //
        //------------------------------------------------------
        // None
        //------------------------------------------------------
        //
        //  Private Constructors
        //
        //------------------------------------------------------

        #region Private Constructor

        static PackUriHelper()
        {
            // indicate that we want "basic" parsing
            if (!UriParser.IsKnownScheme(System.IO.Packaging.PackUriHelper.UriSchemePack))
            {
                try
                {
                    SecurityPermission permobj = new SecurityPermission(SecurityPermissionFlag.Infrastructure);
                    permobj.Assert(); //BlessedAssert:

                    // Indicate that we want a default hierarchical parser with a registry based authority
                    UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), System.IO.Packaging.PackUriHelper.UriSchemePack, -1);
                }
                finally
                {
                    SecurityPermission.RevertAssert();
                }
            }
        }
Esempio n. 13
0
 internal void FilterCallback(Object sender, AssemblyLoadEventArgs args)
 {
     // This code is reentrant
     lock (_lock)
     {
         // Extract assembly
         Assembly a = args.LoadedAssembly;
         // xmlns cache loads assemblies as reflection only and we cannot inspect these using the code below
         // so we ignore also keeping this first is super important because the first time cost is really high
         // other wise also we cannot do any processing on a reflection only assembly aside from reflection based actions
         if (!a.ReflectionOnly)
         {
             // check if it is in the Gac , this ensures that we eliminate any non GAC assembly which are of no risk
             if (a.GlobalAssemblyCache)
             {
                 object[] aptca = a.GetCustomAttributes(typeof(AllowPartiallyTrustedCallersAttribute), false);
                 // if the dll has APTCA
                 if (aptca.Length > 0 && aptca[0] is AllowPartiallyTrustedCallersAttribute)
                 {
                     string assemblyName = AssemblyNameWithFileVersion(a);
                     // If we are on the disallowed list kill the application domain
                     if (AssemblyOnDisallowedList(assemblyName))
                     {
                         // Kill the application domain
                         UnsafeNativeMethods.ProcessUnhandledException_DLL(SR.Get(SRID.KillBitEnforcedShutdown) + assemblyName);
                         // I want to ensure that the process really dies
                         new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();//BlessedAssert
                         try
                         {
                             System.Environment.Exit(-1);
                         }
                         finally
                         {
                             SecurityPermission.RevertAssert();
                             Debug.Fail("Environment.Exit() failed.");
                         }
                     }
                 }
             }
         }
     }
 }
Esempio n. 14
0
        static DocumentsTrace()
        {
#if DEBUG
            // we are adding console as a listener
            TextWriterTraceListener consoleListener = new TextWriterTraceListener(Console.Out);

            // get the listeners collection
            TraceListenerCollection listeners = null;
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
            try
            {
                listeners = System.Diagnostics.Trace.Listeners;
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }

            // add the console listener
            listeners.Add(consoleListener);
#endif
        }
Esempio n. 15
0
        private void OpenSqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation

            // these should be checked by any caller of this method

            // ensure we have validated and normalized the path before
            Debug.Assert(path != null);
            Debug.Assert(transactionContext != null);

            if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------

            // normalize the provided path
            //   * compress path to remove any occurences of '.' or '..'
            //   * trim whitespace from the beginning and end of the path
            //   * ensure that the path starts with '\\'
            //   * ensure that the path does not start with '\\.\'
            //   * ensure that the path is not longer than Int16.MaxValue
            path = GetFullPathInternal(path);

            // ensure the running code has permission to read/write the file
            DemandAccessPermission(path, access);

            FileFullEaInformation    eaBuffer   = null;
            SecurityQualityOfService qos        = null;
            UnicodeString            objectName = null;

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;

            int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE;

            UInt32 dwCreateOptions     = 0;
            UInt32 dwCreateDisposition = 0;

            System.IO.FileShare shareAccess = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS;
            }

            try
            {
                eaBuffer = new FileFullEaInformation(transactionContext);

                qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous,
                                                   false, false);

                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                //   FILESTREAM attributed column data. We will not surface the internal processing that
                //   takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(path);
                objectName = new UnicodeString(mappedPath);

                UnsafeNativeMethods.OBJECT_ATTRIBUTES oa;
                oa.length                   = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                oa.rootDirectory            = IntPtr.Zero;
                oa.attributes               = (int)UnsafeNativeMethods.Attributes.CaseInsensitive;
                oa.securityDescriptor       = IntPtr.Zero;
                oa.securityQualityOfService = qos;
                oa.objectName               = objectName;

                UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock;

                uint oldMode;
                uint retval = 0;

                UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode);
                try
                {
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n",
                              ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions);

                    retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess,
                                                              ref oa, out ioStatusBlock, ref allocationSize,
                                                              0, shareAccess, dwCreateDisposition, dwCreateOptions,
                                                              eaBuffer, (uint)eaBuffer.Length);
                }
                finally
                {
                    UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case UnsafeNativeMethods.STATUS_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(Res.GetString(Res.SqlFileStream_FileAlreadyInTransaction));

                case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_InvalidParameter));

                case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval);
                    if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile);
                if (fileType != UnsafeNativeMethods.FileType.Disk)
                {
                    hFile.Dispose();
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                //   through current data and then append new data to the end, so we need to tell SQL Server to preserve
                //   the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM,
                                                                      IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED,
                                                                      (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS);
                    uint cbBytesReturned = 0;

                    if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                //   use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign
                //   in that we've done much the same validation as in the FileStream(string path, ...) ctor case
                //   most notably, validating that the handle type corresponds to an on-disk file.
                bool bRevertAssert = false;
                try
                {
                    SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Assert();
                    bRevertAssert = true;

                    System.Diagnostics.Debug.Assert(m_fs == null);
                    m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
                }
                finally
                {
                    if (bRevertAssert)
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }

                if (qos != null)
                {
                    qos.Dispose();
                    qos = null;
                }

                if (objectName != null)
                {
                    objectName.Dispose();
                    objectName = null;
                }
            }
        }
Esempio n. 16
0
        /// <include file='doc\CodeCompiler.uex' path='docs/doc[@for="CodeCompiler.FromFileBatch"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Compiles the specified files using the specified options, and returns the
        ///       results from the compilation.
        ///    </para>
        /// </devdoc>
        protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames)
        {
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            string outputFile = null;
            int    retValue   = 0;

            CompilerResults    results = new CompilerResults(options.TempFiles);
            SecurityPermission perm1   = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);

            perm1.Assert();
            try {
                results.Evidence = options.Evidence;
            }
            finally {
                SecurityPermission.RevertAssert();
            }
            bool createdEmptyAssembly = false;

            if (options.OutputAssembly == null || options.OutputAssembly.Length == 0)
            {
                string extension = (options.GenerateExecutable) ? "exe" : "dll";
                options.OutputAssembly = results.TempFiles.AddExtension(extension, !options.GenerateInMemory);

                // Create an empty assembly.  This is so that the file will have permissions that
                // we can later access with our current credential.  If we don't do this, the compiler
                // could end up creating an assembly that we cannot open (bug ASURT 83492)
                new FileStream(options.OutputAssembly, FileMode.Create, FileAccess.ReadWrite).Close();
                createdEmptyAssembly = true;
            }

            results.TempFiles.AddExtension("pdb");


            string args = CmdArgsFromParameters(options) + " " + JoinStringArray(fileNames, " ");

            // Use a response file if the compiler supports it
            string responseFileArgs = GetResponseFileCmdArgs(options, args);
            string trueArgs         = null;

            if (responseFileArgs != null)
            {
                trueArgs = args;
                args     = responseFileArgs;
            }

            Compile(options, Executor.GetRuntimeInstallDirectory(), CompilerName, args, ref outputFile, ref retValue, trueArgs);

            results.NativeCompilerReturnValue = retValue;

            // only look for errors/warnings if the compile failed or the caller set the warning level
            if (retValue != 0 || options.WarningLevel > 0)
            {
                FileStream outputStream = new FileStream(outputFile, FileMode.Open,
                                                         FileAccess.Read, FileShare.ReadWrite);
                try {
                    if (outputStream.Length > 0)
                    {
                        // The output of the compiler is in UTF8 (bug 54925)
                        StreamReader sr = new StreamReader(outputStream, Encoding.UTF8);
                        string       line;
                        do
                        {
                            line = sr.ReadLine();
                            if (line != null)
                            {
                                results.Output.Add(line);

                                ProcessCompilerOutputLine(results, line);
                            }
                        } while (line != null);
                    }
                }
                finally {
                    outputStream.Close();
                }

                // Delete the empty assembly if we created one
                if (retValue != 0 && createdEmptyAssembly)
                {
                    File.Delete(options.OutputAssembly);
                }
            }

            if (!results.Errors.HasErrors && options.GenerateInMemory)
            {
                FileStream fs = new FileStream(options.OutputAssembly, FileMode.Open, FileAccess.Read, FileShare.Read);
                try {
                    int    fileLen = (int)fs.Length;
                    byte[] b       = new byte[fileLen];
                    fs.Read(b, 0, fileLen);
                    SecurityPermission perm = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
                    perm.Assert();
                    try {
                        results.CompiledAssembly = Assembly.Load(b, null, options.Evidence);
                    }
                    finally {
                        SecurityPermission.RevertAssert();
                    }
                }
                finally {
                    fs.Close();
                }
            }
            else
            {
                results.PathToAssembly = options.OutputAssembly;
            }

            return(results);
        }
Esempio n. 17
0
        private ArrayList SaveSubStreams(UIElement element)
        {
            ArrayList subStreams = null;

#pragma warning disable 618
            if ((element != null) && (element.PersistId != 0))
#pragma warning restore 618
            {
                LocalValueEnumerator dpEnumerator = element.GetLocalValueEnumerator();

                while (dpEnumerator.MoveNext())
                {
                    LocalValueEntry           localValueEntry = (LocalValueEntry)dpEnumerator.Current;
                    FrameworkPropertyMetadata metadata        = localValueEntry.Property.GetMetadata(element.DependencyObjectType) as FrameworkPropertyMetadata;

                    if (metadata == null)
                    {
                        continue;
                    }

                    // To be saved, a DP should have the correct metadata and NOT be an expression or data bound.
                    // Since Bind inherits from Expression, the test for Expression will suffice.
                    // NOTE: we do not journal expression. So we should let parser restore it in BamlRecordReader.SetDependencyValue.
                    // Please see Windows OS
                    if (metadata.Journal && (!(localValueEntry.Value is Expression)))
                    {
                        // These properties should not be journaled.
                        //

                        if (object.ReferenceEquals(localValueEntry.Property, Frame.SourceProperty))
                        {
                            continue;
                        }

                        if (subStreams == null)
                        {
                            subStreams = new ArrayList(3);
                        }

                        object currentValue = element.GetValue(localValueEntry.Property);
                        byte[] bytes        = null;

                        if ((currentValue != null) && !(currentValue is Uri))
                        {
                            // Convert the value of the DP into a byte array
                            MemoryStream byteStream = new MemoryStream();
                            new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
                            try
                            {
                                this.Formatter.Serialize(byteStream, currentValue);
                            }
                            finally
                            {
                                SecurityPermission.RevertAssert();
                            }

                            bytes = byteStream.ToArray();
                            // Dispose the stream
                            ((IDisposable)byteStream).Dispose( );
                        }

                        // Save the byte array by the property name
                        subStreams.Add(new SubStream(localValueEntry.Property.Name, bytes));
                    }
                }
            }

            return(subStreams);
        }
Esempio n. 18
0
        internal void OpenFile(string fileName)
        {
            NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES();
            try
            {
                unsafe
                {
                    // Disable PREsharp warning about not calling Marshal.GetLastWin32Error,
                    // because we already check the handle for invalid value and
                    // we are not particularly interested in specific Win32 error.

#pragma warning disable 6523

                    long size;

                    using (SafeFileHandle fileHandle = UnsafeNativeMethods.CreateFile(
                               fileName,
                               NativeMethods.GENERIC_READ,
                               NativeMethods.FILE_SHARE_READ,
                               null,
                               NativeMethods.OPEN_EXISTING,
                               0,
                               IntPtr.Zero
                               ))
                    {
                        if (fileHandle.IsInvalid)
                        {
                            Util.ThrowWin32Exception(Marshal.GetLastWin32Error(), fileName);
                        }

                        UnsafeNativeMethods.LARGE_INTEGER fileSize = new UnsafeNativeMethods.LARGE_INTEGER();
                        if (!UnsafeNativeMethods.GetFileSizeEx(fileHandle, ref fileSize))
                        {
                            throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                        }

                        size = (long)fileSize.QuadPart;
                        if (size == 0)
                        {
                            throw new FileFormatException(new Uri(fileName));
                        }

                        _mappingHandle = UnsafeNativeMethods.CreateFileMapping(
                            fileHandle,
                            sa,
                            UnsafeNativeMethods.PAGE_READONLY,
                            0,
                            0,
                            null);
                    }

                    if (_mappingHandle.IsInvalid)
                    {
                        throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                    }

                    _viewHandle = UnsafeNativeMethods.MapViewOfFileEx(_mappingHandle, UnsafeNativeMethods.FILE_MAP_READ, 0, 0, IntPtr.Zero, IntPtr.Zero);
                    if (_viewHandle.IsInvalid)
                    {
                        throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                    }

#pragma warning restore 6523

                    // Initialize() method demands UnmanagedCode permission, and OpenFile() is already marked as critical.

                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //Blessed Assert

                    try
                    {
                        Initialize((byte *)_viewHandle.Memory, size, size, FileAccess.Read);
                    }
                    finally
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            finally
            {
                sa.Release();
                sa = null;
            }
        }
Esempio n. 19
0
        private void StartRaisingEvents()
        {
            //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
            if (this.disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            try {
                new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                {
                    throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // If we're called when "Initializing" is true, set enabled to true
            if (IsSuspended())
            {
                enabled = true;
                return;
            }

            if (!readGranted)
            {
                string fullPath;
                // Consider asserting path discovery permission here.
                fullPath = System.IO.Path.GetFullPath(directory);

                FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, fullPath);
                permission.Demand();
                readGranted = true;
            }


            // If we're attached, don't do anything.
            if (!IsHandleInvalid)
            {
                return;
            }

            // Create handle to directory being monitored
            directoryHandle = NativeMethods.CreateFile(directory,                               // Directory name
                                                       UnsafeNativeMethods.FILE_LIST_DIRECTORY, // access (read-write) mode
                                                       UnsafeNativeMethods.FILE_SHARE_READ |
                                                       UnsafeNativeMethods.FILE_SHARE_DELETE |
                                                       UnsafeNativeMethods.FILE_SHARE_WRITE,     // share mode
                                                       null,                                     // security descriptor
                                                       UnsafeNativeMethods.OPEN_EXISTING,        // how to create
                                                       UnsafeNativeMethods.FILE_FLAG_BACKUP_SEMANTICS |
                                                       UnsafeNativeMethods.FILE_FLAG_OVERLAPPED, // file attributes
                                                       new SafeFileHandle(IntPtr.Zero, false)    // file with attributes to copy
                                                       );

            if (IsHandleInvalid)
            {
                throw new FileNotFoundException(SR.GetString(SR.FSW_IOError, directory));
            }

            stopListening = false;
            // Start ignoring all events that were initiated before this.
            Interlocked.Increment(ref currentSession);

            // Attach handle to thread pool

            //SECREVIEW: At this point at least FileIOPermission has already been demanded.
            SecurityPermission secPermission = new SecurityPermission(PermissionState.Unrestricted);

            secPermission.Assert();
            try {
                ThreadPool.BindHandle(directoryHandle);
            }
            finally {
                SecurityPermission.RevertAssert();
            }
            enabled = true;

            // Setup IO completion port
            Monitor(null);
        }
Esempio n. 20
0
        private CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (fileNames == null)
            {
                throw new ArgumentNullException("fileNames");
            }

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            string outputFile = null;
            int    retValue   = 0;
            var    results    = new CompilerResults(options.TempFiles);
            var    perm1      = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);

            perm1.Assert();
            try {
#pragma warning disable 618
                results.Evidence = options.Evidence;
#pragma warning restore 618
            }
            finally {
                SecurityPermission.RevertAssert();
            }

            bool createdEmptyAssembly = false;
            if (options.OutputAssembly == null || options.OutputAssembly.Length == 0)
            {
                string extension = (options.GenerateExecutable) ? "exe" : "dll";
                options.OutputAssembly = results.TempFiles.AddExtension(extension, !options.GenerateInMemory);

                // Create an empty assembly.  This is so that the file will have permissions that
                // we can later access with our current credential. If we don't do this, the compiler
                // could end up creating an assembly that we cannot open.
                new FileStream(options.OutputAssembly, FileMode.Create, FileAccess.ReadWrite).Close();
                createdEmptyAssembly = true;
            }

            var pdbname = "pdb";

            // Don't delete pdbs when debug=false but they have specified pdbonly.
            if (options.CompilerOptions != null &&
                -1 != CultureInfo.InvariantCulture.CompareInfo.IndexOf(options.CompilerOptions, "/debug:pdbonly", CompareOptions.IgnoreCase))
            {
                results.TempFiles.AddExtension(pdbname, true);
            }
            else
            {
                results.TempFiles.AddExtension(pdbname);
            }

            string args = GetCompilationArgumentString(options) + " " + JoinStringArray(fileNames, " ");

            // Use a response file if the compiler supports it
            string responseFileArgs = GetResponseFileCmdArgs(options, args);
            string trueArgs         = null;
            if (responseFileArgs != null)
            {
                trueArgs = args;
                args     = responseFileArgs;
            }

            // Appending TTL to the command line arguments.
            if (_providerOptions.CompilerServerTimeToLive > 0)
            {
                args = string.Format("/shared /keepalive:\"{0}\" {1}", _providerOptions.CompilerServerTimeToLive, args);
            }

            Compile(options,
                    CompilerName,
                    args,
                    ref outputFile,
                    ref retValue);

            results.NativeCompilerReturnValue = retValue;

            // only look for errors/warnings if the compile failed or the caller set the warning level
            if (retValue != 0 || options.WarningLevel > 0)
            {
                // The output of the compiler is in UTF8
                string[] lines        = ReadAllLines(outputFile, Encoding.UTF8, FileShare.ReadWrite);
                bool     replacedArgs = false;
                foreach (string line in lines)
                {
                    if (!replacedArgs && trueArgs != null && line.Contains(args))
                    {
                        replacedArgs = true;
                        var outputLine = string.Format("{0}>{1} {2}",
                                                       Environment.CurrentDirectory,
                                                       CompilerName,
                                                       trueArgs);
                        results.Output.Add(outputLine);
                    }
                    else
                    {
                        results.Output.Add(line);
                    }

                    ProcessCompilerOutputLine(results, line);
                }

                // Delete the empty assembly if we created one
                if (retValue != 0 && createdEmptyAssembly)
                {
                    File.Delete(options.OutputAssembly);
                }
            }

            if (retValue != 0 || results.Errors.HasErrors || !options.GenerateInMemory)
            {
                results.PathToAssembly = options.OutputAssembly;
                return(results);
            }

            // Read assembly into memory:
            byte[] assemblyBuff = File.ReadAllBytes(options.OutputAssembly);

            // Read symbol file into memory and ignore any errors that may be encountered:
            // (This functionality was added in NetFx 4.5, errors must be ignored to ensure compatibility)
            byte[] symbolsBuff = null;
            try {
                string symbFileName = options.TempFiles.BasePath + "." + pdbname;

                if (File.Exists(symbFileName))
                {
                    symbolsBuff = File.ReadAllBytes(symbFileName);
                }
            }
            catch {
                symbolsBuff = null;
            }

            // Now get permissions and load assembly from buffer into the CLR:
            var perm = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
            perm.Assert();

            try {
#pragma warning disable 618 // Load with evidence is obsolete - this warning is passed on via the options.Evidence property
                results.CompiledAssembly = Assembly.Load(assemblyBuff, symbolsBuff, options.Evidence);
#pragma warning restore 618
            }
            finally {
                SecurityPermission.RevertAssert();
            }

            return(results);
        }
Esempio n. 21
0
        ///
        /// Begin a download
        ///
        internal static void BeginDownload(
            BitmapDecoder decoder,
            Uri uri,
            RequestCachePolicy uriCachePolicy,
            Stream stream
            )
        {
            lock (_syncLock)
            {
                if (!_thread.IsAlive)
                {
                    _thread.IsBackground = true;
                    _thread.Start();
                }
            }

            QueueEntry entry;

            // If there is already a download for this uri, just add the decoder to the list
            if (uri != null)
            {
                lock (_syncLock)
                {
                    if (_uriTable[uri] != null)
                    {
                        entry = (QueueEntry)_uriTable[uri];
                        entry.decoders.Add(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(decoder));
            }

            entry.inputUri    = uri;
            entry.inputStream = stream;

            string cacheFolder = MS.Win32.WinInet.InternetCacheFolder.LocalPath;
            bool   passed      = false;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
            try
            {
                // Get the file path
                StringBuilder tmpFileName = new StringBuilder(NativeMethods.MAX_PATH);
                MS.Win32.UnsafeNativeMethods.GetTempFileName(cacheFolder, "WPF", 0, tmpFileName);

                try
                {
                    string         pathToUse  = tmpFileName.ToString();
                    SafeFileHandle fileHandle = MS.Win32.UnsafeNativeMethods.CreateFile(
                        pathToUse,
                        NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, /* dwDesiredAccess */
                        0,                                                        /* dwShare */
                        null,                                                     /* lpSecurityAttributes */
                        NativeMethods.CREATE_ALWAYS,                              /* dwCreationDisposition */
                        NativeMethods.FILE_ATTRIBUTE_TEMPORARY |
                        NativeMethods.FILE_FLAG_DELETE_ON_CLOSE,                  /* dwFlagsAndAttributes */
                        IntPtr.Zero                                               /* hTemplateFile */
                        );

                    if (fileHandle.IsInvalid)
                    {
                        throw new Win32Exception();
                    }

                    entry.outputStream = new FileStream(fileHandle, FileAccess.ReadWrite);
                    entry.streamPath   = pathToUse;
                    passed             = true;
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }

            if (!passed)
            {
                throw new IOException(SR.Get(SRID.Image_CannotCreateTempFile));
            }

            entry.readBuffer    = new byte[READ_SIZE];
            entry.contentLength = -1;
            entry.contentType   = string.Empty;
            entry.lastPercent   = 0;

            // Add the entry to the table if we know the uri
            if (uri != null)
            {
                lock (_syncLock)
                {
                    _uriTable[uri] = entry;
                }
            }

            if (stream == null)
            {
                entry.webRequest = WpfWebRequestHelper.CreateRequest(uri);
                if (uriCachePolicy != null)
                {
                    entry.webRequest.CachePolicy = uriCachePolicy;
                }

                entry.webRequest.BeginGetResponse(_responseCallback, entry);
            }
            else
            {
                _workQueue.Enqueue(entry);
                // Signal
                _waitEvent.Set();
            }
        }
Esempio n. 22
0
        ///
        /// Begin a download
        ///
        internal static void BeginDownload(
            BitmapDecoder decoder,
            Uri uri,
            RequestCachePolicy uriCachePolicy,
            Stream stream
            )
        {
            lock (_syncLock)
            {
                if (!_thread.IsAlive)
                {
                    _thread.IsBackground = true;
                    _thread.Start();
                }
            }

            QueueEntry entry;

            // If there is already a download for this uri, just add the decoder to the list
            if (uri != null)
            {
                lock (_syncLock)
                {
                    if (_uriTable[uri] != null)
                    {
                        entry = (QueueEntry)_uriTable[uri];
                        entry.decoders.Add(new WeakReference(decoder));

                        return;
                    }
                }
            }

            entry          = new QueueEntry();
            entry.decoders = new List <WeakReference>();

            lock (_syncLock)
            {
                entry.decoders.Add(new WeakReference(decoder));
            }

            entry.inputUri    = uri;
            entry.inputStream = stream;

            string cacheFolder = MS.Win32.WinInet.InternetCacheFolder.LocalPath;
            bool   passed      = false;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
            try
            {
                // Get the file path
                StringBuilder tmpFileName = new StringBuilder(NativeMethods.MAX_PATH);
                MS.Win32.UnsafeNativeMethods.GetTempFileName(cacheFolder, "WPF", 0, tmpFileName);

                try
                {
                    string         pathToUse  = tmpFileName.ToString();
                    SafeFileHandle fileHandle = MS.Win32.UnsafeNativeMethods.CreateFile(
                        pathToUse,
                        NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, /* dwDesiredAccess */
                        0,                                                        /* dwShare */
                        null,                                                     /* lpSecurityAttributes */
                        NativeMethods.CREATE_ALWAYS,                              /* dwCreationDisposition */
                        NativeMethods.FILE_ATTRIBUTE_TEMPORARY |
                        NativeMethods.FILE_FLAG_DELETE_ON_CLOSE,                  /* dwFlagsAndAttributes */
                        IntPtr.Zero                                               /* hTemplateFile */
                        );

                    if (fileHandle.IsInvalid)
                    {
                        throw new Win32Exception();
                    }

                    entry.outputStream = new FileStream(fileHandle, FileAccess.ReadWrite);
                    entry.streamPath   = pathToUse;
                    passed             = true;
                }
                catch (Exception e)
                {
                    if (CriticalExceptions.IsCriticalException(e))
                    {
                        throw;
                    }
                }
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }

            if (!passed)
            {
                throw new IOException(SR.Get(SRID.Image_CannotCreateTempFile));
            }

            entry.readBuffer    = new byte[READ_SIZE];
            entry.contentLength = -1;
            entry.contentType   = string.Empty;
            entry.lastPercent   = 0;

            // Add the entry to the table if we know the uri
            if (uri != null)
            {
                lock (_syncLock)
                {
                    _uriTable[uri] = entry;
                }
            }

            if (stream == null)
            {
                bool fElevate = false;
                if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
                {
                    SecurityHelper.BlockCrossDomainForHttpsApps(uri);

                    // In this case we first check to see if the consumer has media permissions for
                    // safe media (Site of Origin + Cross domain), if it
                    // does we assert and run the code that requires the assert
                    if (SecurityHelper.CallerHasMediaPermission(MediaPermissionAudio.NoAudio,
                                                                MediaPermissionVideo.NoVideo,
                                                                MediaPermissionImage.SafeImage))
                    {
                        fElevate = true;
                    }
                }

                // This is the case where we are accessing an http image from an http site and we have media permission
                if (fElevate)
                {
                    (new WebPermission(NetworkAccess.Connect, BindUriHelper.UriToString(uri))).Assert(); // BlessedAssert
                }
                try
                {
                    entry.webRequest = WpfWebRequestHelper.CreateRequest(uri);
                    if (uriCachePolicy != null)
                    {
                        entry.webRequest.CachePolicy = uriCachePolicy;
                    }
                }
                finally
                {
                    if (fElevate)
                    {
                        WebPermission.RevertAssert();
                    }
                }

                entry.webRequest.BeginGetResponse(_responseCallback, entry);
            }
            else
            {
                _workQueue.Enqueue(entry);
                // Signal
                _waitEvent.Set();
            }
        }
Esempio n. 23
0
        private void OnCopy(object sender, ExecutedRoutedEventArgs e)
        {
            if (HasSelection && _selectionRect.Width > 0 && _selectionRect.Height > 0)
            {
                //Copy to clipboard
                IDataObject dataObject;
                string      textString = GetText();
                object      bmp        = null;

                bool supportImageCopy = false;

                if (_scope is DocumentGrid && ((DocumentGrid)_scope).DocumentViewerOwner is DocumentApplicationDocumentViewer)
                {
                    // This is XPSViewer, make sure it is user initiated
                    if (!e.UserInitiated && !HasRubberBandCopyPermissions())
                    {
                        return;
                    }
                    supportImageCopy = true;
                }
                else
                {
                    //Outside of XPSViewer, support image copy in full trust only
                    supportImageCopy = HasRubberBandCopyPermissions();
                }

                if (supportImageCopy)
                {
                    bmp = SystemDrawingHelper.GetBitmapFromBitmapSource(GetImage());
                }

                (new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert
                try
                {
                    dataObject = new DataObject();
                    // Order of data is irrelevant, the pasting application will determine format
                    dataObject.SetData(DataFormats.Text, textString, true);
                    dataObject.SetData(DataFormats.UnicodeText, textString, true);
                    if (bmp != null)
                    {
                        dataObject.SetData(DataFormats.Bitmap, bmp, true);
                    }
                }
                finally
                {
                    UIPermission.RevertAssert();
                }


                PermissionSet ps = new PermissionSet(PermissionState.None);
                ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                ps.AddPermission(new UIPermission(UIPermissionClipboard.AllClipboard));
                ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));

                if (supportImageCopy)
                {
                    CodeAccessPermission mediaAccessPermission = SecurityHelper.CreateMediaAccessPermission(null);
                    ps.AddPermission(mediaAccessPermission);
                }

                ps.Assert(); // BlessedAssert

                try
                {
                    Clipboard.SetDataObject(dataObject, true);
                }
                catch (System.Runtime.InteropServices.ExternalException)
                {
                    // Clipboard is failed to set the data object.
                    return;
                }
                finally
                {
                    SecurityPermission.RevertAssert();
                }
            }
        }
Esempio n. 24
0
        private object OnUnregisterTextStore(object arg)
        {
            UnsafeNativeMethods.ITfContext context;
            UnsafeNativeMethods.ITfSource  source;

            if ((_threadManager == null) || (_threadManager.Value == null))
            {
                return(null);
            }

            SecurityPermission secperm   = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            TextStore          textstore = (TextStore)arg;

            // We don't have to release Dispatcher.
            // These Cicero COM calls could be marshalled when UnregisterTextStore is called from
            // TextEditor's Finalizer through TextStore.OnDetach. GC Thread does not take Dispatcher.
            if (textstore.ThreadFocusCookie != UnsafeNativeMethods.TF_INVALID_COOKIE)
            {
                source = _threadManager.Value as UnsafeNativeMethods.ITfSource;
                source.UnadviseSink(textstore.ThreadFocusCookie);
                textstore.ThreadFocusCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
            }

            textstore.DocumentManager.GetBase(out context);
            if (context != null)
            {
                if (textstore.EditSinkCookie != UnsafeNativeMethods.TF_INVALID_COOKIE)
                {
                    source = context as UnsafeNativeMethods.ITfSource;
                    source.UnadviseSink(textstore.EditSinkCookie);
                    textstore.EditSinkCookie = UnsafeNativeMethods.TF_INVALID_COOKIE;
                }
                Marshal.ReleaseComObject(context);
            }

            secperm.Assert();
            try
            {
                textstore.DocumentManager.Pop(UnsafeNativeMethods.PopFlags.TF_POPF_ALL);
            }
            finally
            {
                SecurityPermission.RevertAssert();
            }
            Marshal.ReleaseComObject(textstore.DocumentManager);
            textstore.DocumentManager = null;

            Debug.Assert(_registeredtextstorecount > 0, "Overrelease TextStore!");
            _registeredtextstorecount--;

            // If Dispatcher is finished and the last textstore
            // is unregistered, we don't need ThreadManager any more. Deactivate and release it.
            // We keep ThreadManager active as long as Dispatcher is alive even if
            // _registeredtextstorecount is 0.
            if (_isDispatcherShutdownFinished && (_registeredtextstorecount == 0))
            {
                DeactivateThreadManager();
            }

            return(null);
        }