473,652 Members | 3,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mulples threads and impersonation

I have a windows service which every night checks a SQL Server database for
some data and business rules. The application can access different DBs with
the same structure, to tell the service which database to check I created
local users and assigned each of them a different default DB in SQL Server,
then, in the windows service I impersonate each user and then access the DB,
when the connection to the DB is made, the default DB for the impersonated
user is automatically selected, so far so good.

Now, after that, I realized that each time I connect to the DB to do the
checking, the code can take a long time to finish and impersonate the next
user, so I decided to put the code that does the impersonating and the
checking in a thread, so the service now creates a different thread for each
user it has to impersonate and then the thread impersonates its assigned
user and runs the checking process, my idea with this was that every DB
could be checked simultaneously, instead of sequentially.

Problem is, its not working!!! It seems every time one of the threads
impersonates a user, it "overwrites " the last impersonation.

Is there no way to have each thread impersonate a diferent user at the same
time??

I'm using Windows Server 2003, SQL Server 2005, Visual Studio.NET 2003 (if
necessary to upgrade to 2005, no problem!), but code should run on Windows
2000 server and SQL Server 2000 also.

Please help!!!

Thanks!
David C.
Jun 15 '06 #1
4 1785
"David Cablalero" <dc********@edu cate-global.com> wrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
I have a windows service which every night checks a SQL Server database for
some data and business rules. The application can access different DBs with
the same structure, to tell the service which database to check I created
local users and assigned each of them a different default DB in SQL Server,
then, in the windows service I impersonate each user and then access the
DB, when the connection to the DB is made, the default DB for the
impersonated user is automatically selected, so far so good.

Now, after that, I realized that each time I connect to the DB to do the
checking, the code can take a long time to finish and impersonate the next
user, so I decided to put the code that does the impersonating and the
checking in a thread, so the service now creates a different thread for
each user it has to impersonate and then the thread impersonates its
assigned user and runs the checking process, my idea with this was that
every DB could be checked simultaneously, instead of sequentially.

Problem is, its not working!!! It seems every time one of the threads
impersonates a user, it "overwrites " the last impersonation.

Is there no way to have each thread impersonate a diferent user at the
same time??

I'm using Windows Server 2003, SQL Server 2005, Visual Studio.NET 2003 (if
necessary to upgrade to 2005, no problem!), but code should run on Windows
2000 server and SQL Server 2000 also.


Impersonation is strictly a per-thread operation - there's no way to change
the identity of every thread in a process en-masse.

How are you doing the impersonation? How are you assessing that it's "not
working"? Have you checked in SQL Server (e.g. via SQL Profiler) to see if
the requests are being made by the impersonated users?

-cd
Jun 15 '06 #2
Hi Carl, thanks for replying!
Here are some code extracts:

Public Class LMSService
Inherits ServiceBase

Private Class DoTaskClass
Private sUser As String, sDomain As String, sPwd As String

Public Sub New(ByVal sD As String, ByVal sU As String, ByVal sP
As String)
sDomain = sD
sUser = sU
sPwd = sP
TaskThread = New Threading.Threa d(AddressOf DoTask)
End Sub

Private Sub DoTask()
try
tokenHandle = IntPtr.Zero
Dim returnValue As Boolean = LogonUser(sUser , sDomain,
sPwd, LOGON32_LOGON_I NTERACTIVE, LOGON32_PROVIDE R_DEFAULT, tokenHandle)
Dim newId As New WindowsIdentity (tokenHandle)
impersonatedUse r = newId.Impersona te()

'The checking code

Catch ex As Exception
WriteLog("'" + sDomain + "\" + sUser + "':" +
ex.Message + vbCrLf + vbCrLf + ex.StackTrace)
Finally
If Not IsNothing(imper sonatedUser) Then
impersonatedUse r.Undo()
impersonatedUse r = Nothing
End If
If Not System.IntPtr.o p_Equality(toke nHandle,
IntPtr.Zero) Then
CloseHandle(tok enHandle)
End If
End Try
End Sub

Public Sub StartTask()
TaskThread.Star t()
End Sub
End Class
Private WithEvents LMSServiceTimer As Timer

Private Sub LMSTimer(ByVal sender As Object, ByVal e As
ElapsedEventArg s) Handles LMSServiceTimer .Elapsed
Dim LMSTask As DoTaskClass

if (DateLastCheck< DateToday) then
for each user to impersonate
LMSTask = New DoTaskClass(sDo main,sUser,sPwd )
LMSTask.StartTa sk
next
then
End Sub

Protected Overrides Sub OnStart(ByVal args() As String)
LMSServiceTimer .Enabled = True
End Sub

<MTAThread()> _
Public Shared Sub Main()
Dim ServicesToRun() As System.ServiceP rocess.ServiceB ase

ServicesToRun = New System.ServiceP rocess.ServiceB ase() {New
LMSService}
System.ServiceP rocess.ServiceB ase.Run(Service sToRun)
End Sub

End Class

Of course I skipped a lot of things here, like the imports of the
impersonating functions, not creating new threads for the same users,
checking if the threads have finished, etc. I only put the code of the
problem I'm talking about.

I've been testing with only 2 users/databases, after the run I check
the databases and only 1 of them was affected, which one was affected
varies, I'm guessing depending on the order in which the threads did
the impersonation.

Carl Daniel [VC++ MVP] wrote:
"David Cablalero" <dc********@edu cate-global.com> wrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
I have a windows service which every night checks a SQL Server database for
some data and business rules. The application can access different DBs with
the same structure, to tell the service which database to check I created
local users and assigned each of them a different default DB in SQL Server,
then, in the windows service I impersonate each user and then access the
DB, when the connection to the DB is made, the default DB for the
impersonated user is automatically selected, so far so good.

Now, after that, I realized that each time I connect to the DB to do the
checking, the code can take a long time to finish and impersonate the next
user, so I decided to put the code that does the impersonating and the
checking in a thread, so the service now creates a different thread for
each user it has to impersonate and then the thread impersonates its
assigned user and runs the checking process, my idea with this was that
every DB could be checked simultaneously, instead of sequentially.

Problem is, its not working!!! It seems every time one of the threads
impersonates a user, it "overwrites " the last impersonation.

Is there no way to have each thread impersonate a diferent user at the
same time??

I'm using Windows Server 2003, SQL Server 2005, Visual Studio.NET 2003 (if
necessary to upgrade to 2005, no problem!), but code should run on Windows
2000 server and SQL Server 2000 also.


Impersonation is strictly a per-thread operation - there's no way to change
the identity of every thread in a process en-masse.

How are you doing the impersonation? How are you assessing that it's "not
working"? Have you checked in SQL Server (e.g. via SQL Profiler) to see if
the requests are being made by the impersonated users?

-cd


Jun 15 '06 #3
"DCaballero " <dc********@edu cate-global.com> wrote in message
news:11******** **************@ h76g2000cwa.goo glegroups.com.. .
Hi Carl, thanks for replying!
Here are some code extracts:


You've only shown one thread here. How are multiple threads created? e.g.
is there a separate instance of LMSService for each thread, or is there a
single instance that starts all the threads?

If the latter, and if this snippet represents the actual code, then your
problem lies in the use of member variables to pass information to the
thread: You've no way to know when the newly started thread has consumed
the values of sDomain, sUser and sPwd. It could be before the first call to
new Thread() returns, or it could be after you've started all your threads.

You either need to interlock thread startup so that you're guarateed that
the new thread has consumed those values before you move on, or change the
design so that unique copies of those variables exist for each thread, e.g.
by making a Task class that has a copy of those variables and implements the
"DoTask" method that's actually run on the new thread.

-cd
Jun 16 '06 #4

But that's exactly what I'm doing, as you can see in the code, the
sDomain, sUser and sPwd variables are private in DoTaskClass, they are
initialized with values passed to the constructor of the class, so when
each thread is started it uses its class' own variables, I thought this
way each thread would impersonate its own user. What am I doing wrong?

When you say interlock thread startup, do you mean that I start 1
thread and wait for it to impersonate before starting the next thread?
Would that be the same as impersonating the user in the main thread,
creating and starting 1 thread, impersonate the next user in the main
thread then creating and starting the next thread and so on?

David C.

Carl Daniel [VC++ MVP] wrote:
"DCaballero " <dc********@edu cate-global.com> wrote in message
news:11******** **************@ h76g2000cwa.goo glegroups.com.. .
Hi Carl, thanks for replying!
Here are some code extracts:


You've only shown one thread here. How are multiple threads created? e.g.
is there a separate instance of LMSService for each thread, or is there a
single instance that starts all the threads?

If the latter, and if this snippet represents the actual code, then your
problem lies in the use of member variables to pass information to the
thread: You've no way to know when the newly started thread has consumed
the values of sDomain, sUser and sPwd. It could be before the first call to
new Thread() returns, or it could be after you've started all your threads.

You either need to interlock thread startup so that you're guarateed that
the new thread has consumed those values before you move on, or change the
design so that unique copies of those variables exist for each thread, e.g.
by making a Task class that has a copy of those variables and implements the
"DoTask" method that's actually run on the new thread.

-cd


Jun 19 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5159
by: Chris | last post by:
Hello all, Here is my problem. I have a windows service (C#) that is supposed to move files from/to the local drive to/from a UNC share (\\domainserver\share). The service is running on a Win3k server not connected to a domain, as a local user. The service impersonates a local user (on domainserver) that has full permissions to that share. Any File.Move, File.Copy operations are successfull. Any Directory.GetFiles fail with "Logon...
1
3955
by: techfuzz | last post by:
I'm posting my problem experience and solution I found here for other ASP.NET developers. I have a web application that uses Forms Authentication with Active Directory to control access. In this web application, I have search page that utilizes the Windows Indexing Service (MSIDXS provider). For reasons I'm not aware of at this time, setting <identity impersonation="true" /> in the web.config causes an error whenever you try to search.
10
1463
by: Markus P | last post by:
Hi! I am trying to write an asp.net app (page/class) which is going to make several calls to distibuted objects (com+/serviced componentes) which in turns talks to other distributed computers. These COM+/serviced componentes object has security settings that allows only privileged users to instanciate and use them. So I have the impersonate=true flag setted in web.config. Because of the long responsetimes and low CPU usage when calling...
7
1361
by: Bonj | last post by:
Hi I made a naff web application which uses the impersonation method in MSDN (can't find it now, but it basically revolves around creating a token by calling the LogonUser API, calling DuplicateToken API on it, and then calling w.Impersonate() where w is a System.Security.Principal.WindowsIdentity object). This is the only real point of the said web application if I'm brutally honest with myself ;-) however it leaves me curious, as does...
2
1587
by: Sparky | last post by:
Hi I have an vb.net winforms application that needs to launch a thread, and within that thread change the security context of the current user to a new one using impersonation. For clarity, the main thread that the application is running under is Thread A, and the new thread in which i perform the impersonation under is thread B. This works fine, but i now need to launch another thread (Thread C) from within Thread B. This is all...
11
2843
by: Phil | last post by:
Hi, I've currently setup a local user as described in: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnne...
0
1259
by: velvet.graham | last post by:
I'm having a difficult time with impersonation. I've created an impersonation class. Here is the code below: ******Impersonation Class Code********* Imports System Imports System.Web.Security Imports System.Runtime.InteropServices Imports System.Security.Principal Imports System.DirectoryServices Imports System.Security.Permissions
1
1531
by: zhuang | last post by:
Dear all, I found a very interesting thing about viewing crystal report (located on network drive) with asp.net application. To do the impersonation, modify web.config does not work, you have to modify machine.config. which is not recommended. However, there is no way around. To prove I did the impersonation properly, I did the below test.
5
2662
by: =?Utf-8?B?S2l0dHlIYXdr?= | last post by:
I am in the process of migrating an II6 environment from a single server to a network load balanced system. Thus, I am using a virtual directory on a UNC share to house the dynamic data that the web farm will access. Since ASP.NET runs as a local account on the IIS servers, I have to use impersonation to perform any operations on the data that resides on the UNC share. I am hard-coding the impersonation credentials in the web.config files...
0
8279
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8811
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8467
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7302
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4145
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2703
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.