473,705 Members | 2,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Installing a Windows Service Programmaticall y

Hi all:
I read an article from
http://www.c-sharpcorner.com/Code/20...mmatically.asp
about how to install a windows service programmaticall y.
Based ont the code sample, it provides the feature to install service
under LocalSystem account.
What I need is to install service under some other certian account. By
further studying the code, and MSDN
(http://msdn.microsoft.com/library/de...-us/dllproc/ba
se/createservice.a sp) ,
public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
lpServiceStartN ame,string lpPassword);
is the core API to create a service. And the last two parameters should be
name and password of account under wihcih service should run. But when I
tried to pass values to these two parameters bu calling:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
This piece of code is just a bit different from original, but sv_handle
return is 0, which means failure.

Anybody has idea how to install a service under some certain account?
Thanks for any suggestion.
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
Nov 15 '05 #1
9 7019
Hardy,

If the return value is IntPtr.Zero, then throw a new instance of the
Win32Exception class. It will detail what the error from the call to
GetLastError is and it will give you more information about what went wrong
with the call.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
Hi all:
I read an article from
http://www.c-sharpcorner.com/Code/20...mmatically.asp about how to install a windows service programmaticall y.
Based ont the code sample, it provides the feature to install service
under LocalSystem account.
What I need is to install service under some other certian account. By
further studying the code, and MSDN
(http://msdn.microsoft.com/library/de...-us/dllproc/ba se/createservice.a sp) ,
public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
lpServiceStartN ame,string lpPassword);
is the core API to create a service. And the last two parameters should be
name and password of account under wihcih service should run. But when I
tried to pass values to these two parameters bu calling:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
This piece of code is just a bit different from original, but sv_handle
return is 0, which means failure.

Anybody has idea how to install a service under some certain account?
Thanks for any suggestion.
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Nov 15 '05 #2
I adding some code like:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);

if (sv_handle.ToIn t32() == 0) {
CloseServiceHan dle(sc_handle);
int err = GetLastError();
return false;
}

I tried to capture the error by reading return from GetLastError(), I got
997, where to find the definition of error code?

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
Hardy,

If the return value is IntPtr.Zero, then throw a new instance of the
Win32Exception class. It will detail what the error from the call to
GetLastError is and it will give you more information about what went wrong with the call.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
Hi all:
I read an article from

http://www.c-sharpcorner.com/Code/20...mmatically.asp
about how to install a windows service programmaticall y.
Based ont the code sample, it provides the feature to install service under LocalSystem account.
What I need is to install service under some other certian account. By further studying the code, and MSDN

(http://msdn.microsoft.com/library/de...-us/dllproc/ba
se/createservice.a sp) ,
public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string lpServiceStartN ame,string lpPassword);
is the core API to create a service. And the last two parameters should be name and password of account under wihcih service should run. But when I
tried to pass values to these two parameters bu calling:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
This piece of code is just a bit different from original, but sv_handle
return is 0, which means failure.

Anybody has idea how to install a service under some certain account?

Thanks for any suggestion.
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy


Nov 15 '05 #3
Hardy,

You should never call GetLastError yourself, as it is not guaranteed to
be accurate. The reason for this is that the runtime makes API calls
between your API call and it might set the error state on its own. Because
of this, you should call the static GetLastWin32Err or method on the Marshal
class.

However, there is a class that does all of this, the Win32Exception
class in the System.Componen tModel namespace. You should make your call
like this:

// Call CreateService.
IntPtr sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);

// Throw an exception if there is no handle.
try
{
if (sv_handle == IntPtr.Zero)
// Throw an exception.
throw new Win32Exception( );
}
finally
{
CloseServiceHan dle(sc_handle);
}

This should give you the description of the error. You can also look in
WINERROR.H to find the error the code represents.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I adding some code like:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);

if (sv_handle.ToIn t32() == 0) {
CloseServiceHan dle(sc_handle);
int err = GetLastError();
return false;
}

I tried to capture the error by reading return from GetLastError(), I got
997, where to find the definition of error code?

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
Hardy,

If the return value is IntPtr.Zero, then throw a new instance of the
Win32Exception class. It will detail what the error from the call to
GetLastError is and it will give you more information about what went wrong
with the call.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
Hi all:
I read an article from

http://www.c-sharpcorner.com/Code/20...mmatically.asp
about how to install a windows service programmaticall y.
Based ont the code sample, it provides the feature to install service under LocalSystem account.
What I need is to install service under some other certian account. By
further studying the code, and MSDN

(http://msdn.microsoft.com/library/de...-us/dllproc/ba se/createservice.a sp) ,
public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string lpServiceStartN ame,string lpPassword);
is the core API to create a service. And the last two parameters should be
name and password of account under wihcih service should run. But when
I tried to pass values to these two parameters bu calling:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
This piece of code is just a bit different from original, but sv_handle return is 0, which means failure.

Anybody has idea how to install a service under some certain

account?

Thanks for any suggestion.
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy



Nov 15 '05 #4
I tried your codes, got error message "Control ID not found".

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:e$******** ******@TK2MSFTN GP12.phx.gbl...
Hardy,

You should never call GetLastError yourself, as it is not guaranteed to be accurate. The reason for this is that the runtime makes API calls
between your API call and it might set the error state on its own. Because of this, you should call the static GetLastWin32Err or method on the Marshal class.

However, there is a class that does all of this, the Win32Exception
class in the System.Componen tModel namespace. You should make your call
like this:

// Call CreateService.
IntPtr sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame, SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);

// Throw an exception if there is no handle.
try
{
if (sv_handle == IntPtr.Zero)
// Throw an exception.
throw new Win32Exception( );
}
finally
{
CloseServiceHan dle(sc_handle);
}

This should give you the description of the error. You can also look in WINERROR.H to find the error the code represents.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I adding some code like:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);

if (sv_handle.ToIn t32() == 0) {
CloseServiceHan dle(sc_handle);
int err = GetLastError();
return false;
}

I tried to capture the error by reading return from GetLastError(), I got
997, where to find the definition of error code?

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
Hardy,

If the return value is IntPtr.Zero, then throw a new instance of the Win32Exception class. It will detail what the error from the call to
GetLastError is and it will give you more information about what went

wrong
with the call.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
> Hi all:
> I read an article from
>

http://www.c-sharpcorner.com/Code/20...mmatically.asp
> about how to install a windows service programmaticall y.
> Based ont the code sample, it provides the feature to install

service
> under LocalSystem account.
> What I need is to install service under some other certian account.
By
> further studying the code, and MSDN
>

(http://msdn.microsoft.com/library/de...-us/dllproc/ba
> se/createservice.a sp) ,
> public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g > lpSvcName,strin g lpDisplayName,
> int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
> dwErrorControl, string lpPathName,
> string lpLoadOrderGrou p,int lpdwTagId,strin g

lpDependencies, string
> lpServiceStartN ame,string lpPassword);
> is the core API to create a service. And the last two parameters should
be
> name and password of account under wihcih service should run. But when I > tried to pass values to these two parameters bu calling:
> sv_handle = CreateService(s c_handle, serviceName,
serviceDisplayN ame, > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> servicePath, null, 0, null, _UserName, _Password);
> This piece of code is just a bit different from original, but

sv_handle > return is 0, which means failure.
>
> Anybody has idea how to install a service under some certain

account?
>
>
> Thanks for any suggestion.
>
>
> --
> WWW: http://hardywang.1accesshost.com
> ICQ: 3359839
> yours Hardy
>
>



Nov 15 '05 #5
Hardy,

Are you sure that this is the error that the call to CreateService gave?
If you replace the "throw" part with a call to GetLastWin32Err or, what does
that return?
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:uu******** ******@tk2msftn gp13.phx.gbl...
I tried your codes, got error message "Control ID not found".

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote in message news:e$******** ******@TK2MSFTN GP12.phx.gbl...
Hardy,

You should never call GetLastError yourself, as it is not guaranteed to
be accurate. The reason for this is that the runtime makes API calls
between your API call and it might set the error state on its own.

Because
of this, you should call the static GetLastWin32Err or method on the

Marshal
class.

However, there is a class that does all of this, the Win32Exception
class in the System.Componen tModel namespace. You should make your call
like this:

// Call CreateService.
IntPtr sv_handle = CreateService(s c_handle, serviceName,

serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);

// Throw an exception if there is no handle.
try
{
if (sv_handle == IntPtr.Zero)
// Throw an exception.
throw new Win32Exception( );
}
finally
{
CloseServiceHan dle(sc_handle);
}

This should give you the description of the error. You can also look in
WINERROR.H to find the error the code represents.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
I adding some code like:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);

if (sv_handle.ToIn t32() == 0) {
CloseServiceHan dle(sc_handle);
int err = GetLastError();
return false;
}

I tried to capture the error by reading return from GetLastError(), I

got 997, where to find the definition of error code?

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com>

wrote
in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
> Hardy,
>
> If the return value is IntPtr.Zero, then throw a new instance of the > Win32Exception class. It will detail what the error from the call to > GetLastError is and it will give you more information about what went wrong
> with the call.
>
> Hope this helps.
>
>
> --
> - Nicholas Paldino [.NET/C# MVP]
> - ni************* *@exisconsultin g.com
>
> "Hardy Wang" <ha********@mar ketrend.com> wrote in message
> news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
> > Hi all:
> > I read an article from
> >
>

http://www.c-sharpcorner.com/Code/20...mmatically.asp
> > about how to install a windows service programmaticall y.
> > Based ont the code sample, it provides the feature to install
service
> > under LocalSystem account.
> > What I need is to install service under some other certian

account.
By
> > further studying the code, and MSDN
> >
>

(http://msdn.microsoft.com/library/de...-us/dllproc/ba
> > se/createservice.a sp) ,
> > public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g > > lpSvcName,strin g lpDisplayName,
> > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
> > dwErrorControl, string lpPathName,
> > string lpLoadOrderGrou p,int lpdwTagId,strin g
lpDependencies, string
> > lpServiceStartN ame,string lpPassword);
> > is the core API to create a service. And the last two parameters

should
be
> > name and password of account under wihcih service should run. But when
I
> > tried to pass values to these two parameters bu calling:
> > sv_handle = CreateService(s c_handle, serviceName,

serviceDisplayN ame, > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> > servicePath, null, 0, null, _UserName, _Password);
> > This piece of code is just a bit different from original, but

sv_handle
> > return is 0, which means failure.
> >
> > Anybody has idea how to install a service under some certain
account?
> >
> >
> > Thanks for any suggestion.
> >
> >
> > --
> > WWW: http://hardywang.1accesshost.com
> > ICQ: 3359839
> > yours Hardy
> >
> >
>
>



Nov 15 '05 #6
Yes, I am sure, I used a catch to capure exception thrown by code, and got
that message.
By calling "int err = Marshal.GetLast Win32Error();" I have error number
1421, don't know what does it mean.

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:eR******** ********@TK2MSF TNGP11.phx.gbl. ..
Hardy,

Are you sure that this is the error that the call to CreateService gave? If you replace the "throw" part with a call to GetLastWin32Err or, what does that return?
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:uu******** ******@tk2msftn gp13.phx.gbl...
I tried your codes, got error message "Control ID not found".

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com>

wrote
in message news:e$******** ******@TK2MSFTN GP12.phx.gbl...
Hardy,

You should never call GetLastError yourself, as it is not guaranteed
to
be accurate. The reason for this is that the runtime makes API calls
between your API call and it might set the error state on its own.

Because
of this, you should call the static GetLastWin32Err or method on the

Marshal
class.

However, there is a class that does all of this, the
Win32Exception class in the System.Componen tModel namespace. You should make your call like this:

// Call CreateService.
IntPtr sv_handle = CreateService(s c_handle, serviceName,

serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);
// Throw an exception if there is no handle.
try
{
if (sv_handle == IntPtr.Zero)
// Throw an exception.
throw new Win32Exception( );
}
finally
{
CloseServiceHan dle(sc_handle);
}

This should give you the description of the error. You can also look
in
WINERROR.H to find the error the code represents.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
> I adding some code like:
> sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame, > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> servicePath, null, 0, null, _UserName, _Password);
>
> if (sv_handle.ToIn t32() == 0) {
> CloseServiceHan dle(sc_handle);
> int err = GetLastError();
> return false;
> }
>
> I tried to capture the error by reading return from GetLastError(), I got
> 997, where to find the definition of error code?
>
> --
> WWW: http://hardywang.1accesshost.com
> ICQ: 3359839
> yours Hardy
> "Nicholas Paldino [.NET/C# MVP]"
<ni************ **@exisconsulti ng.com> wrote
> in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
> > Hardy,
> >
> > If the return value is IntPtr.Zero, then throw a new instance of the
> > Win32Exception class. It will detail what the error from the call to > > GetLastError is and it will give you more information about what went > wrong
> > with the call.
> >
> > Hope this helps.
> >
> >
> > --
> > - Nicholas Paldino [.NET/C# MVP]
> > - ni************* *@exisconsultin g.com
> >
> > "Hardy Wang" <ha********@mar ketrend.com> wrote in message
> > news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
> > > Hi all:
> > > I read an article from
> > >
> >
>

http://www.c-sharpcorner.com/Code/20...mmatically.asp > > > about how to install a windows service programmaticall y.
> > > Based ont the code sample, it provides the feature to install > service
> > > under LocalSystem account.
> > > What I need is to install service under some other certian
account.
> By
> > > further studying the code, and MSDN
> > >
> >
>

(http://msdn.microsoft.com/library/de...-us/dllproc/ba
> > > se/createservice.a sp) ,
> > > public static extern IntPtr CreateService(I ntPtr

SC_HANDLE,strin g
> > > lpSvcName,strin g lpDisplayName,
> > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int > > > dwErrorControl, string lpPathName,
> > > string lpLoadOrderGrou p,int lpdwTagId,strin g
> lpDependencies, string
> > > lpServiceStartN ame,string lpPassword);
> > > is the core API to create a service. And the last two parameters
should
> be
> > > name and password of account under wihcih service should run.

But when
I
> > > tried to pass values to these two parameters bu calling:
> > > sv_handle = CreateService(s c_handle, serviceName,

serviceDisplayN ame,
> > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> > > servicePath, null, 0, null, _UserName, _Password);
> > > This piece of code is just a bit different from original, but
sv_handle
> > > return is 0, which means failure.
> > >
> > > Anybody has idea how to install a service under some certain
> account?
> > >
> > >
> > > Thanks for any suggestion.
> > >
> > >
> > > --
> > > WWW: http://hardywang.1accesshost.com
> > > ICQ: 3359839
> > > yours Hardy
> > >
> > >
> >
> >
>
>



Nov 15 '05 #7
Hardy,

This is truly odd. 1421 is what the exception and the call to
GetLastWin32Err or returned. However, I don't know why CreateService is
returning it. What are you doing in the UI when this call is made?
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:e7******** ******@tk2msftn gp13.phx.gbl...
Yes, I am sure, I used a catch to capure exception thrown by code, and got
that message.
By calling "int err = Marshal.GetLast Win32Error();" I have error number
1421, don't know what does it mean.

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote in message news:eR******** ********@TK2MSF TNGP11.phx.gbl. ..
Hardy,

Are you sure that this is the error that the call to CreateService gave?
If you replace the "throw" part with a call to GetLastWin32Err or, what

does
that return?
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Hardy Wang" <ha********@mar ketrend.com> wrote in message
news:uu******** ******@tk2msftn gp13.phx.gbl...
I tried your codes, got error message "Control ID not found".

--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com>

wrote
in message news:e$******** ******@TK2MSFTN GP12.phx.gbl...
> Hardy,
>
> You should never call GetLastError yourself, as it is not guaranteed to
> be accurate. The reason for this is that the runtime makes API calls > between your API call and it might set the error state on its own.
Because
> of this, you should call the static GetLastWin32Err or method on the
Marshal
> class.
>
> However, there is a class that does all of this, the Win32Exception > class in the System.Componen tModel namespace. You should make your call > like this:
>
> // Call CreateService.
> IntPtr sv_handle = CreateService(s c_handle, serviceName,
serviceDisplayN ame,
> SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
> SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password); >
> // Throw an exception if there is no handle.
> try
> {
> if (sv_handle == IntPtr.Zero)
> // Throw an exception.
> throw new Win32Exception( );
> }
> finally
> {
> CloseServiceHan dle(sc_handle);
> }
>
> This should give you the description of the error. You can also

look
in
> WINERROR.H to find the error the code represents.
>
>
> --
> - Nicholas Paldino [.NET/C# MVP]
> - ni************* *@exisconsultin g.com
>
> "Hardy Wang" <ha********@mar ketrend.com> wrote in message
> news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
> > I adding some code like:
> > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame, > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> > servicePath, null, 0, null, _UserName, _Password);
> >
> > if (sv_handle.ToIn t32() == 0) {
> > CloseServiceHan dle(sc_handle);
> > int err = GetLastError();
> > return false;
> > }
> >
> > I tried to capture the error by reading return from GetLastError(), I
got
> > 997, where to find the definition of error code?
> >
> > --
> > WWW: http://hardywang.1accesshost.com
> > ICQ: 3359839
> > yours Hardy
> > "Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> > wrote
> > in message news:eW******** ******@TK2MSFTN GP10.phx.gbl...
> > > Hardy,
> > >
> > > If the return value is IntPtr.Zero, then throw a new
instance
of the
> > > Win32Exception class. It will detail what the error from the
call
to
> > > GetLastError is and it will give you more information about what

went
> > wrong
> > > with the call.
> > >
> > > Hope this helps.
> > >
> > >
> > > --
> > > - Nicholas Paldino [.NET/C# MVP]
> > > - ni************* *@exisconsultin g.com
> > >
> > > "Hardy Wang" <ha********@mar ketrend.com> wrote in message
> > > news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
> > > > Hi all:
> > > > I read an article from
> > > >
> > >
> >
>

http://www.c-sharpcorner.com/Code/20...mmatically.asp > > > > about how to install a windows service programmaticall y.
> > > > Based ont the code sample, it provides the feature to

install > > service
> > > > under LocalSystem account.
> > > > What I need is to install service under some other certian
> account.
> > By
> > > > further studying the code, and MSDN
> > > >
> > >
> >
>

(http://msdn.microsoft.com/library/de...-us/dllproc/ba
> > > > se/createservice.a sp) ,
> > > > public static extern IntPtr CreateService(I ntPtr
SC_HANDLE,strin g
> > > > lpSvcName,strin g lpDisplayName,
> > > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int > > > > dwErrorControl, string lpPathName,
> > > > string lpLoadOrderGrou p,int lpdwTagId,strin g
> > lpDependencies, string
> > > > lpServiceStartN ame,string lpPassword);
> > > > is the core API to create a service. And the last two parameters > should
> > be
> > > > name and password of account under wihcih service should run. But when
> I
> > > > tried to pass values to these two parameters bu calling:
> > > > sv_handle = CreateService(s c_handle, serviceName,
serviceDisplayN ame,
> > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
> > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
> > > > servicePath, null, 0, null, _UserName, _Password);
> > > > This piece of code is just a bit different from original, but
> sv_handle
> > > > return is 0, which means failure.
> > > >
> > > > Anybody has idea how to install a service under some certain > > account?
> > > >
> > > >
> > > > Thanks for any suggestion.
> > > >
> > > >
> > > > --
> > > > WWW: http://hardywang.1accesshost.com
> > > > ICQ: 3359839
> > > > yours Hardy
> > > >
> > > >
> > >
> > >
> >
> >
>
>



Nov 15 '05 #8
Let me post all my codes here, what I like to do is to create a class
library, I can use it by other UI, then add a test Windows Application
Class Library:
----------------------------------------
using System;
using System.Runtime. InteropServices ;

/// <summary>
/// Programmaticall y install / uninstall Windows Service
/// </summary>
/// <example>
/// <code>
/// string svcPath = @"C:\build\serv ice\Debug\Servi ce.exe";
/// string svcDispName="Se rvice Display Name";
/// string svcName= "Service Name";
/// WindowsServiceI nstaller c = new WindowsServiceI nstaller();
/// c.InstallServic e(svcPath, svcName, svcDispName);
/// </code>
/// </example>
public class WindowsServiceI nstaller {
/// <summary>
/// Default constructor to initialize instance
/// </summary>
public WindowsServiceI nstaller() {
_UserName = "";
_Password = "";
}

/// <summary>
/// Username to run account
/// </summary>
private string _UserName;
/// <summary>
/// Password to run account
/// </summary>
private string _Password;

#region DLLImport
/// <summary>
/// Open SC Manager
/// </summary>
[DllImport("adva pi32.dll")]
private static extern IntPtr OpenSCManager(s tring lpMachineName,s tring
lpSCDB, int scParameter);
/// <summary>
/// Create Service
/// </summary>
[DllImport("Adva pi32.dll")]
private static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
lpServiceStartN ame,string lpPassword);
/// <summary>
/// Close Service Handle
/// </summary>
[DllImport("adva pi32.dll")]
private static extern void CloseServiceHan dle(IntPtr SCHANDLE);
/// <summary>
/// Start Service
/// </summary>
[DllImport("adva pi32.dll")]
private static extern int StartService(In tPtr SVHANDLE,int
dwNumServiceArg s,string lpServiceArgVec tors);
/// <summary>
/// Open Service
/// </summary>
[DllImport("adva pi32.dll",SetLa stError=true)]
private static extern IntPtr OpenService(Int Ptr SCHANDLE,string
lpSvcName,int dwNumServiceArg s);
/// <summary>
/// Delete Service
/// </summary>
[DllImport("adva pi32.dll")]
private static extern int DeleteService(I ntPtr SVHANDLE);

/// <summary>
/// Get last error
/// </summary>
[DllImport("kern el32.dll")]
private static extern int GetLastError();
#endregion DLLImport

//path to the service that you want to install
//servicePath = @"C:\build\serv ice\Debug\Servi ce.exe";
//serviceDisplayN ame="Service Display Name";
//serviceName= "Service Name";

/// <summary>
/// This method installs and runs the service in the service conrol manager
under LocalSystem account.
/// </summary>
/// <param name="servicePa th">The complete path of the service.</param>
/// <param name="serviceNa me">Name of the service.</param>
/// <param name="serviceDi splayName">Disp lay name of the service.</param>
/// <returns>True if the process went throgh successfully. False if there
was any error.</returns>
public bool InstallService( string servicePath, string serviceName, string
serviceDisplayN ame) {
#region Constants declaration.
int SC_MANAGER_CREA TE_SERVICE = 0x0002;
int SERVICE_WIN32_O WN_PROCESS = 0x00000010;
int SERVICE_DEMAND_ START = 0x00000003;
int SERVICE_ERROR_N ORMAL = 0x00000001;

int STANDARD_RIGHTS _REQUIRED = 0xF0000;
int SERVICE_QUERY_C ONFIG = 0x0001;
int SERVICE_CHANGE_ CONFIG = 0x0002;
int SERVICE_QUERY_S TATUS = 0x0004;
int SERVICE_ENUMERA TE_DEPENDENTS = 0x0008;
int SERVICE_START = 0x0010;
int SERVICE_STOP = 0x0020;
int SERVICE_PAUSE_C ONTINUE =0x0040;
int SERVICE_INTERRO GATE = 0x0080;
int SERVICE_USER_DE FINED_CONTROL = 0x0100;

int SERVICE_ALL_ACC ESS = (STANDARD_RIGHT S_REQUIRED |
SERVICE_QUERY_C ONFIG |
SERVICE_CHANGE_ CONFIG |
SERVICE_QUERY_S TATUS |
SERVICE_ENUMERA TE_DEPENDENTS |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_C ONTINUE |
SERVICE_INTERRO GATE |
SERVICE_USER_DE FINED_CONTROL);
int SERVICE_AUTO_ST ART = 0x00000002;
#endregion Constants declaration.

IntPtr sc_handle = OpenSCManager(n ull,null,SC_MAN AGER_CREATE_SER VICE);

if (sc_handle.ToIn t32() != 0) {
IntPtr sv_handle;
if (_UserName.Trim ().Length > 0) {
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
} else {
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, null, null);
}

if (sv_handle.ToIn t32() == 0) {
int err = Marshal.GetLast Win32Error();
CloseServiceHan dle(sc_handle);
return false;
} else {
//now trying to start the service
int i = StartService(sv _handle, 0, null);
// If the value i is zero, then there was an error starting the service.
// note: error may arise if the service is already running or some other
problem.
if(i == 0) {
//Console.WriteLi ne("Couldnt start service");
return false;
}
//Console.WriteLi ne("Success");
CloseServiceHan dle(sc_handle);
return true;
}
} else {
//Console.WriteLi ne("SCM not opened successfully");
return false;
}
}

/// <summary>
/// This method installs and runs the service in the service conrol manager
under specified account.
/// </summary>
/// <param name="servicePa th">The complete path of the service.</param>
/// <param name="serviceNa me">Name of the service.</param>
/// <param name="serviceDi splayName">Disp lay name of the service.</param>
/// <param name="serviceSt artName">The name of the account under which the
service should run</param>
/// <param name="password" >The password to the account name specified by
the serviceStartNam e parameter</param>
/// <returns>True if the process went throgh successfully. False if there
was any error.</returns>
public bool InstallService( string servicePath, string serviceName,
string serviceDisplayN ame, string serviceStartNam e, string password) {
_UserName = serviceStartNam e;
_Password = password;

return InstallService( servicePath, serviceName, serviceDisplayN ame);
}

/// <summary>
/// This method uninstalls the service from the service conrol manager.
/// </summary>
/// <param name="serviceNa me">Name of the service to uninstall.</param>
public bool UnInstallServic e(string serviceName) {
int GENERIC_WRITE = 0x40000000;
IntPtr sc_hndl = OpenSCManager(n ull,null,GENERI C_WRITE);

if (sc_hndl.ToInt3 2() !=0) {
int DELETE = 0x10000;
IntPtr svc_hndl = OpenService(sc_ hndl,serviceNam e,DELETE);
//Console.WriteLi ne(svc_hndl.ToI nt32());
if(svc_hndl.ToI nt32() !=0) {
int i = DeleteService(s vc_hndl);
if (i != 0) {
CloseServiceHan dle(sc_hndl);
return true;
} else {
CloseServiceHan dle(sc_hndl);
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
=============== ============
Test application:
-----------------------------
private void button1_Click(o bject sender, System.EventArg s e) {
WindowsServiceI nstaller c = new WindowsServiceI nstaller();
if
(c.InstallServi ce(@"C:\Work\Re portScheduler\R eportScheduler\ bin\Debug\Repor t
Scheduler.exe", "Report", "Report", @"domian\userna me", "password") ) {
MessageBox.Show ("OK");
} else {
MessageBox.Show ("Bad");
}
}
=============== =============== =============== ==
I tried the overload without username and password, the service is created,
but this one failed.
Nov 15 '05 #9
Why not simply use the sc.exe commandline utility (standard on XP and W2K3, resource kit utility for NT4).

Willy.

"Hardy Wang" <ha********@mar ketrend.com> wrote in message news:Oo******** ******@TK2MSFTN GP11.phx.gbl...
Hi all:
I read an article from
http://www.c-sharpcorner.com/Code/20...mmatically.asp
about how to install a windows service programmaticall y.
Based ont the code sample, it provides the feature to install service
under LocalSystem account.
What I need is to install service under some other certian account. By
further studying the code, and MSDN
(http://msdn.microsoft.com/library/de...-us/dllproc/ba
se/createservice.a sp) ,
public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
lpSvcName,strin g lpDisplayName,
int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
dwErrorControl, string lpPathName,
string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
lpServiceStartN ame,string lpPassword);
is the core API to create a service. And the last two parameters should be
name and password of account under wihcih service should run. But when I
tried to pass values to these two parameters bu calling:
sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
servicePath, null, 0, null, _UserName, _Password);
This piece of code is just a bit different from original, but sv_handle
return is 0, which means failure.

Anybody has idea how to install a service under some certain account?
Thanks for any suggestion.
--
WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Nov 15 '05 #10

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

Similar topics

2
15222
by: Ken Lindner | last post by:
I have a need to become familiar with SQL Server 2000 for work. Needless to say I am new to SQL Server any version, but not IT in general. My employer has provided me with the SQL Server 2000 Personal disk from the SQL Server 2000 Enterprise kit as this is reported here on the MSDN web site to be the version that is supported on Windows XP. In fact so many of you kind people confess to having succeeded in doing it. I have tried...
2
2886
by: Vince Keller | last post by:
I dont know if this is the correct newsgroup to post questions on Windows Service. I am trying to install and uninstall a Windows Service programmatically. As far as I know, there isnt a class in .NET FCL which supports doing that. The ServiceController class starts/stops an installed service but doesnt install a service. Is there a way to install/uninstall a service programmatically (not using the Installer) ? Thanks.
1
7487
by: Bhavya Shah | last post by:
Hello, I want to install an application as a Windows Service on a remote computer. I know the procedure to install a windows service on a local computer by using installutil.exe. How can I install a Windows Service on a remote computer programmatically through C#. Regards, Bhavya Shah
11
5773
by: tshad | last post by:
I have a small Windows Service program that just has a timer on it and it built fine. I try to install it using InstallUtil and I get the following message: System.ComponentModel.Win32Exception: The account name is invalid or does not exist, or the password is invalid for the account name specified I am in the same folder my program is in (MyService.exe). I assume it has to do with Logon Credentials.
5
2413
by: Andrea Vincenzi | last post by:
Help me please, I'm totally stuck! My Visual Studio 2003 debugger stopped working after I installed Windows XP Service Pack 2. Here is what happens (with any project, even a "Hello, world" message): the first time I open a project and try to start it in debug mode, Visual Studio hangs before executing the first line of code. The only way to stop it is to kill the process using the Task Manager. If I open the same project a second time and...
4
15703
by: juliashah | last post by:
I've developed a windows service that monitors the database and shows icon of a different color depending on the data. To be able to show an icon I have to select the "Allow service to interact with desktop" checkbox on the service, and when I do it manually, the icon shows just fine. But I want the users to double-click the installation file and not have to go to the Services and select the checkbox. So I used this example...
7
4372
by: sunil | last post by:
Hi all, I read an article from http://www.c-sharpcorner.com/Code/2003/Sept/InstallingWinServiceProgrammatically.asp about how to install a windows service programmatically. Based on the code sample, it provides the feature to install service under LocalSystem account. What I need is to install service under NT AUTHORITY\NetworkService, so that my service can access the shared network resources.
11
20217
by: Don | last post by:
QUESTIONS: 1. Has anyone figured out how to successfully install the Office 97 Pro Service Release 2 patch in Vista? 2. Has anyone successfully installed an Office 97 Pro CD (SR2 version) in Vista? DETAILS: My setup: Dell Inspiron notebook with Vista Business edition My CD: Office 97 Professional (Service Release 1) Upgrade
15
2438
by: =?Utf-8?B?RWxpb3Ro?= | last post by:
I try to install Windows Services but it show this error during the installation process, "Insufficient System resources exist to complete the requested service." I created this Services in VB 2005. I has other Windows Services installed on this machine. I try to install in other computer with the same specification and its is OK. Specification
0
8771
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8691
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
9275
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...
0
8981
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7895
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
6607
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
5934
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4705
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2492
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.