public void Cancel(int severity) { this.threadCanceled = true; System.Security.Permissions.SecurityPermission secPerm = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); secPerm.Assert(); if (severity == 2) { try { if (this.worker.IsAlive) { this.worker.Interrupt(); } } catch { } } else if (severity > 2) { if (this.worker.IsAlive) { try { this.worker.Abort(); } catch { } } } }
/// <summary> /// Workitem 7889: handle ERROR_LOCK_VIOLATION during read /// </summary> /// <remarks> /// This could be gracefully handled with an extension attribute, but /// This assembly is built for .NET 2.0, so I cannot use them. /// </remarks> internal static int ReadWithRetry(System.IO.Stream s, byte[] buffer, int offset, int count, string FileName) { int n = 0; bool done = false; #if !NETCF && !SILVERLIGHT int retries = 0; #endif do { try { n = s.Read(buffer, offset, count); done = true; } #if NETCF || SILVERLIGHT catch (System.IO.IOException) { throw; } #else catch (System.IO.IOException ioexc1) { // Check if we can call GetHRForException, // which makes unmanaged code calls. var p = new System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); if (p.IsUnrestricted()) { uint hresult = _HRForException(ioexc1); if (hresult != 0x80070021) // ERROR_LOCK_VIOLATION { throw new System.IO.IOException(String.Format("Cannot read file {0}", FileName), ioexc1); } retries++; if (retries > 10) { throw new System.IO.IOException(String.Format("Cannot read file {0}, at offset 0x{1:X8} after 10 retries", FileName, offset), ioexc1); } // max time waited on last retry = 250 + 10*550 = 5.75s // aggregate time waited after 10 retries: 250 + 55*550 = 30.5s System.Threading.Thread.Sleep(250 + retries * 550); } else { // The permission.Demand() failed. Therefore, we cannot call // GetHRForException, and cannot do the subtle handling of // ERROR_LOCK_VIOLATION. Just bail. throw; } } #endif }while (!done); return(n); }
public static bool IsInGroup(string user, string group) { System.Security.Permissions.SecurityPermission sp = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); sp.Assert(); using (var identity = new WindowsIdentity(user)) { var principal = new WindowsPrincipal(identity); return(principal.IsInRole(group)); } }
internal static int GetErrorCode(IOException ioe) { #if !WindowsCE && !SILVERLIGHT && !NETFX_CORE var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Demand(); return Marshal.GetHRForException(ioe) & 0xFFFF; #else return 0; #endif }
internal static int GetErrorCode(System.IO.IOException ioe) { #if !WindowsCE && !SILVERLIGHT var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Demand(); return System.Runtime.InteropServices.Marshal.GetHRForException(ioe) & 0xFFFF; #else return 0; #endif }
internal static int GetErrorCode(System.IO.IOException ioe) { #if !WindowsCE && !SILVERLIGHT var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Demand(); return(System.Runtime.InteropServices.Marshal.GetHRForException(ioe) & 0xFFFF); #else return(0); #endif }
internal static int GetErrorCode(IOException ioe) { #if !WindowsCE && !SILVERLIGHT && !NETFX_CORE var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Demand(); return(Marshal.GetHRForException(ioe) & 0xFFFF); #else return(0); #endif }
/// <summary> /// Starts an executable with command line parameters. /// </summary> internal static int RunProcess(string processRelPath, string cmdLine, string workingDirectory) { Process winProcess = null; int retCode = -1; try { winProcess = new Process(); ProcessStartInfo winProcessStartInfo = new ProcessStartInfo(); winProcessStartInfo.FileName = processRelPath; winProcessStartInfo.Arguments = cmdLine; winProcessStartInfo.UseShellExecute = false; winProcessStartInfo.RedirectStandardOutput = true; winProcessStartInfo.WorkingDirectory = workingDirectory; winProcess.StartInfo = winProcessStartInfo; System.Security.Permissions.SecurityPermission permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); permission.Assert(); try { winProcess.Start(); string standardOutput = winProcess.StandardOutput.ReadToEnd(); Console.WriteLine(standardOutput); winProcess.WaitForExit(); retCode = winProcess.ExitCode; } finally { System.Security.CodeAccessPermission.RevertAssert(); } } finally { if (winProcess != null) { winProcess.Dispose(); } } return(retCode); }
static ConnectionBuilder() { if (SqlContext.IsAvailable) { System.Security.Permissions.EnvironmentPermission envPerm = new System.Security.Permissions.EnvironmentPermission(System.Security.Permissions.PermissionState.Unrestricted); envPerm.Assert(); string instanceName = getInstanceName(); if (instanceName == "MSSQLSERVER") { instanceName = null; } System.Security.CodeAccessPermission.RevertAll(); System.Security.Permissions.SecurityPermission secPerm = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); secPerm.Assert(); GetDbName g = new GetDbName( instanceName, new ManualResetEvent(false)); System.Threading.Thread t = new Thread(new ThreadStart(g.DoIt)); //t.Name = "QueryParallelizer: ConnectionBuilder Loopback Database Name"; t.Start(); g.m.WaitOne(); if (null != g.E) { e = new Exception("Error in creating loopback connection", g.E); } else { connectionString = g.sb.ConnectionString; } } else { connectionString = null; } }
public static string[] Parse(string input) { if (string.IsNullOrWhiteSpace(input) || input.Length == 0) { throw new ArgumentException("Cannot parse an empty embedded command-line string"); } #if !SYS_SUB_CMDLINE var parser = new SimpleCommandLineParser(input); return(parser.Parse()); #endif #if SYS_SUB_CMDLINE var allowance = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); allowance.Assert(); IntPtr argv = IntPtr.Zero; try { int argc; argv = CommandLineToArgvW(input, out argc); if (argv == IntPtr.Zero) { throw new ArgumentException("Unable to parse arguments", input, new System.ComponentModel.Win32Exception()); } string[] args = new string[argc]; for (int k = 0; k < argc; ++k) { args[k] = System.Runtime.InteropServices.Marshal.PtrToStringUni ( System.Runtime.InteropServices.Marshal.ReadIntPtr(argv, k * IntPtr.Size) ); } return(args); } finally { LocalFree(argv); System.Security.CodeAccessPermission.RevertAssert(); } #endif }
/// <summary> /// This method is used to cause the QueryParallelizer to begin processing based on the values passed /// to the constructor and set via the public properties. /// </summary> /// <returns> /// The method returns an enumerator which streams back the output rows in the shape of the generic /// type used when the class was instantiated. /// </returns> public IEnumerable <T> Process() { if (isProcessing) { throw new Exception("Processing can only be started a single time per instance"); } isProcessing = true; IntPtr callerIdentityToken = new IntPtr(); if (impersonateCaller) { System.Security.Permissions.SecurityPermission secPerm = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); secPerm.Assert(); callerIdentityToken = SqlContext.WindowsIdentity.Token; } return(new internalEnumerator( query, minVariable, maxVariable, minValue, maxValue, numWorkerThreads, rowLogic, targetConnectionString, rowBufferSize, packageSize, batchSize, reuseConnection, bulkSettings, impersonateCaller, callerIdentityToken, additionalParameters)); }
internal CodeAccessSecurityEngine() { InitSecurityEngine(); AssertPermission = new SecurityPermission(SecurityPermissionFlag.Assertion); AssertPermissionToken = PermissionToken.GetToken(AssertPermission); }
public void doWork() { SqlConnection conn = null; System.Security.Principal.WindowsImpersonationContext callerContext = null; try { Thread.BeginThreadAffinity(); if (impersonateCaller) { System.Security.Permissions.SecurityPermission secPerm = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); secPerm.Assert(); //sometimes the first attempt will fail, due to what is apparently a CLR bug. //Retry several times if necessary, and sleep to let things clear out. int impersonationAttempt = 0; while (impersonationAttempt < 25) { try { callerContext = System.Security.Principal.WindowsIdentity.Impersonate(callerIdentityToken); } catch (ArgumentException) { if (impersonationAttempt == 24) { throw; } else { Thread.Sleep(250); impersonationAttempt++; continue; } } impersonationAttempt = 25; } System.Security.CodeAccessPermission.RevertAll(); } SqlClientPermission sqlPerm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); sqlPerm.Assert(); //set up object for the connection conn = comm.Connection; if (reuseConnection) { conn.Open(); comm.Prepare(); } while (true) { if (ThreadCanceled) { break; } //find out if there is some work to do workPackage wp = monitor.GetNextWorkPackage(); if (wp == null) { break; } comm.Parameters[0].Value = wp.rangeMinimum; comm.Parameters[1].Value = wp.rangeMaximum; if (!reuseConnection) { conn.Open(); } //run the query SqlDataReader r = comm.ExecuteReader(); if (r.HasRows) { foreach (T row in rowLogic(r)) { if (ThreadCanceled) { break; } enqueue(row, true); } //tell the enqueue method to send the final set of rows enqueue(default(T), false); } else { //r has no rows //need to call Read() to discover whether an exception occurred r.Read(); //an exception may have occurred on a "result" other than the first //need to iterate over all possible results while (r.NextResult()) { r.Read(); } } if (reuseConnection) { r.Dispose(); } else { conn.Close(); } monitor.SetWorkerCompleted(true); } } catch (Exception ex) { Exception workerEx = new Exception("Exception occurred in worker", ex); monitor.WorkerThreadException = workerEx; monitor.SetWorkerCompleted(true); } finally { this.threadFinishing = true; comm.Cancel(); comm.Dispose(); if (conn != null) { conn.Dispose(); } if (callerContext != null) { callerContext.Undo(); } this.workComplete = true; Thread.EndThreadAffinity(); } }
/// <summary> /// Workitem 7889: handle ERROR_LOCK_VIOLATION during read /// </summary> /// <remarks> /// This could be gracefully handled with an extension attribute, but /// This assembly is built for .NET 2.0, so I cannot use them. /// </remarks> internal static int ReadWithRetry(System.IO.Stream s, byte[] buffer, int offset, int count, string FileName) { int n = 0; bool done = false; #if !NETCF && !SILVERLIGHT int retries = 0; #endif do { try { n = s.Read(buffer, offset, count); done = true; } #if NETCF || SILVERLIGHT catch (System.IO.IOException) { throw; } #else catch (System.IO.IOException ioexc1) { // Check if we can call GetHRForException, // which makes unmanaged code calls. var p = new System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode); if (p.IsUnrestricted()) { uint hresult = _HRForException(ioexc1); if (hresult != 0x80070021) // ERROR_LOCK_VIOLATION throw new System.IO.IOException(String.Format("Cannot read file {0}", FileName), ioexc1); retries++; if (retries > 10) throw new System.IO.IOException(String.Format("Cannot read file {0}, at offset 0x{1:X8} after 10 retries", FileName, offset), ioexc1); // max time waited on last retry = 250 + 10*550 = 5.75s // aggregate time waited after 10 retries: 250 + 55*550 = 30.5s System.Threading.Thread.Sleep(250 + retries * 550); } else { // The permission.Demand() failed. Therefore, we cannot call // GetHRForException, and cannot do the subtle handling of // ERROR_LOCK_VIOLATION. Just bail. throw; } } #endif } while (!done); return n; }
public void doWork() { System.Security.Principal.WindowsImpersonationContext callerContext = null; try { if (impersonateCaller) { System.Security.Permissions.SecurityPermission secPerm = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted); secPerm.Assert(); //sometimes the first attempt will fail, due to what is apparently a CLR bug. //Retry several times if necessary, and sleep to let things clear out. int impersonationAttempt = 0; while (impersonationAttempt < 25) { try { callerContext = System.Security.Principal.WindowsIdentity.Impersonate(callerIdentityToken); } catch (ArgumentException) { if (impersonationAttempt == 24) { throw; } else { Thread.Sleep(250); impersonationAttempt++; continue; } } impersonationAttempt = 25; } System.Security.CodeAccessPermission.RevertAll(); } SqlClientPermission sqlPerm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); sqlPerm.Assert(); using (SqlBulkCopy bc = new SqlBulkCopy(connectionString, copyOptions)) { bc.DestinationTableName = destinationTable; bc.BulkCopyTimeout = 0; bc.BatchSize = batchSize; if (columnMap != null) { foreach (SqlBulkCopyColumnMapping cm in columnMap) { bc.ColumnMappings.Add(cm); } } bc.WriteToServer(this.bulkDataReader); } } catch (Exception ex) { Exception workerEx = new Exception("Exception occurred in worker", ex); monitor.WorkerThreadException = workerEx; } finally { this.threadFinishing = true; if (callerContext != null) { callerContext.Undo(); } monitor.SetWorkerCompleted(true); this.workComplete = true; } }