0

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;

enter link description here

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.

Usha phulwani
  • 184
  • 4
  • 22
  • `TypeInitializationException` is often cause through errors in static constructors. See if any of those might be failing. Please post relevant code. – Nisarg Shah Aug 31 '18 at 07:57
  • 2
    And I think `System.Configuration.ConfigurationManager.get_ConnectionStrings()` is main issue. – Renatas M. Aug 31 '18 at 07:58
  • See: https://stackoverflow.com/questions/12425199/type-initialization-exception and https://stackoverflow.com/questions/7017043/typeinitializationexception-exception-on-creating-an-object – Nisarg Shah Aug 31 '18 at 07:58
  • Added relevant code above. And I am not creating any object here. I am directly calling the method. So Static constructors is not an issue I think. – Usha phulwani Aug 31 '18 at 08:16
  • 1
    @Reniuz is right, you need to obtain the actual error from the `ConfigurationErrorsException`. Perhaps the `SqlClient` is not registered. – CodeCaster Aug 31 '18 at 08:19
  • @CodeCaster As you said I searched a little about the issue. And I think you guys are right. I have read that windows service doesn't read from app.config after installation and my connectionstring is in app.config. that might be causing the issue. I will change it now and try and will update here the results. – Usha phulwani Aug 31 '18 at 08:29
  • @Reniuz I edited the code but received the same issue – Usha phulwani Aug 31 '18 at 08:49
  • Hard code your connection string and do not pull it from config. See what happens then. If it works than you will have to work out the issue with app configuration. – Renatas M. Aug 31 '18 at 09:24
  • @Reniuz connection string is resolved I think...because after adding that line of codes. Its now giving different error. But I dont know the reason for this error now. I am trying to find out – Usha phulwani Aug 31 '18 at 09:26
  • @Reniuz.. There are 2 exceptions now - NullReference and TypeInitialization. – Usha phulwani Aug 31 '18 at 09:33
  • It is not resolved! You getting NullReferenceException which is absolutely clear that `config == null` or `config.AppSettings.Settings["CresijCamConnectionString"] == null`. – Renatas M. Aug 31 '18 at 09:35
  • @Reniuz... OOps!! I thought its resolved... I will first hardcode connectionstring and check.. – Usha phulwani Aug 31 '18 at 09:37
  • @Reniuz.. I am again getting the error that I was getting in beginning. ConfigurationExceptions – Usha phulwani Aug 31 '18 at 09:49
  • @CodeCaster... This is the new issue Description: **The process was terminated due to an unhandled exception. Exception Info: System.NullReferenceException at TCPService.AsynchronousSocketListener..cctor()** – Usha phulwani Aug 31 '18 at 10:08
  • @Reniuz.. Still null reference.. – Usha phulwani Aug 31 '18 at 10:22
  • Now I have no idea what you are doing... – Renatas M. Aug 31 '18 at 10:35
  • You are aware that `Thread.Abort` is probably the worst way of achieving shutdown possible, aren't you? Not related to your current problem, but whilst it's still in your code, don't consider your work to be "done". – Damien_The_Unbeliever Aug 31 '18 at 10:52
  • @Damien_The_Unbeliever Removed it – Usha phulwani Aug 31 '18 at 10:55
  • I now know, the issue is not with configuration. the issue is with constructor. The exception is thrown while initialization only. But I dont know how will I resolve it because whatever solution I found till now its not working for me – Usha phulwani Aug 31 '18 at 11:48
  • What does `AcceptCallback()` look like? – Matt Davis Aug 31 '18 at 20:20
  • @MattDavis this is the error and I am getting it on line where I am calling StartListening() method. I have added the code for accept call back. But I think the issue is with constructor. – Usha phulwani Sep 04 '18 at 00:45
  • @MattDavis... Error **{"The type initializer for 'TCPService.AsynchronousSocketListener' threw an exception."}** All the methods in class are static and I think may be that's why there is error and may be I am missing something with constructor – Usha phulwani Sep 04 '18 at 00:51
  • @Reniuz.. you guys were right. After I removed connection string Config.. It didn't throw any exception so That's the LOC which was throwing error. I now just need to figure out how else can I initialize that string. – Usha phulwani Sep 04 '18 at 01:23
  • @Reniuz,... 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. – Usha phulwani Sep 04 '18 at 03:39

0 Answers0