Пример #1
0
 public void UndoImpersonation()
 {
     if (impersonationContext != null)
     {
         impersonationContext.Undo();
     }
 }
Пример #2
0
 /// <summary>
 /// Stops impersonation.
 /// </summary>
 private void UndoImpersonation()
 {
     if (_wic != null)
     {
         _wic.Undo();
     }
     _wic = null;
 }
Пример #3
0
 public void Undo()
 {
     try
     {
         Win32API.CloseHandle(_main_token);
         _win_identity_context.Undo();
     }
     catch (Exception ex) { }
 }
Пример #4
0
 public void Revert()
 {
     if (_impersonationContext != null)
     {
         // Revert to previous user.
         _impersonationContext.Undo();
         _impersonationContext = null;
     }
 }
Пример #5
0
        private List <string> GetItems()
        {
            System.Security.Principal.WindowsImpersonationContext targetImpersonationContext = null;
            List <string> list = null;
            bool          res  = false;

            System.Data.SqlClient.SqlConnectionStringBuilder bldr;

            if (m_serverInfo.windowsAuth)
            {
                try
                {
                    System.Security.Principal.WindowsIdentity wi =
                        Impersonation.GetCurrentIdentity(m_serverInfo.login, m_serverInfo.password);
                    targetImpersonationContext = wi.Impersonate();
                }
                catch (Exception ex)
                {
                    Idera.SQLsecure.Core.Logger.LogX logX = new Idera.SQLsecure.Core.Logger.LogX("Idera.SQLsecure.UI.Console.Sql.Database");
                    logX.loggerX.Error("Error Processing Impersonation for retrieving Database objects list (" + m_serverInfo.login + ")", ex);
                }
                bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, null, null, Utility.Activity.TypeServerOnPremise);
            }
            else
            {
                bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, m_serverInfo.login, m_serverInfo.password, Utility.Activity.TypeServerOnPremise);
            }

            switch (m_filterObject.ObjectType)
            {
            case RuleObjectType.Database:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetDatabases(m_serverInfo.version, m_filterObject.ObjectScope, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.Table:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetTables(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.View:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetViews(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.Function:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetFunctions(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;
            }

            if (targetImpersonationContext != null)
            {
                targetImpersonationContext.Undo();
                targetImpersonationContext.Dispose();
                targetImpersonationContext = null;
            }

            return(res ? list : new List <string>());
        }
Пример #6
0
        public static void Save(SiteConfig siteConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SiteConfig));

            using (StreamWriter writer = new StreamWriter(SiteConfig.GetConfigFilePathFromCurrentContext()))
            {
                ser.Serialize(writer, siteConfig);
            }

            wi.Undo();
        }
Пример #7
0
        public static void Save(SeoMetaTags seoConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SeoMetaTags));

            using (StreamWriter writer = new StreamWriter(MetaConfigFile))
            {
                ser.Serialize(writer, seoConfig);
            }

            wi.Undo();
        }
Пример #8
0
        public void Leave()
        {
            if (this.IsInContext == false)
            {
                return;
            }
            _context.Undo();

            if (m_Token != IntPtr.Zero)
            {
                CloseHandle(m_Token);
            }
            _context = null;
        }
Пример #9
0
 public void Dispose()
 {
     if (context != null)
     {
         try
         {
             context.Undo();
         }
         finally
         {
             CloseHandle(token);
             context = null;
         }
     }
 }
Пример #10
0
        public static void CopyFile2RemoteFolder(string from, string to, string username, string domain, string password)
        {
            IntPtr tokenHandle = new IntPtr(0);
            int    returnValue = LogonUser(username, domain, password, 2, 0, ref tokenHandle);

            if (returnValue == -1)
            {
                throw new Exception("Logon failed.");
            }

            System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
            System.Security.Principal.WindowsIdentity             wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
            impersonatedUser = wid.Impersonate();

            System.IO.File.Copy(from, to, true);
            impersonatedUser.Undo();
        }
Пример #11
0
        internal void Save(DataManager data)
        {
            string fullPath = data.ResolvePath(FileName);

            // We use the internal list to circumvent ignoring
            // items where IsPublic is set to false.
            if (Entries.Count == 0)
            {
                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }
            }
            else
            {
                System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

                FileStream fileStream = FileUtils.OpenForWrite(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(DayEntry), Data.NamespaceURI);
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            ser.Serialize(writer, this);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }

                wi.Undo();
            }
        }
Пример #12
0
 public static void LogIt(string msg, string type)
 {
     //Method used for logging errors or other messages to the Event log.
     System.Security.Principal.WindowsImpersonationContext wic = null;
     try
     {
         wic = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
         string source  = "Neudesic Mobile Application";
         string logName = "Application";
         string message = msg;
         if (!EventLog.SourceExists(source))
         {
             EventLog.CreateEventSource(source, logName);
         }
         if (type.ToLower() == "msg" || type.ToLower() == "info")
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Information);
         }
         else if (type.ToLower() == "warning")
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Warning);
         }
         else
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Error);
         }
     }
     catch (Exception ex)
     {
         LogIt(ex.ToString(), "Error");
         throw new Exception(ex.ToString());
     }
     finally
     {
         if (wic != null)
         {
             wic.Undo();
         }
     }
 }
        private static void loopCrackNTPassword(ref char[] buffer, int level, string domain, string user, ref string pass, ref bool found)
        {
            int nextLevel = level + 1;

            char[] charSet = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789".ToCharArray();
            for (int c = 0; c < charSet.Length; c++)
            {
                buffer[level] = charSet[c];
                if (nextLevel == buffer.Length)
                {
                    string strBuffer = new string(buffer);
                    //Console.WriteLine("Trying password: " + strBuffer);
                    System.Security.Principal.WindowsImpersonationContext wic = getImpersonate(domain, user, strBuffer);
                    if (wic != null)
                    {
                        wic.Undo();
                        wic.Dispose();
                        wic   = null;
                        found = true;
                        pass  = new string(buffer);
                        return;
                    }
                }
                else
                {
                    if (!found)
                    {
                        loopCrackNTPassword(ref buffer, nextLevel, domain, user, ref pass, ref found);
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
Пример #14
0
            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;
                }
            }
Пример #15
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        internal void Run()
        {
            if (p.Context.Trace.IsEnabled)
            {
                p.Context.Trace.Write(Constant.AjaxID, "Begin ProcessRequest");
            }


            try
            {
                // If we are using the async handler we have to set the ASPNET username
                // to have the same user rights for the created thread.

                if (token != IntPtr.Zero)
                {
                    winctx = System.Security.Principal.WindowsIdentity.Impersonate(token);
                }


                // We will check the custom attributes and try to invoke the method.

                p.Context.Response.Expires = 0;
                p.Context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

                // TODO: check why Opera is not working with application/json;
                // p.Context.Response.AddHeader("Content-Type", "application/json; charset=utf-8");

                p.Context.Response.ContentType     = p.ContentType;
                p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                if (!p.IsValidAjaxToken())
                {
                    // TODO: maybe we want to throw a special exception type.
                    p.SerializeObject(new System.Security.SecurityException("The AjaxPro-Token is not valid."));

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                object[] po  = null;
                object   res = null;

                #region Retreive Parameters from the HTTP Request

                try
                {
                    // The IAjaxProcessor will read the values either form the
                    // request URL or the request input stream.

                    po = p.RetreiveParameters();
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion

                // Check if we have the same request already in our cache. The
                // cacheKey will be the type and a hashcode from the parameter values.

                string cacheKey = p.Type.FullName + "|" + p.GetType().Name + "|" + p.AjaxMethod.Name + "|" + p.GetHashCode();
                if (p.Context.Cache[cacheKey] != null)
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Using cached result");
                    }

                    p.Context.Response.AddHeader("X-" + Constant.AjaxID + "-Cache", "server");

                    // Return the full output of the last cached call
                    p.Context.Response.Write(p.Context.Cache[cacheKey]);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #region Reflection part of Ajax.NET

                try
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Invoking " + p.Type.FullName + "." + p.AjaxMethod.Name);
                    }

                    // If this is a static method we do not need to create an instance
                    // of this class. Some classes do not have a default constructor.

                    if (p.AjaxMethod.IsStatic)
                    {
                        try
                        {
                            //Note: Demand Invocation here!
                            p.DemandInvocation();

                            res = p.Type.InvokeMember(
                                p.AjaxMethod.Name,
                                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod,
                                null, null, po);
                        }
                        catch (Exception ex)
                        {
                            if (ex.InnerException != null)
                            {
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }
                    }
                    else
                    {
                        // Create an instance of the class using the default constructor that will
                        // not need any argument. This can be a problem, but currently I have no
                        // idea on how to specify arguments for the constructor.

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection Start");
                        }

                        try
                        {
                            object c = (object)Activator.CreateInstance(p.Type, new object[] {});

                            // Because the page context properties (Request, Response, Cache...) are
                            // not set using Reflection we will set the context by using the IContextInitializer
                            // interface.

                            if (typeof(IContextInitializer).IsAssignableFrom(p.Type))
                            {
                                ((IContextInitializer)c).InitializeContext(p.Context);
                            }

                            if (c != null)
                            {
//								if(po == null)
//									po = new object[p.Method.GetParameters().Length];

                                //Note: Demand Invocation here!
                                p.DemandInvocation();
                                res = p.AjaxMethod.Invoke(c, po);
                            }
                        }
                        catch (Exception ex)
                        {
#if (WEBEVENT)
                            string errorText = string.Format(Constant.AjaxID + " Error", p.Context.User.Identity.Name);
#endif

                            if (ex.InnerException != null)
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 100, ex.InnerException);
                                ev.Raise();
#endif
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 101, ex);
                                ev.Raise();
#endif
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection End");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        p.SerializeObject(ex.InnerException);
                    }
                    else
                    {
                        p.SerializeObject(ex);
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion


                try
                {
                    if (res != null && res.GetType() == typeof(System.Xml.XmlDocument))
                    {
                        // If the return value is XmlDocument we will return it direct
                        // without any convertion. On the client-side function we can
                        // use .responseXML or .xml.

                        p.Context.Response.ContentType     = "text/xml";
                        p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                        ((System.Xml.XmlDocument)res).Save(p.Context.Response.OutputStream);


                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }


                    string result = null;;

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    try
                    {
                        result = p.SerializeObject(res);
                    }
                    catch (Exception ex)
                    {
                        p.SerializeObject(ex);

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }

                    if (p.ServerCacheAttributes.Length > 0)
                    {
                        if (p.ServerCacheAttributes[0].IsCacheEnabled)
                        {
                            p.Context.Cache.Add(cacheKey, result, null, DateTime.Now.Add(p.ServerCacheAttributes[0].CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "Adding result to cache for " + p.ServerCacheAttributes[0].CacheDuration.TotalSeconds + " seconds (HashCode = " + p.GetHashCode().ToString() + ")");
                            }
                        }
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Result (maybe encrypted): " + result);
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                p.SerializeObject(ex);

                if (p.Context.Trace.IsEnabled)
                {
                    p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                }
                return;
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    winctx.Undo();
                }
            }
        }
        private static System.Collections.Hashtable getNTPasswords(string machine, string[] users, int max)
        {
            try {
                if (max < 1)
                {
                    max = 1;
                }
                if (users == null || users.Length == 0)
                {
                    return(new System.Collections.Hashtable(0));
                }
                if (machine == null || machine.Length == 0)
                {
                    machine = System.Environment.MachineName;
                }

                //machine = machine.ToUpper();

                /*bool isLocalDomain = false;
                 * string localUser = string.Empty;
                 * if (machine.Equals(System.Environment.MachineName.ToUpper())){
                 *  isLocalDomain = true;
                 *  localUser = System.Environment.UserName.ToUpper();
                 * }*/

                System.Collections.Hashtable table = new System.Collections.Hashtable(0);
                for (int i = 0; i < users.Length; i++)
                {
                    //if (isLocalDomain && i < users.Length + 1 && localUser.Equals(users[i].ToUpper())) i++;
                    bool continueCheck = true;
                    System.Security.Principal.WindowsImpersonationContext wic = getImpersonate(machine, users[i], null);
                    if (wic != null)
                    {
                        wic.Undo();
                        wic.Dispose();
                        wic = null;
                        table.Add(users[i], null);
                        continueCheck = false;
                    }
                    if (continueCheck)
                    {
                        wic = getImpersonate(machine, users[i], "");
                        if (wic != null)
                        {
                            wic.Undo();
                            wic.Dispose();
                            wic = null;
                            table.Add(users[i], "");
                            continueCheck = false;
                        }
                    }
                    if (continueCheck)
                    {
                        string pass  = string.Empty;
                        bool   found = false;
                        initCrackNTPassword(max, machine, users[i], ref pass, ref found);
                        if (found)
                        {
                            table.Add(users[i], pass);
                        }
                        pass          = string.Empty;
                        found         = false;
                        continueCheck = false;
                    }
                }
                if (table.Count > 0)
                {
                    return(table);
                }
            } catch (Exception e) {
                string msg = e.Message;
            }
            return(new System.Collections.Hashtable(0));
        }
Пример #17
0
        static void Main(string[] args)
        {
            if (!ProcessCommandLine(args))
            {
                while (!System.Console.KeyAvailable) /* do nothing */ } {
                return;
        }


        System.Security.Principal.WindowsIdentity windowsIdentity = new System.Security.Principal.WindowsIdentity(System.Security.Principal.WindowsIdentity.GetCurrent().Token);

        System.Security.Principal.WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate();

        System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.WindowsPrincipal(windowsIdentity);


        Mercury.Server.Data.SqlConfiguration enterpriseConfiguration = new Mercury.Server.Data.SqlConfiguration();

        enterpriseConfiguration.ServerName = enterpriseServerName;

        enterpriseConfiguration.DatabaseName = enterpriseDatabaseName;

        enterpriseConfiguration.TrustedConnection = enterpriseUseTrustedConnection;

        enterpriseConfiguration.UserName = enterpriseUserName;

        enterpriseConfiguration.Password = enterprisePassword;


        try {
            Mercury.Server.Engine.Processor processor = new Processor(enterpriseServerName, enterpriseDatabaseName, enterpriseUserName, enterprisePassword, environmentDatabaseName);

            processor.MaximumThreads = processThreadCount;


            if (processServices)
            {
                processor.ProcessSingletons();

                processor.ProcessSets();

                processor.ProcessAuthorizedServices();
            }

            if (processMetrics)
            {
                processor.ProcessMetrics();
            }

            if (processPopulations)
            {
                processor.ProcessPopulations();
            }
        }

        catch (Exception engineException) {
            Exception currentException = engineException;

            do
            {
                System.Console.WriteLine(currentException.Message);

                System.Diagnostics.Debug.WriteLine(currentException.Message);

                currentException = currentException.InnerException;
            } while (currentException != null);
        }

        finally {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }


        System.Console.WriteLine("Completed.");

        if (pauseAfterRun)
        {
            while (!System.Console.KeyAvailable) /* do nothing */ } {
    }

    return;
}
Пример #18
0
 public static void undoImpersonation()
 {
     impersonationContext.Undo();
 }
Пример #19
0
            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();
                }
            }