C# .NET - how can I retrieve a particular windows service?

Asked By ipsoftware IT
29-Nov-04 09:13 AM
how can I retrieve a particular windows service based on the service name or service display name? the getservice method in ServiceController only gives us a list of service. If a lot of services running and I want to retrieve a particular service, the getService method is rather undesirable! please help. Thanks

Did you not want to use WMI?  Did you not want to use WMI?

29-Nov-04 10:17 AM
http://www.eggheadcafe.com/forums/ForumPost.asp?ID=15822&INTID=2

All the ingredients you need  All the ingredients you need

29-Nov-04 10:40 AM
are right there:

public ServiceController FindServiceByName(string s) 
    {          
        try 
        { 
            ServiceController[] services; 
            services = ServiceController.GetServices(); 
            for(int i = 0; i <  services.Length; i++) 
            { 
                if(services[i].ServiceName==s) 
                { 
                    return services[i];
                    break; 
                } 
            } 
        }  
        catch(Exception ){ throw;}         
	 return null;
    }

You are absolutely right  You are absolutely right

29-Nov-04 01:44 PM
I had forgotten that .NET has a wrapper to advapi32.dll that is much nicer to use.  Good call.
Thank you  Thank you
30-Nov-04 12:11 PM
actually, we can retrieve a particular service using the ServiceController constructor
I had forgotten about  NET's wrapper class  I had forgotten about NET's wrapper class
30-Nov-04 01:53 PM
for the dll used by WMI.
But WMI does't solve the problem  But WMI does't solve the problem
30-Nov-04 02:03 PM
say I just want to stop the "Messenger" service on my local machine. the code is actually is the same as the one in windows application. just call ServiceController.Start() or Stop(). No any specific class or method involved in WMI. However, we cannot do that. The starting or stop is not successful. But the same code. in windows application, it work. The link below explains WMI and use it to stop and start services just using Start() and Stop() methods. I tried. not working. 
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=114

So what is wrong here? Thank you!
Are you running this from ASP NET?  Are you running this from ASP NET?
30-Nov-04 06:07 PM
.  If so, the likely reason for failure is that the windows account that your ASP.NET session runs doesn't have enough permissions like your logged in windows account does.

BTW... I was just commenting on why the .NET solution is easier than converting my classic ASP sample.  I reviewed the source code of the .NET Framework for this namespace and found that it uses the same windows api dll that WMI in COM does.
I am using my own computer and definitely I am  I am using my own computer and definitely I am
30-Nov-04 07:00 PM
the PC administrator.  So I don't think it is the permission problem. Any way, have you seen the code from the link I posted in my previous question. It is simple, Can you run from there? I am using ASP.NET. Thank you!
ASP NET - Start And Stop A Windows Service  ASP NET - Start And Stop A Windows Service
30-Nov-04 08:09 PM
When you browse to an ASP.NET page, it runs under the ASPNET account by default not under the windows account you are logged in as.  The sample will demonstrate this.

Run this as an ASP.NET app to start and stop your services.  This sample starts and stops SQL Server.

Make sure you put this in your web.config as well:

    <authentication mode="Windows"/>
     <authorization>
       <deny users="?"/>
     </authorization>


Code behind:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ServiceProcess; 
using System.Net;
using System.Security.Principal; 

namespace WebApplication1
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
    private void Page_Load(object sender, System.EventArgs e)
  {
             
                string PcName = "Your PC Name Goes Here";
                WindowsImpersonationContext wic = null;

                try 
                { 

                    IPrincipal p = this.User;

                    WindowsIdentity id = (WindowsIdentity)p.Identity;

                    Response.Write("Running as:" +  WindowsIdentity.GetCurrent().Name + "<br>");
 
                     wic = id.Impersonate();
 
                    Response.Write("Running as:" +  WindowsIdentity.GetCurrent().Name + "<br>");

                    ServiceController[] services = ServiceController.GetServices(); 

                    for(int i = 0; i <  services.Length; i++) 
                    { 
                        
                        if (services[i].DisplayName == "MSSQLSERVER")
                        {
                            Response.Write(services[i].DisplayName + " - ");
                            Response.Write(services[i].Status.ToString());
                            Response.Write("<br>");
                            ServiceController sc = new ServiceController(services[i].DisplayName,PcName);

                            if (sc.Status == ServiceControllerStatus.Running)
                            {
                                sc.Stop();
                            }
                            if (sc.Status == ServiceControllerStatus.Stopped)
                            {
                                sc.Start(); 
                            }
                          
                        }
                    } 
                }   
                catch(Exception err )
                {
                   Response.Write(err.Message);
                }         
              finally 
                    {
                        wic.Undo();
                    }
                        
  }
Thank you Robbe, I solved the problem by  Thank you Robbe, I solved the problem by
01-Dec-04 06:51 AM
unstalling IIS and reinstalling it. Thank you so much for your kind help. I have another question and I would like to listen to your suggestion.

I want to retrieve a list of windows services over web application (not windows application) and display them to the user via IE. Now, only several windows services available and I could display them in table format using Repeater control. Within one row, the first item will be a check box, 2nd item will be the service name, 3rd item will be the status of the service, and 4th will be a button which allows the user to start and stop the service.

Now, I am told there will be potentially huge number of window services. However, the Repeater doesn't provide a scroll bar. User has to use the IE scroll bar. I thought about two options, one is to use a list box to display the data which has a scroll bar. However, how to display the check box, name, status and button in one row in the list box????

2nd option will be I display only several services in the first page and provide the "next Page " "previous page" link to allow user to browse those services. But this requires more coding work. and unfortunately, user perfers a list box.

May I hear your suggestion on this? is there any availabe code to implement the two options? Thank you.
By the way, I am using ASP NET together with C#  By the way, I am using ASP NET together with C#
01-Dec-04 07:17 AM
no VB
See if this custom repeater is of use  See if this custom repeater is of use
01-Dec-04 08:19 AM
http://www.eggheadcafe.com/articles/Custom_Repeater_Control.asp

BTW, you didn't resolve your problem by uninstalling IIS.  It is a permissions problem that will persist when you deploy your app to a production web server.  You'll need to either authenticate to a windows account with high enough permissions to start/stop services or automatically run the page under that account (as the sample I showed you does).

For security reasons, your ASP.NET pages are not run under windows accounts with access to do much of anything but process the page under the root of the web site or read files under the root of the web site.
Thank you  Robbe, I solved that problem  Another  Thank you Robbe, I solved that problem Another
02-Dec-04 07:39 AM
question I would like to consult with you is: how can I bind DataGrid to a dynamically increasing data source. e.g. a ArrayList with increasing number of items inside.

Basically what I want to do is I use an ArrayList to store the windows services, and then bind it the datagrid for display. If user stops all listed windows services by clicking "Stop All" button. I like to display the stopped service one by one(one row at a time), which means if a windows service is stopped first, it is displayed to the user. in the mean time, the 2nd windows service may be in the progress of being stopped, once it is done, 2nd windows service with status "stopped" is shown and then 3rd, 4th windows services....

it is simple to think about this implementation, but in reality, I find it difficult. I thought about to use a Page timer to keep retrieving the service status, but this requires a lot of interactions between the client and the server which I think is not desirable.

Thank you !!!
can I solve permission problem by changing IIS  can I solve permission problem by changing IIS
14-Dec-04 10:32 AM
Can I solve this problem by changing the IIS properties (e.g. Authentication properties)? last time, I remember I made some changes to the IIS properties, then suddenly I may start and stop the windows services...Thanks for the help
ASPNET account permission to startstop winservice  ASPNET account permission to startstop winservice
14-Dec-04 10:37 AM
we know that when we browse to an ASP.NET page, it runs under the ASPNET account by default not under the windows account I am logged in as. So in this case, user has no enought permisson rights to start / stop a windows services. I am wondering whether  we can solve this problem by changing the IIS properties (e.g. Authentication properties)? last time, I remember I made some changes to the IIS properties, then suddenly I may start and stop the windows services...Now, I cannot get the procedure back.....Thanks for the help
Create New Account
help
i want to do some authentication in this project. How To: Use Forms Authentication with SQL Server in ASP.NET 2.0 patterns & practices Developer Center J.D. Meier, Alex Mackman, Blaine Andy Wigley, Kishore Gopalan Microsoft Corporation August 2005 Applies To • ASP.NET version 2.0 • SQL Server 2000 Summary This How To shows you how you can use forms authentication with the SQL Server membership provider. Forms authentication with SQL Server is most applicable in situations where users of your application are not part of your
completed rendering. Eventually the connections timeout however it's likely that the maximum number of SQL Server connections will be exceeded when the SharePoint site is under load. I monitored the connection namespace WssTest { class Class1 { private static string virtualServerUrl = "http: / / 10.40.28.51 / "; / / your virtual server address here [STAThread] static void Main(string[] args) { using (SPGlobalAdmin globalAdmin = new SPGlobalAdmin()) { SPVirtualServer server = globalAdmin.OpenVirtualServer(new Uri(virtualServerUrl)); int x1 = server.Sites.Count; / / opens a database connection int x2 server.Sites.Count; / / no new connection using (SPWeb rootWeb = server.Sites[0].RootWeb) / / opens 2nd database connection { bool b1 = rootWeb.HasExternalSecurityProvider; / / opens 3rd database connection b2 = rootWeb.HasExternalSecurityProvider; / / no new connection } / / implicit rootWeb.Dispose() - - connection not closed using (SPWeb rootWeb = server.Sites[0].RootWeb) / / new SPWeb instance - - no new connection { bool b3 = rootWeb.HasExternalSecurityProvider; / / opens 4th
DBCC Memorystatus Results across a linked server SQL Server declare @lnvc_SQL nvarchar(4000) select @lnvc_SQL = N'select * from openquery([HQAPPSQL04], ''set fmtonly off; ' + ' exec lnvc_SQL Does anyone know why this only returns 1 result and not all of them? SQL Server Programming Discussions Microsoft.SqlServer.Server.SqlProcedure (1) SQL Server 2008 (1) SQL Server 2000 (1) SQL Server (1) Microsoft.SqlServer.Server (1) System.Data
System.Security.SecurityException: Request failed executing SQL Function created from vb.net assembly I am somewhat new to VB.NET. I have created a VB.Net 2005 assembly that I have inserted into my SQL database and created a SQL function from. I use the following SQL script to assembly (and its SQL function) into the database: - - Build the assembly(s). Location is variable depending on name of server. Select @D_PathToAssembly = ' \ Sql3 \ HDS8 \ _DEVSQL05 \ 05500 \ Assemblies \ ', @D_Assembly = @D_PathToAssembly + 'HDSExecuteApp.dll' CREATE ASSEMBLY ASM_HDSExecuteApp FROM fine. The HDSExecuteApp.dll calls another vb.net assembly (exe) that is located on the server. The Code Access Security for machine level trust to where this called .net exe resides and the exe) are signed with the same key. When I execute the function from SQL I get the following error: Msg 6522, Level 16, State 2, Line 1 A .NET
Performance of RevertToSelf and ImpersonateLoggedOnUser C++ / VB I have a server application which need to use Impersonation when connecting to databases, however, it need to use the answer is Thanks Charles Zhang Win32 Kernel Discussions Database (1) ImpersonateLoggedOnUser (1) RevertToSelf (1) WindowsImpersonationContext (1) ImpersonateNamedPipeClient (1) NtSetInformationThread (1) WindowsIdentity (1) ConfigurationManager (1) Hi Charles , I have checked the side issues on impersonation: 1. If you are designing a 3 tier application and your server application impersonate the client without using username / password explicitly(such as using ImpersonateNamedPipeClient), then you should take care of the delegation problem. If the server application impersonating the client is trying to connect to the 3rd machine database, the connection jump 2 hops. To resolve this problem, we have embeded the client username / password in server side explicitly and use LogonUser to obtain the token, or enable the kerberos delegation. 2 IS" with no warranties, and confers no rights. The sequence of the call in my server application is as follows LogonUser ImpersonateLoggedOnUser Connect (connect to database) RevertToSelf Right after the thread runs under Aspnet account(IIS5) which we do not assign enough permission to operate the Sql Server, then I impersonate the current thread as my domain account(which has enough right to