This is my App.Config -
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<setting name="RunAsWindowsService" serializeAs="String">
<value>True</value>
</setting>
<AppSettings>
<settings>
<settings>
<add key="ConnectionString" value="Server=WIN-OTVR1M4I567;Database=CresijCam;Integrated Security=SSPI;" />
</settings>
</settings>
</AppSettings>
</configuration>
This is my code for calling the method -
public partial class Service1 : ServiceBase
{
Thread th = null;
public Service1()
{
InitializeComponent();
th = new Thread(AsynchronousSocketListener.StartListening);
}
protected override void OnStart(string[] args)
{
try {
th.Start();
// Log an event to indicate successful start.
EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);
}
catch(Exception ex)
{
// Log the exception.
EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
}
protected override void OnStop()
{
th.Abort();
}
}
HEre is the code -
public class AsynchronousSocketListener
{
static string path = @"E:\F\trythis\TCPService\bin\Debug\TCPService.exe";
static Configuration config = ConfigurationManager.OpenExeConfiguration(path);
static string constr = config.AppSettings.Settings["ConnectionString"].Value;
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
private AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Establish the local endpoint for the socket.
// The DNS name of the computer
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1200);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(200);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
}
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
string ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
This service is to create a TCP listener that continuously works in background and updates data in database so that I can use that data through my web app. If you need code for the method called here.. I will Add that here.. But I think that code doesn't contain any error because that same code is working in windows form application.
Any suggestions will be appreciated. Thanks
I changed the code as per said here - https://stackoverflow.com/a/27544887/9650643
taking connection string from service.exe.config file.
static Configuration config = ConfigurationManager.OpenExeConfiguration("E:\\F\\trythis\\TCPService\\bin\\Debug\\TCPService.exe");
static string constr = config.AppSettings.Settings["ConnectionString"].Value;
Now I have a different issue -
Application: TCPService.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException at TCPService.AsynchronousSocketListener..cctor()
Exception Info: System.TypeInitializationException at TCPService.AsynchronousSocketListener.StartListening() at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Threading.ThreadHelper.ThreadStart()
I tried adding connection string in all different possible ways. I dont understand now what is causing this error
Added : How I am initializing databaseConfiguration string in above code. If possible please let me know If I am doing the initialization wrong. I have tried in 2-3 different ways. Another way I tried is - I removed appsetting and added this in App.config
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="CresijCamConnectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Data Source=WIN-OTVR1M4I567;Initial Catalog=CresijCam" providerName="System.Data.SqlClient"/>
</connectionStrings>
And I removed this that I created above in Class AsynchronousSocketListener
static string path = @"E:\F\trythis\TCPService\bin\Debug\TCPService.exe";
static Configuration config = ConfigurationManager.OpenExeConfiguration(path);
static string constr = config.AppSettings.Settings["ConnectionString"].Value;
And Added this in the class -
static string constr = ConfigurationManager.ConnectionStrings["CresijCamConnectionString"].ConnectionString;
But both are not working
App.Config had no configSection tag as first child of Configurations tag thats why service was not able to read settings. Now It is working fine.