.NETGURU
windows service with C#
Messages   Related Types
This message was discovered on ASPFriends.com 'ngfx-services' list.
Responses highlighted in red are from those people who are likely to be able to contribute good, authoratitive information to this discussion. They include Microsoft employees, MVP's and others who IMHO contribute well to these kinds of discussions.

Wally McClure

Anyone out there writing Windows Services with C#? I have written a Window=
s Service with VB.NET. It runs perfectly. I have tried to translate it in=
to C#. The c# service compiles properly and installs. When I try and star=
t the service, I get an error stating that the service did not start in a t=
imely manner (Error 1053). The service merely gets a value from a MSMQ Que=
ue and inputs some data into a db table. I don=92t think my problem is in =
my install routine, so I have not included it. I have been looking through=
the documentation and the MSDN MQ C# example app on MSDN. I can=92t see a=
nything that I have done that is different from the example app, but obviou=
sly there is something wrong with my code. If you have any thoughts regard=
ing this, please let me know.

Wally

I have included my code below:

using System;

using System.Data;

using System.Data.OleDb;

using System.Data.SqlClient;

using System.ServiceProcess;

using System.Configuration;

using System.Messaging;

using System.Diagnostics;

using System.Reflection;

namespace MSMQDBService

{

/// <summary>

/// Summary description for MSMQDBServiceClass.

/// </summary>

public class MSMQDBServiceClass : ServiceBase

{

public static readonly string pstrMSMQDBServiceName =3D "MSMQDB=
ServiceCS";

public static readonly string pstrMSMQDBServiceDesc =3D "MSMQDB=
ServiceCS";

private string pServiceName =3D MSMQDBServiceClass.pstrMSMQDBSe=
rviceName;

private string pstrServerName;

private string pstrQueueName;

private string pstrQueue;

private bool pblSQLClient;

private string pstrSqlCn;

private string pstrOleDbCn;

private MessageQueue pMQ;

private string pstrServiceStarted =3D pstrMSMQDBServiceName + "=
service started.";

private string pstrServiceStopped =3D pstrMSMQDBServiceName + "=
service stopped.";

private string pstrServicePaused =3D pstrMSMQDBServiceName + " =
service paused.";

private string pstrServiceContinue =3D pstrMSMQDBServiceName + =
" service continue.";

private string pstrServicePowerEvent =3D pstrMSMQDBServiceName =
+ " service power event detected.";

private void InitializeComponent()

{

}

public static void Main()

{

ServiceBase.Run(new MSMQDBServiceClass());

}

public MSMQDBServiceClass()

{

ServiceName =3D pServiceName;

CanStop =3D true;

AutoLog =3D true;

CanShutdown =3D true;

CanPauseAndContinue =3D true;

CanHandlePowerEvent =3D true;

}

protected override void OnStart(string[] args)

{

pstrServerName =3D ConfigurationSettings.AppSettings["MSM=
QServerName"];

pstrQueueName =3D ConfigurationSettings.AppSettings["MSMQ=
QueueName"];

pstrQueue =3D pstrServerName + "\\" + pstrQueueName;

pblSQLClient =3D Convert.ToBoolean(ConfigurationSettings.=
AppSettings["UseSQLClient"]);

pstrSqlCn =3D ConfigurationSettings.AppSettings["SQLClien=
tString"];

pstrOleDbCn =3D ConfigurationSettings.AppSettings["OleDbC=
lientString"];

EventLog.WriteEntry(pstrMSMQDBServiceName,pstrServiceStar=
ted);

pMQ =3D new MessageQueue();

pMQ.Path =3D pstrQueue;

pMQ.Formatter =3D new XmlMessageFormatter(new string[]{"S=
ystem.String, mscorlib"});

pMQ.ReceiveCompleted +=3D new ReceiveCompletedEventHandle=
r(this.MQ_ReceiveCompleted);

pMQ.BeginReceive();

}

private void MQ_ReceiveCompleted(object sender, ReceiveComplete=
dEventArgs e)

{

// Add code here to respond to message.

Message msg =3D pMQ.EndReceive(e.AsyncResult);

msg.Formatter =3D new XmlMessageFormatter(new String[]{"S=
ystem.String, mscorlib"}); //new XmlMessageFormatter(new String(){"System.S=
tring, mscorlib"});

string strBody =3D (string)msg.Body;

string strSql =3D "insert into tblMQ (DatePlacedInQueue, =
DateProcessedByService) values ('" + strBody + "',getdate())";

try

{

if (pblSQLClient =3D=3D true)

{

SqlConnection sqlCn =3D new SqlConnection(pst=
rSqlCn);

SqlCommand sqlCm =3D new SqlCommand( strSql, =
sqlCn);

sqlCn.Open();

sqlCm.ExecuteNonQuery();

sqlCm.Dispose();

sqlCn.Close();

sqlCn.Dispose();

}

else

{

OleDbConnection oledbCn =3D new OleDbConnecti=
on(pstrSqlCn);

OleDbCommand oledbCm =3D new OleDbCommand( st=
rSql, oledbCn);

oledbCn.Open();

oledbCm.ExecuteNonQuery();

oledbCm.Dispose();

oledbCn.Close();

oledbCn.Dispose();

}

}

catch (SqlException exc )

{

EventLog.WriteEntry(pstrMSMQDBServiceName, "SQLExce=
ption Message: " + exc.Message);

}

catch (OleDbException exc )

{

EventLog.WriteEntry(pstrMSMQDBServiceName, "SQLExce=
ption Message: " + exc.Message);

}

catch (Exception exc )

{

EventLog.WriteEntry(pstrMSMQDBServiceName, "Excepti=
on Message: " + exc.Message);

}

finally

{

pMQ.BeginReceive();

}

}

protected override void OnStop()

{

}

protected override void OnPause()

{

}

protected override void OnContinue()

{

pstrServerName =3D ConfigurationSettings.AppSettings["MSM=
QServerName"];

pstrQueueName =3D ConfigurationSettings.AppSettings["MSMQ=
QueueName"];

pstrQueue =3D pstrServerName + "\\" + pstrQueueName;

pblSQLClient =3D Convert.ToBoolean(ConfigurationSettings.=
AppSettings["UseSQLClient"]);

pstrSqlCn =3D ConfigurationSettings.AppSettings["SQLClien=
tString"];

pstrOleDbCn =3D ConfigurationSettings.AppSettings["OleDbC=
lientString"];

pMQ.Path =3D pstrQueue;

pMQ.Formatter =3D new XmlMessageFormatter(new string[]{"S=
ystem.String, mscorlib"});

pMQ.BeginReceive();

}

protected void OnPowerEvent()

{

}

}

}

McClure Development

865-693-3004

118 Durwood Rd.

Knoxville, TN 37922

Reply to this message...
 
    
Mitch Denny (VIP)
Wally,

Reading your source, I can't see anything that stop the service
initializing. In your ServiceInstaller, what is the name of the
service that you have defined for the SCM?

The name in the source that you sent was "MSMQDBServiceCS", if the
name specified in the SCM/ServiceInstaller isn't that then when
you tell the SCM to start whatever it is named, it will indeed kick
off the above service, but when it finishes starting up and posts
it status to the SCM, then the SCM won't care because it is looking
for it under another name.

Hopefully that should solve it for you, otherwise post the complete
source to the list and we can take it further.

Hope this helps.

----------------------------------------
- Mitch Denny
- http://www.warbyte.com
- Click here to reveal e-mail address
- +61 (414) 610-141
-

[Original message clipped]

Reply to this message...
 
    
Wally McClure
Mitch,

thanks for taking a look into this. I have checked and my installer is
using the same name as the service name in the below code snippet. I have
included a copy of my install routine source for everyone to look at. I am
wondering if there is something within my install routine that I have forgot
to place in it. My Install routine is the exact same as the one used by the
MSMQ C# example on MSDN. I am wondering if there is something more specific
for my app that is needed?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/ht
ml/csharpmsmq.asp?frame=true

Wally

namespace MSMQDBService
{
    using System;
    using System.Collections;
    using System.Configuration.Install;
    using System.ServiceProcess;
    using System.ComponentModel;
    using System.Diagnostics;

    /// <summary>
    /// Summary description for MSMQDBServiceClassInstaller.
    /// </summary>
    [RunInstallerAttribute(true)]
    public class MSMQDBServiceClassInstaller : Installer
    {
        private ServiceInstaller serviceInstaller;
        private ServiceProcessInstaller processInstaller;

        public MSMQDBServiceClassInstaller()
        {
            //
            // TODO: Add constructor logic here
            //
            serviceInstaller = new ServiceInstaller();
            serviceInstaller.StartType = ServiceStartMode.Manual;
            serviceInstaller.ServiceName = MSMQDBServiceClass.pstrMSMQDBServiceName;
            serviceInstaller.DisplayName = MSMQDBServiceClass.pstrMSMQDBServiceDesc;
            Installers.Add(serviceInstaller);

            // define and create the process installer
            processInstaller = new ServiceProcessInstaller();
             processInstaller.Account = ServiceAccount.LocalSystem;

            Installers.Add(processInstaller);
        }
    }
}

-----Original Message-----
From: Mitch Denny [mailto:Click here to reveal e-mail address]
Sent: Monday, September 10, 2001 12:20 AM
To: ngfx-services
Subject: [ngfx-services] RE: windows service with C#

Wally,

Reading your source, I can't see anything that stop the service
initializing. In your ServiceInstaller, what is the name of the
service that you have defined for the SCM?

The name in the source that you sent was "MSMQDBServiceCS", if the
name specified in the SCM/ServiceInstaller isn't that then when
you tell the SCM to start whatever it is named, it will indeed kick
off the above service, but when it finishes starting up and posts
it status to the SCM, then the SCM won't care because it is looking
for it under another name.

Hopefully that should solve it for you, otherwise post the complete
source to the list and we can take it further.

Hope this helps.

----------------------------------------
- Mitch Denny
- http://www.warbyte.com
- Click here to reveal e-mail address
- +61 (414) 610-141
-

[Original message clipped]

| [ngfx-services] member Click here to reveal e-mail address = YOUR ID
| http://www.asplists.com/asplists/aspngbeta.asp = JOIN/QUIT
| http://www.asplists.com/search = SEARCH Archives

Reply to this message...
 
    
Mitch Denny (VIP)
Wally,

OK. I don't have MSMQ here so I can't kick-off those pieces of code
to test it out. What I did is stripped out the MSMQ stuff and the
places where you read in the configuration leaving pretty much the
shell of a well formed service. I compiled and installed it and
it came up OK. This leads me to suspect that MSMQ is causing the
problem here.

I see the following line in the source for
the ServiceBase derived class:

    pMQ.BeginReceive();

Now, according to the documentation, this is an async operation
which should return immediately, but I am just wondering if it
does any work before. The BeginRecieve() method calls the
RecieveAsnc(...)
method which by the looks of the IL does a fair bit of initialization,
including some authorization work. Could it be getting hung up
there? Maybe. It still doesn't explain why this worked from VB.NET
and not C#.

I guess the first step is to comment out the MSMQ stuff (don't worry
about the config stuff, I just did that because I didn't have the
configuration file ... is it possible that your configuration file
isn't being read?) and kick off the service. It should start OK
and stay up.

Post back to the list once you have done that and we will
continue from there.

----------------------------------------
- Mitch Denny
- http://www.warbyte.com
- Click here to reveal e-mail address
- +61 (414) 610-141
-

[Original message clipped]

Reply to this message...
 
 
System.ComponentModel.RunInstallerAttribute
System.Configuration.ConfigurationSettings
System.Convert
System.Data.OleDb.OleDbCommand
System.Data.OleDb.OleDbConnection
System.Data.OleDb.OleDbException
System.Data.SqlClient.SqlCommand
System.Data.SqlClient.SqlConnection
System.Data.SqlClient.SqlException
System.Diagnostics.EventLog
System.Messaging.MessageQueue
System.Messaging.ReceiveCompletedEventArgs
System.Messaging.ReceiveCompletedEventHandler
System.Messaging.XmlMessageFormatter
System.ServiceProcess.ServiceAccount
System.ServiceProcess.ServiceBase
System.ServiceProcess.ServiceInstaller
System.ServiceProcess.ServiceProcessInstaller
System.ServiceProcess.ServiceStartMode
System.String




ExamGuru IT Solutions - .Net Guru is owned and operated by ExamGuru, Inc., the man behind .Net Guru. If you're in the market for bespoke software or software consultancy, why not get him and his highly trained team to help? - www.examguru.net/ITCertification
Ad


Need Dot Net Interview Questions?
Ask ExamGuru, Inc. for advice and help on Passing .Net Interviews
.Net Projects
Best-of-breed application framework for .NET projects, developed by ExamGuru, Inc. and ExamGuru IT
Free .net Help
Commission ExamGuru, Inc. and his team for your next bespoke software project
FogBUGZ
The only bug tracking system carefully crafted with one goal in mind: helping teams create great software.
Awesome Tools
If you don't know about these, you're missing out... IT Certification Questions
IT Interview Questions
Free Oracle 10g Training
MCSE Boortcamp
Cisco Study Guides
Cheap Study Guides
Exact Questions
Dot Net Interview Questions
Oracle OCP
Cheap Travel
Designer Perfumes - Wholesale Prices
Free Programming Tutorials
 
ExamGuru IT Solutions - .Net Guru is owned and operated by ExamGuru, Inc., the man behind .Net Guru. If you're in the market for bespoke software or software consultancy, why not get him and his highly trained team to help? - www.examguru.net/ITCertification
 Copyright © ExamGuru, Inc. 2001-2006
Contact Us - Terms of Use - Privacy Policy - www.dot-net-guru.com - www.examguru.net - www.oraclesource.net - www.itinterviews.net - www.examguru.net/ITCertification