none
Open Configuration File from Windows Service RRS feed

  • Question

  • Hi,

    I am trying below code in Windows Service project but it's to writing the connection string to the EventLog nor an exception

    What I am missing here? and How can I fix this so I can open the config file?

    try
    {
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = @"c:\temp\MaxMonUI.exe.config";
        Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
    
        var connection = System.Configuration.ConfigurationManager.ConnectionStrings["MaxMonConnection"].ConnectionString;
    
        eventLogMaxMon.WriteEntry("Connection: " + connection);
    }
    catch (Exception ex)
    {
        eventLogMaxMon.WriteEntry(ex.StackTrace);
    }
    

    Thanks,

    Jassim

    Friday, July 19, 2019 12:07 AM

All replies

  • Hi Jassim Rahma, 

    Thank you for posting here.

    Based on your description, I cannot reproduce your problem.

    Could you provide more details about your exception with which line of the code thrown the exception and some code about ‘eventLogMaxMon’? It will help us to do the test.

    We are waiting for your update.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, July 19, 2019 8:14 AM
    Moderator
  • There is no exception thrown, that's the problem.

    but based on my code if successful then this should be written in the EventLog:

    eventLogMaxMon.WriteEntry("Connection: " + connection);

    and if faled this should be written in the EventLog:

    eventLogMaxMon.WriteEntry(ex.StackTrace);

    and non is happening..

    Here is the full code:

                
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    using System.Timers;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace MaxMon
    {
        public partial class MaxMon : ServiceBase
        {
            public MaxMon()
            {
                InitializeComponent();
    
                /*
                ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
                ServiceInstaller serviceInstaller = new ServiceInstaller();
    
                serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
                serviceProcessInstaller.Username = null;
                serviceProcessInstaller.Password = null;
    
                serviceInstaller.ServiceName = "MaxMon Monitoring";
                serviceInstaller.Description = "The service which handles the monitoring of MaxMon.";
                serviceInstaller.StartType = ServiceStartMode.Automatic;
                */
    
                eventLogMaxMon = new System.Diagnostics.EventLog();
    
                if (!System.Diagnostics.EventLog.SourceExists("MaxMon"))
                {
                    System.Diagnostics.EventLog.CreateEventSource("MaxMon", "MaxMonLog");
                }
    
                eventLogMaxMon.Source = "MaxMon";
                eventLogMaxMon.Log = "MaxMonLog";
            }
    
            protected override void OnStart(string[] args)
            {
                eventLogMaxMon.WriteEntry("MaxMon Service Started.");
    
                // Set up a timer that triggers every minute.
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Interval = 60000; // 60 seconds
                timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
                timer.Start();
            }
    
            public void OnTimer(object sender, ElapsedEventArgs args)
            {
                try
                {
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                    fileMap.ExeConfigFilename = @"c:\temp\MaxMonUI.exe.config";
                    Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
    
                    var connection = System.Configuration.ConfigurationManager.ConnectionStrings["MaxMonConnection"].ConnectionString;
    
                    eventLogMaxMon.WriteEntry("Connection: " + connection);
                }
                catch (Exception ex)
                {
                    eventLogMaxMon.WriteEntry(ex.StackTrace);
                }
    
                eventLogMaxMon.WriteEntry("Monitoring the System", EventLogEntryType.Information, 1000);
    
                PingTo("103.1.175.1");
            }
    
            protected override void OnStop()
            {
                eventLogMaxMon.WriteEntry("MaxMon Service Stopped.");
            }
    
            private void PingTo(string address)
            {
                try
                {
                    Ping pingSender = new Ping();
                    PingOptions options = new PingOptions();
    
                    // Use the default Ttl value which is 128,
                    // but change the fragmentation behavior.
                    options.DontFragment = true;
    
                    // Create a buffer of 32 bytes of data to be transmitted.
                    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                    byte[] buffer = Encoding.ASCII.GetBytes(data);
                    int timeout = 120;
    
                    IPAddress ip_host = IPAddress.Parse(address);
    
                    PingReply reply = pingSender.Send(ip_host, timeout, buffer, options);
    
                    if (reply.Status == IPStatus.Success)
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(address);
    
                        // save result in database;
                        using (SqlConnection sql_connection = new SqlConnection("Server=.\\MAXMON; Database=maxmon; User Id=maxmon; Password=maxmon; Integrated Security=False;"))
                        // using (SqlConnection sql_connection = new SqlConnection("Data Source=.\\MAXMON;Initial Catalog=maxmon;Integrated Security=False;"))
                        {
                            SqlCommand sql_command = new SqlCommand("sp_ping", sql_connection);
                            sql_command.CommandType = CommandType.StoredProcedure;
                            sql_command.Parameters.Add(new SqlParameter("@address_id", 9999));
                            sql_command.Parameters.Add(new SqlParameter("@address_ip", address));
                            sql_command.Parameters.Add(new SqlParameter("@address_name", hostEntry.HostName));
                            sql_command.Parameters.Add(new SqlParameter("@roundtrip_time", reply.RoundtripTime));
                            sql_command.Parameters.Add(new SqlParameter("@ttl", reply.Options.Ttl));
                            sql_command.Parameters.Add(new SqlParameter("@dont_fragment", reply.Options.DontFragment));
                            sql_command.Parameters.Add(new SqlParameter("@reply_length", reply.Buffer.Length));
    
                            sql_command.Connection.Open();
                            sql_command.ExecuteNonQuery();
                        }
                    }
    
                    eventLogMaxMon.WriteEntry("Pinging Completed", EventLogEntryType.Information, 1000);
                }
                catch (Exception ex)
                {
                    eventLogMaxMon.WriteEntry(ex.StackTrace, EventLogEntryType.Error, 1000);
                }
            }
        }
    }
    
    
    
    
    
    
    
    


    Friday, July 19, 2019 1:51 PM
  • Hi Jassim Rahma, 

    Thanks for the feedback.

    >> and non is happening..

    If ‘eventLogMaxMon.WriteEntry("MaxMon Service Started.")’ works correctly in OnTimer() method, I suggest you use breakpoints to find whether OnTimer() method is executed.

    Change the time interval to 2 seconds:

    timer.Interval = 2000;

    It will be helpful to see the results quickly.

    We are waiting for your result after testing.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, July 22, 2019 9:46 AM
    Moderator