public Clerk(string compensator, string description, CompensatorOptions flags)
 {
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     this.Init(compensator, description, flags);
 }
Beispiel #2
0
        public void RunApp(string FileName, string arg)
        {
            SecurityPermission SP = new SecurityPermission(SecurityPermissionFlag.AllFlags);
            SP.Assert();

            //ProcessStartInfo process = new ProcessStartInfo("cmd", "/c " + FileName ));
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            //process.StartInfo.UseShellExecute = false;
            //process.StartInfo.RedirectStandardOutput = true;
            //process.StartInfo.RedirectStandardError = true;
            //process.StartInfo.CreateNoWindow = true;
            process.StartInfo.FileName = FileName;
            process.StartInfo.Arguments = arg;
            process.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(FileName);

            //Vista or higher check
            if (System.Environment.OSVersion.Version.Major >= 6)
                process.StartInfo.Verb = "runas";

            try
            {
                process.Start();
                process.WaitForExit();
                process.Close();
            }
            catch (InvalidOperationException)
            {
                //e.ExceptionObject.ToString();
            }
        }
        public static void SetAppDomainData()
        {
            SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
            sp.Assert();

            AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
        }
 public ClerkMonitor()
 {
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     this._monitor = new CrmMonitor();
     this._version = 0;
 }
 public Clerk(Type compensator, string description, CompensatorOptions flags)
 {
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     this.ValidateCompensator(compensator);
     string str = "{" + Marshal.GenerateGuidForType(compensator) + "}";
     this.Init(str, description, flags);
 }
Beispiel #6
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="evidence"></param>
 /// <returns></returns>
 public static Assembly ReadAssembly(Stream stream, Evidence evidence)
 {
     SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence);
     securityPermission.Assert();
     int num = (int)stream.Length;
     byte[] array = new byte[num];
     stream.Read(array, 0, num);
     try
     {
         return Assembly.Load(array, null, evidence);
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
 }
        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;
        }
        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;

            CompilerResults results = new CompilerResults(options.TempFiles);
            SecurityPermission 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;
            }

#if FEATURE_PAL
            string pdbname = "ildb";
#else
            string pdbname = "pdb";
#endif
            
            // 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 = 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,
                RedistVersionInfo.GetCompilerPath(provOptions, CompilerName),
                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) {

                // The output of the compiler is in UTF8
                string [] lines = ReadAllLines(outputFile, Encoding.UTF8, FileShare.ReadWrite);
                foreach (string line in lines) {
                    results.Output.Add(line);

                    ProcessCompilerOutputLine(results, line);
                }

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

            if (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 mempory 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:
            SecurityPermission 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;
        }
Beispiel #9
0
		/// <summary>
		/// Retrieve the order in which columns appear
		/// </summary>
		/// <returns>Current display order of column indices</returns>
		protected int[] GetColumnOrder()
		{
			IntPtr lPar	= Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);
			SecurityPermission perm = new
				SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

			// The method itself is attached with the security permission 
			// Deny for unmanaged code, which will override
			// the Assert permission in this stack frame.
			perm.Assert();

			IntPtr res = NativeMethods.SendMessage(Handle, NativeMethods.GetColumnOrderArray, new IntPtr(Columns.Count), lPar);
			if (res.ToInt32() == 0)	// Something went wrong
			{
				Marshal.FreeHGlobal(lPar);
				return null;
			}

			int	[] order = new int[Columns.Count];
			Marshal.Copy(lPar, order, 0, Columns.Count);

			Marshal.FreeHGlobal(lPar);

			return order;
		}
        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(); 
            }
        } 
        private const int _COMPlusExceptionCode = unchecked((int)0xe0524f54);   // Win32 exception code for COM+ exceptions

        internal virtual String InternalToString()
        {
            try 
            {
                SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
                sp.Assert();
            }
            catch  
            {
            }
            return ToString();
        }
		internal virtual string InternalToString()
		{
			try
			{
				SecurityPermission securityPermission = new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
				securityPermission.Assert();
			}
			catch
			{
			}
			bool needFileLineInfo = true;
			return this.ToString(needFileLineInfo);
		}
Beispiel #13
0
        [System.Security.SecurityCritical]  // auto-generated
        internal virtual String InternalToString()
        {
            try 
            {
#pragma warning disable 618
                SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
#pragma warning restore 618
                sp.Assert();
            }
            catch  
            {
                //under normal conditions there should be no exceptions
                //however if something wrong happens we still can call the usual ToString
            }

            // Get the current stack trace string.  On CoreCLR we don't bother
            // to try and include file/line-number information because all AppDomains
            // are sandboxed, and so this won't succeed in most (or all) cases.  Therefore the
            // Demand and exception overhead is a waste.
            // We currently have some bugs in watson bucket generation where the SecurityException
            // here causes us to lose saved bucket parameters.  By not even doing the demand
            // we avoid those problems (although there are deep underlying problems that need to
            // be fixed there - relying on this to avoid problems is incomplete and brittle).
            bool fGetFileLineInfo = true;
#if FEATURE_CORECLR
            fGetFileLineInfo = false;
#endif
            return ToString(fGetFileLineInfo, true);
        }
        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;

            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.
                new FileStream(options.OutputAssembly, FileMode.Create, FileAccess.ReadWrite).Close();
                createdEmptyAssembly = true;
            }

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

            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
                        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;
        }
 public void InstallAssembly(RegistrationConfig regConfig, object obSync)
 {
     Assembly asm = null;
     ApplicationSpec spec = null;
     CatalogSync sync = null;
     bool flag = false;
     bool flag2 = false;
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     try
     {
         permission.Demand();
         permission.Assert();
         ICatalogObject app = null;
         this.PrepArguments(regConfig);
         asm = this.NewLoadAssembly(regConfig.AssemblyFile);
         spec = new ApplicationSpec(asm, regConfig);
         if (spec.ConfigurableTypes == null)
         {
             regConfig.Application = null;
             regConfig.TypeLibrary = null;
         }
         else
         {
             if (obSync != null)
             {
                 if (!(obSync is CatalogSync))
                 {
                     throw new ArgumentException(Resource.FormatString("Err_obSync"));
                 }
                 sync = (CatalogSync) obSync;
             }
             this.PrepDriver(ref spec);
             string message = string.Empty;
             if (!this.ValidateBitness(spec, out message))
             {
                 throw new RegistrationException(message);
             }
             if ((regConfig.InstallationFlags & InstallationFlags.Register) != InstallationFlags.Default)
             {
                 flag = !this.IsAssemblyRegistered(spec);
                 this.ClassicRegistration(spec.Assembly);
                 if ((regConfig.InstallationFlags & InstallationFlags.ExpectExistingTypeLib) != InstallationFlags.Default)
                 {
                     RegisterTypeLibrary(spec.TypeLib);
                 }
                 else
                 {
                     flag2 = true;
                     GenerateTypeLibrary(spec.Assembly, spec.TypeLib, new Report(this.ReportWarning));
                 }
             }
             if (((regConfig.InstallationFlags & InstallationFlags.Install) != InstallationFlags.Default) && (spec.ConfigurableTypes != null))
             {
                 if ((regConfig.InstallationFlags & InstallationFlags.CreateTargetApplication) != InstallationFlags.Default)
                 {
                     app = this.CreateApplication(spec, true);
                 }
                 else if ((regConfig.InstallationFlags & InstallationFlags.FindOrCreateTargetApplication) != InstallationFlags.Default)
                 {
                     app = this.FindOrCreateApplication(spec, (regConfig.InstallationFlags & InstallationFlags.ReconfigureExistingApplication) != InstallationFlags.Default);
                 }
                 this.InstallTypeLibrary(spec);
                 if (sync != null)
                 {
                     sync.Set();
                 }
             }
             if (((regConfig.InstallationFlags & InstallationFlags.Configure) != InstallationFlags.Default) && (spec.ConfigurableTypes != null))
             {
                 this.ConfigureComponents(spec);
                 if (sync != null)
                 {
                     sync.Set();
                 }
             }
             if (app != null)
             {
                 this.PostProcessApplication(app, spec);
             }
             this.CleanupDriver();
         }
     }
     catch (Exception exception)
     {
         if ((exception is NullReferenceException) || (exception is SEHException))
         {
             throw;
         }
         if (((exception is SecurityException) || (exception is UnauthorizedAccessException)) || ((exception.InnerException != null) && ((exception.InnerException is SecurityException) || (exception.InnerException is UnauthorizedAccessException))))
         {
             exception = new RegistrationException(Resource.FormatString("Reg_Unauthorized"), exception);
         }
         if (flag && (null != asm))
         {
             try
             {
                 this.ClassicUnregistration(asm);
             }
             catch (Exception exception2)
             {
                 if ((exception2 is NullReferenceException) || (exception2 is SEHException))
                 {
                     throw;
                 }
             }
         }
         if (flag2 && (null != asm))
         {
             try
             {
                 this.UnregisterTypeLib(asm);
             }
             catch (Exception exception3)
             {
                 if ((exception3 is NullReferenceException) || (exception3 is SEHException))
                 {
                     throw;
                 }
             }
         }
         throw exception;
     }
 }
Beispiel #16
0
        private void rtfcontrol_Load(object sender, System.EventArgs e)
        {
            //new FileIOPermission(PermissionState.Unrestricted).Assert();
            PrincipalPermission P = new PrincipalPermission(PermissionState.Unrestricted);

            if(!P.IsUnrestricted())
                Msg("Assigning Principal failed!");
            else
                Msg("Assigning Principal passed!!");

            SecurityPermission SP = new SecurityPermission(PermissionState.Unrestricted);

            if(!SP.IsUnrestricted())
                Msg("Assigning SecurityPermission failed!");
            else
                Msg("Assigning SecurityPermission passed!!");
            try
            {
                SP.Assert();
            }
            catch(Exception Err)
            {
                throw new Exception(Err.Message,Err.InnerException);
            }

            ListViewItem LVI = listView1.Items.Add(System.DateTime.Now.ToShortTimeString());
            LVI.SubItems.Add("Contacting Server please wait...");
            CodeAccessPermission.RevertAssert();
        }
 public void UninstallAssembly(RegistrationConfig regConfig, object obSync)
 {
     CatalogSync sync = null;
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     if (obSync != null)
     {
         if (!(obSync is CatalogSync))
         {
             throw new ArgumentException(Resource.FormatString("Err_obSync"));
         }
         sync = (CatalogSync) obSync;
     }
     Assembly asm = this.NewLoadAssembly(regConfig.AssemblyFile);
     ApplicationSpec spec = new ApplicationSpec(asm, regConfig);
     if (spec.ConfigurableTypes != null)
     {
         this.PrepDriver(ref spec);
         if (spec.ConfigurableTypes != null)
         {
             ICatalogObject obj2 = this.FindApplication(this._appColl, spec);
             if (obj2 == null)
             {
                 throw new RegistrationException(Resource.FormatString("Reg_AppNotFoundErr", spec));
             }
             ICatalogCollection collection = (ICatalogCollection) this._appColl.GetCollection(CollectionName.Components, obj2.Key());
             string[] arr = new string[spec.ConfigurableTypes.Length];
             int index = 0;
             foreach (Type type in spec.ConfigurableTypes)
             {
                 arr[index] = Marshal.GenerateGuidForType(type).ToString();
                 index++;
             }
             Populate(collection);
             bool flag = true;
             int lIndex = 0;
             while (lIndex < collection.Count())
             {
                 ICatalogObject obj3 = (ICatalogObject) collection.Item(lIndex);
                 string g = (string) obj3.Key();
                 g = new Guid(g).ToString();
                 if (this.FindIndexOf(arr, g) != -1)
                 {
                     collection.Remove(lIndex);
                     if (sync != null)
                     {
                         sync.Set();
                     }
                 }
                 else
                 {
                     lIndex++;
                     flag = false;
                 }
             }
             SaveChanges(collection);
             if (flag)
             {
                 for (int i = 0; i < this._appColl.Count(); i++)
                 {
                     ICatalogObject obj4 = (ICatalogObject) this._appColl.Item(i);
                     if (obj4.Key().Equals(obj2.Key()))
                     {
                         this._appColl.Remove(i);
                         if (sync != null)
                         {
                             sync.Set();
                         }
                         break;
                     }
                 }
                 SaveChanges(this._appColl);
             }
         }
         this.UnregisterAssembly(asm, spec);
         this.CleanupDriver();
     }
 }
Beispiel #18
0
        private void RegisterAsSponsor()
        {
            ILease baseLease = (ILease)GetLifetimeService();

            if (baseLease != null)
            {
                // Assert permission to register as a sponsor for this lease.  This is needed for the Internet permission level.
                SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration);
                permission.Assert();
                try
                {
                    // register for sponsorship
                    baseLease.Register(this);
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }
            // baseLease == null when we are not in a separate appdomain
        }
Beispiel #19
0
        private void AppDomainUnload()
        {
            // assert is needed for the Internet named permission set.
            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
            permission.Assert();

            // Sadly, AppDomains can refuse to unload under certain circumstances - mainly when threads get stuck in native code.
            // If that happens, we will retry with increasing intervals.
            // Other exceptions can also happen, in which case, we will trace the error message and quiety leave, otherwise the process might be torn down
            // and this is never what we want as the user has no way to catch anything thrown by this thread.
            try
            {
                for (int wait = 0; wait < MaxAppDomainUnloadWaits; wait++)
                {
                    try
                    {
                        AppDomain.Unload(AppDomain.CurrentDomain);
                        // if we get here successfully, we have unloaded the AppDomain, and thus life is good
                        return;
                    }
                    catch (CannotUnloadAppDomainException)
                    {
                        // Double the interval and wait
                        Thread.Sleep(1 << wait);
                    }
                }

                // We end up here if all retries failed. We try once more, and if that throws - so be it.
                // The outer handler will eat it and trace it out
                Thread.Sleep(1 << MaxAppDomainUnloadWaits);
                AppDomain.Unload(AppDomain.CurrentDomain);
            }
            // We are unloading our own AppDomain so one of these two will typically happen. They actually indicate success, and we don't need to report these
            catch (AppDomainUnloadedException) { }
            catch (ThreadAbortException) { }
            // If we got here, this means that either we are done trying to unload or something unexpected happened during the unload. We trace that out
            catch (Exception ex)
            {
                Trace.WriteLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, Res.FailedToUnloadAppDomain, AppDomain.CurrentDomain.FriendlyName, ex.Message));
            }
        }
Beispiel #20
0
        public void RevokeLifetimeToken(int token)
        {

            lock (m_lifetimeTokens)
            {
                if (!m_lifetimeTokens.Remove(token))
                    throw new InvalidOperationException(Res.LifetimeTokenNotFound);

                if (m_lifetimeTokens.Count == 0)
                {
                    m_zeroReferencesLeft = true;
                    // hook to allow subclasses to clean up
                    OnFinalRevoke();

                    IContract owner = ContractHandle.AppDomainOwner(AppDomain.CurrentDomain);
                    if (owner != null)
                    {
                        if (owner == this)
                        {
                            // Create a separate thread to unload this appdomain, because we 
                            // cannot shut down an appdomain from the Finalizer thread (though there
                            // is a bug that allows us to do so after the first appdomain has been
                            // unloaded, but let's not rely on that).  
                            // We can consider using an threadpool thread to do this, but that would add
                            // test burden.

                            SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlThread);
                            permission.Assert();

                            System.Threading.ThreadStart threadDelegate = new System.Threading.ThreadStart(AppDomainUnload);
                            System.Threading.Thread unloaderThread = new System.Threading.Thread(threadDelegate);
                            unloaderThread.Start();
                        }
                        else
                            owner.RevokeLifetimeToken(m_tokenOfAppdomainOwner);
                    }
                }
            }
        }
Beispiel #21
0
        // Render the contents of the RichTextBox for printing
        // Return the last character printed + 1 (printing start from this point for next page)

        public int Print(int charFrom, int charTo, Graphics gr, Rectangle bounds)
        {
            //Calculate the area to render and print
            RECT rectToPrint;
            rectToPrint.Top = (int)(bounds.Top * anInch);
            rectToPrint.Bottom = (int)(bounds.Height * anInch);// (int)(bounds.Bottom * anInch);
            rectToPrint.Left = (int)(bounds.Left * anInch);
            rectToPrint.Right = (int)(bounds.Width * anInch);// (int)(bounds.Right * anInch);

            //Calculate the size of the page
            RECT rectPage;
            rectPage.Top = (int)(bounds.Top * anInch);
            rectPage.Bottom = (int)(gr.ClipBounds.Height * anInch);//(int)(bounds.Bottom * anInch);
            rectPage.Left = (int)(bounds.Left * anInch);
            rectPage.Right = (int)(gr.ClipBounds.Right * anInch);//(int)(bounds.Right * anInch);
            IntPtr hdc = gr.GetHdc();
            FORMATRANGE fmtRange;
            fmtRange.chrg.cpMax = charTo; //Indicate character from to character to 
            fmtRange.chrg.cpMin = charFrom;
            fmtRange.hdc = hdc; //Use the same DC for measuring and rendering
            fmtRange.hdcTarget = hdc; //Point at printer hDC
            fmtRange.rc = rectToPrint; //Indicate the area on page to print
            fmtRange.rcPage = rectPage; //Indicate size of page
            IntPtr res = IntPtr.Zero;
            IntPtr wparam = IntPtr.Zero;
            wparam = new IntPtr(1);

            //Get the pointer to the FORMATRANGE structure in memory
            IntPtr lparam = IntPtr.Zero;
            lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange));
            Marshal.StructureToPtr(fmtRange, lparam, false);

            //System.Security.Permissions.SecurityPermission, mscorlib
            SecurityPermission secPerm = new SecurityPermission(PermissionState.Unrestricted);
            secPerm.Assert();

            //Send the rendered data for printing 
            res = SendMessage(Handle, EM_FORMATRANGE, wparam, lparam);

            //Free the block of memory allocated
            Marshal.FreeCoTaskMem(lparam);

            //Release the device context handle obtained by a previous call
            gr.ReleaseHdc(hdc);

            //Return last + 1 character printer
            return res.ToInt32();

        }
        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);
        }
        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;
        }
 internal void ConfigureCollection(ICatalogCollection coll, IConfigCallback cb)
 {
     bool flag = false;
     SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     permission.Demand();
     permission.Assert();
     foreach (object obj2 in cb)
     {
         object a = cb.FindObject(coll, obj2);
         cb.ConfigureDefaults(a, obj2);
     }
     SaveChanges(coll);
     flag = false;
     foreach (object obj4 in cb)
     {
         object obj5 = cb.FindObject(coll, obj4);
         if (cb.Configure(obj5, obj4))
         {
             flag = true;
         }
     }
     SaveChanges(coll);
     flag = false;
     foreach (object obj6 in cb)
     {
         object obj7 = cb.FindObject(coll, obj6);
         if (cb.AfterSaveChanges(obj7, obj6))
         {
             flag = true;
         }
     }
     if (flag)
     {
         SaveChanges(coll);
     }
     cb.ConfigureSubCollections(coll);
 }
 internal static Win32Exception CreateSafeWin32Exception(int error)
 {
     Win32Exception result = null;
     SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);
     securityPermission.Assert();
     try
     {
         if (error == 0)
         {
             result = new Win32Exception();
         }
         else
         {
             result = new Win32Exception(error);
         }
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
     return result;
 }
        protected override 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;

            CompilerResults results = new CompilerResults(options.TempFiles);
            SecurityPermission 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;
            
            string extension = (options.GenerateExecutable) ? "exe" : "dll";
            string extensionWithDot = '.' + extension;

            if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
                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.<

                new FileStream(options.OutputAssembly, FileMode.Create, FileAccess.ReadWrite).Close();
                createdEmptyAssembly = true;
            }
            
            String outputAssemblyFile = options.OutputAssembly;
            
            if (!Path.GetExtension(outputAssemblyFile).Equals(extensionWithDot, StringComparison.OrdinalIgnoreCase)) {
                // The vb compiler automatically appends the 'dll' or 'exe' extension if it's not present. 
                // We similarly determine the file name, so we can find it later.
                outputAssemblyFile += extensionWithDot;
            }

#if FEATURE_PAL
            string pdbname = "ildb";
#else
            string pdbname = "pdb";
#endif

            // hack so that we don't delete pdbs when debug=false but they have specified pdbonly. 
            if (options.CompilerOptions!= null && options.CompilerOptions.IndexOf("/debug:pdbonly", StringComparison.OrdinalIgnoreCase) != -1)
                results.TempFiles.AddExtension(pdbname, true);
            else
                results.TempFiles.AddExtension(pdbname);

            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,
                RedistVersionInfo.GetCompilerPath(provOptions, CompilerName),
                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) {

                // The VB Compiler generates multi-line error messages. Currently, the best way to obtain the
                // full message without going too far, is to use the distinction between \n and \r\n. 
                // For multi-line error messages, the former is always output between lines of an error message, 
                // and the latter is output at the end. So this rearranges the output of File.ReadAllLines 
                // so that an error message is contained on a line.
                // 
                // As of now, this is the best way to match a full error message. This is because the compiler 
                // may output other trailing data which isn't an error msg or warning, but doesn't belong to 
                // the error message. So trailing data could get tacked on since the message doesn't always end 
                // with punctuation or some other marker. I confirmed this with the VBC group.
                byte[] fileBytes = ReadAllBytes(outputFile, FileShare.ReadWrite);

                // The output of the compiler is in UTF8
                string fileStr = Encoding.UTF8.GetString(fileBytes);

                // Split lines only around \r\n (see above)
                string[] lines = Regex.Split(fileStr, @"\r\n");

                foreach (string line in lines) {
                    results.Output.Add(line);

                    ProcessCompilerOutputLine(results, line);
                }

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

            if (!results.Errors.HasErrors && options.GenerateInMemory) {
                FileStream fs = new FileStream(outputAssemblyFile, 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 {
#pragma warning disable 618 // Load with evidence is obsolete - this warning is passed on via the options.Evidence parameter
                       results.CompiledAssembly = Assembly.Load(b,null,options.Evidence);
#pragma warning restore 618
                    }
                    finally {
                       SecurityPermission.RevertAssert();
                    }
                }
                finally {
                    fs.Close();
                }
            }
            else {

                results.PathToAssembly = outputAssemblyFile;
            }

            return results;
        }
        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 );
#if MOBILE
                    m_fs = new System.IO.FileStream ( hFile.DangerousGetHandle (), access, ( ( options & System.IO.FileOptions.Asynchronous ) != 0 ), DefaultBufferSize );
#else
                    m_fs = new System.IO.FileStream ( hFile, access, DefaultBufferSize, ( ( options & System.IO.FileOptions.Asynchronous ) != 0 ) );
#endif
                }
                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;
                }
            }
        }
Beispiel #28
0
        private static Uri GetDeploymentUri()
        {
            Invariant.Assert(ApplicationDeployment.IsNetworkDeployed);
            AppDomain currentDomain = AppDomain.CurrentDomain;
            ApplicationIdentity ident = null;
            string codeBase = null;

            SecurityPermission p1 = new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy);
            p1.Assert();
            try
            {
                ident = currentDomain.ApplicationIdentity; // ControlDomainPolicy
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
            
            SecurityPermission p2 = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            p2.Assert();
            try
            {
                codeBase = ident.CodeBase; // Unmanaged Code permission
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }

            return new Uri(new Uri(codeBase), new Uri(".", UriKind.Relative));
        }
Beispiel #29
0
        [System.Security.SecurityCritical]  // auto-generated
        internal virtual String InternalToString()
        {
            try 
            {
#pragma warning disable 618
                SecurityPermission sp= new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy);
#pragma warning restore 618
                sp.Assert();
            }
            catch  
            {
                //under normal conditions there should be no exceptions
                //however if something wrong happens we still can call the usual ToString
            }

            // Get the current stack trace string. 
            return ToString(true, true);
        }
 internal void UnloadAppDomain()
 {
     if (Process.IsCurrentProcess)
     {
         SecurityPermission permission = new SecurityPermission(SecurityPermissionFlag.ControlAppDomain);
         permission.Assert();
         
         AppDomain.Unload(AppDomain);
         CodeAccessPermission.RevertAssert();
     }
     else
     {
         try
         {
             _addInServerWorker.UnloadAppDomain();
         }
         catch (AppDomainUnloadedException) { }
         catch (RemotingException) { }
     }
 }