Error: Object reference not set to an instance of an object for Window Service Appconfig file not exist in the same folder for Window Service in ASP.Net

dipad10
 
on Jan 27, 2017 07:24 AM
3115 Views

hello, can i copy the exe file and the appconfig only into a single folder in my c drive? will it work that way?

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Indresh
 
on Jan 27, 2017 07:26 AM
on Jan 27, 2017 07:27 AM

Hi dipad10,

Will you please explain more detail about your requirement?

 

dipad10
 
on Jan 27, 2017 07:35 AM

im dealing with simple window service creation in c#. i have completed the window service but after i run the service, i get this error in the servicelog.txt saying

"Simple Service started 27/01/2017 03:22:31 PM

Simple Service Error on: 27/01/2017 03:22:31 PM Object reference not set to an instance of an object.   at WindowsService.Service1.ScheduleService()"

Someone said i should paste the appconfig with the exe into the same folder which i did.i want to know if am to copy the rest of the bin folder alongside with the exe file.

heres my service.cs code for your review.

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.IO;
using System.Threading;
using System.Configuration;
using System.Data.SqlClient;
using System.Net.Mail;
namespace WindowsService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            this.WriteToFile("Simple Service started {0}");
            this.ScheduleService();
        }

        protected override void OnStop()
        {
            this.WriteToFile("Simple Service stopped {0}");
            this.Schedular.Dispose();
        }

        private Timer Schedular;

        public void ScheduleService()
        {
            try
            {
                Schedular = new Timer(new TimerCallback(SchedularCallback));
                string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
                this.WriteToFile("Simple Service Mode: " + mode + " {0}");

                //Set the Default Time.
                DateTime scheduledTime = DateTime.MinValue;

                if (mode == "DAILY")
                {
                    //Get the Scheduled Time from AppSettings.
                    scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next day.
                        scheduledTime = scheduledTime.AddDays(1);
                    }
                }

                if (mode.ToUpper() == "INTERVAL")
                {
                    //Get the Interval in Minutes from AppSettings.
                    int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);

                    //Set the Scheduled Time by adding the Interval to Current Time.
                    scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next Interval.
                        scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
                    }
                }

                TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
                string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);

                this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");

                //Get the difference in Minutes between the Scheduled and Current Time.
                int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);

                //Change the Timer's Due Time.
                Schedular.Change(dueTime, Timeout.Infinite);
            }
            catch (Exception ex)
            {
                WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);

                //Stop the Windows Service.
                using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
                {
                    serviceController.Stop();
                }
            }
        }

        private void SchedularCallback(object e)
        {
            try
            {
                DataTable dt = new DataTable();
                string query = "select * from Tickets where DueDate < @duedate and Status='OPEN'";
                string constr = ConfigurationManager.ConnectionStrings["GuruHelpDeskConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@duedate", DateTime.Now);
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            sda.Fill(dt);
                        }
                    }
                }
                foreach (DataRow row in dt.Rows)
                {
                    string ticketno = row["TicketID"].ToString();
                    string email = row["AssigneeEmail"].ToString();
                    WriteToFile("Trying to send email to: " + email + " " + ticketno);

                    using (MailMessage mm = new MailMessage("info@gurugeeksroyalty.biz", email))
                    {
                        mm.Subject = "Tickets Due!";


                        mm.Body = string.Format("Ticket <b>{0}</b> is Due<br /><br /> Please Attend to this ticket or consider it closed", ticketno);

                        mm.IsBodyHtml = true;
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = ConfigurationManager.AppSettings["Host"];
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = ConfigurationManager.AppSettings["UserName"];
                        credentials.Password = ConfigurationManager.AppSettings["Password"];
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                        smtp.Send(mm);
                        WriteToFile("Email sent successfully to: " + email + " " + ticketno);
                    }
                }
                this.ScheduleService();
            }
            catch (Exception ex)
            {
                WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);

                //Stop the Windows Service.
                using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
                {
                    serviceController.Stop();
                }
            }
        }
        private void WriteToFile(string text)
        {
            string path = "C:\\ServiceLog.txt";
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
                writer.Close();
            }
        }
    }
}

 

Indresh
 
on Jan 27, 2017 07:38 AM

Hi dipad10,

Please refer the below link.

Simple Window Service