首次成功运行后,Windows服务会自动停止

时间:2018-06-18 09:24:58

标签: c# windows-services

我已经创建了24小时后运行的Windows服务调度程序,当我第一次在数据库中输入数据时查看服务时,它运行得很好。 但在第二次运行服务停止,但我希望服务不断运行。

我已经为它创建了调度程序以及每分钟运行它,但数据仅在时间匹配时插入。

 public void StartService(object e)
    {
        try {
            //ExtractorEventLog("0", null);
            List<PracticeInformation> getServiceTime = GetpracticeInformationList();
            var gettime = (from t in getServiceTime
                           select new PracticeInformation
                           {
                               extractor_start_time = t.extractor_start_time
                           }).OrderByDescending(x => x.id).ToList().FirstOrDefault();

            DateTime SetdateTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]);
            if (gettime != null)
            {
                SetdateTime = DateTime.Parse(gettime.extractor_start_time.ToString());
            }
            try
            {
                if (SetdateTime.ToString("HH:mm") == DateTime.Now.ToString("HH:mm"))
                {
                    ExtractorEventLog(SetdateTime.ToString("HH:mm") + " " + DateTime.Now.ToString("HH:mm"), null);
                    string strFile = @"C:\requiredFilesForDDP\Temp" + DateTime.Now.Ticks.ToString() + ".csv";
                    if (connm == "")
                    {
                       GetConnectionString();
                    }
                    using (OdbcConnection conn = new OdbcConnection(connm))
                    {
                        //ExtractorEventLog(connm, null);
                        conn.Open();
                        #region  Get Hospital data 
                        var id = 0;
                        try
                        {
                            List<PracticeInformation> practiceList = getServiceTime;
                            var practiceName = practiceList[0].name;
                            id = practiceList[0].id;
                            List<PracticeInformationModel> HospitalAll = new List<PracticeInformationModel>();
                            using (OdbcCommand com = new OdbcCommand(Common.cmdGetHospital, conn))
                            {
                                using (OdbcDataReader readerHospital = com.ExecuteReader())
                                {
                                    HospitalAll = DataReaderMapToList<PracticeInformationModel>(readerHospital);
                                    List<PracticeInformationModel> objPracticeInformationmodel = (from pi in HospitalAll
                                                                                                  select new PracticeInformationModel
                                                                                                  {
                                                                                                      practice_name = pi.practice_name,
                                                                                                      phone = pi.phone
                                                                                                  }
                                                                                        ).ToList();

                                    var getPracticeName = practiceList.Select(x => new { x.name }).ToList();
                                    List<PracticeInformationModel> objpracticelist = objPracticeInformationmodel.Where(x => !getPracticeName.Any(y => y.name == x.practice_name)).ToList();
                                    DataTable PracticeInformationDT = ToDataTable(objpracticelist);  // To save PracticeInformation table 
                                    using (MySqlConnection sqConn = new MySqlConnection(Common.connectionStringDB))
                                    {
                                        using (SqlBulkCopy blkcopyPi = new SqlBulkCopy(sqConn.ConnectionString, SqlBulkCopyOptions.KeepNulls))
                                        {
                                            CreateCSVfile(PracticeInformationDT, strFile);
                                            if (!File.Exists(strFile))
                                            {
                                                FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
                                                fs.Close();
                                                fs.Dispose();
                                            }
                                            if (sqConn.State == ConnectionState.Open)
                                            {
                                                sqConn.Close();
                                            }
                                            sqConn.Open();
                                            MySqlBulkLoader bcp1 = new MySqlBulkLoader(sqConn);
                                            bcp1.TableName = "PracticeInformation"; //Create PracticeInformation table into MYSQL database...
                                            bcp1.FieldTerminator = ",";
                                            bcp1.LineTerminator = "\r\n";
                                            bcp1.FileName = strFile;
                                            bcp1.NumberOfLinesToSkip = 0;
                                            bcp1.Load();
                                            try
                                            {
                                                File.Delete(strFile);
                                            }
                                            catch (Exception ex)
                                            {
                                                ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
                                            }
                                        }
                                        readerHospital.Close();
                                    }
                                }
                            }
                            #endregion
                        #region  Get Provider Data From Dentrix
                            List<Provider> ProviderAll = new List<Provider>();
                            using (OdbcCommand com = new OdbcCommand(Common.cmdGetProvider, conn))
                            {
                                using (OdbcDataReader readerProvider = com.ExecuteReader())
                                {
                                    ProviderAll = DataReaderMapToList<Provider>(readerProvider);
                                    List<Provider> objProvider = (from pro in ProviderAll
                                                                  select new Provider
                                                                  {
                                                                      provider_id = pro.provider_id,
                                                                      first_name = pro.first_name,
                                                                      last_name = pro.last_name,
                                                                      work_phone = pro.work_phone
                                                                  }).ToList();
                                }
                            }
                            #endregion
                        #region  Add Appointment
                            using (OdbcCommand com = new OdbcCommand(Common.cmdText, conn))
                            {
                                using (OdbcDataReader reader = com.ExecuteReader())
                                {
                                    List<AllModalFromApplointment> AppointmentListAll = new List<AllModalFromApplointment>();
                                    AppointmentListAll = DataReaderMapToList<AllModalFromApplointment>(reader);
                                    List<Alert> patientalert_id = new List<Alert>();
                                    #region Get alert data 
                                    MySqlConnection connection = null;
                                    List<string> target = new List<string>();
                                    EventLog(Common.Get_Pre_Med_Alerts);
                                    ExtractorEventLog(Common.Get_Pre_Med_Alerts, id.ToString());
                                    int add = 0;
                                    int alert_count = 0;
                                    //string connectionStringDB = "server=192.168.0.1;user=dentrix;database=db_dentrix;password=dentrix";
                                    connection = new MySqlConnection(Common.connectionStringDB);
                                    foreach (var i in AppointmentListAll.Select(x => x.patient_id).ToList())
                                    {
                                        if (i != 0)
                                        {
                                            OdbcCommand ODBCCommand = new OdbcCommand("{call admin.sp_getpatientmedalerts (?)}", conn);
                                            ODBCCommand.CommandType = CommandType.StoredProcedure;
                                            ODBCCommand.Parameters.AddWithValue("@patient_guid", i); //4898-11738
                                            ODBCCommand.ExecuteNonQuery();
                                            OdbcDataReader a = ODBCCommand.ExecuteReader();
                                            DataTable getAlert = new DataTable();
                                            if (a.HasRows)
                                            {
                                                target.Add(i.ToString());
                                                alert_count = add + 1;
                                                getAlert.Load(a);
                                                a.Close();
                                            }
                                        }
                                    }
                                    ExtractorEventLog(target.Count() + " " + Common.No_Of_Pre_Med_Alert, null);
                                    #endregion

                                    #region
                                    List<AppointmentDetail> objAppointment = (from app in AppointmentListAll
                                                                              join pro in ProviderAll on app.provider_id equals pro.provider_id
                                                                              select new AppointmentDetail
                                                                              {
                                                                                  patient_id = Convert.ToInt64(app.patient_guid),
                                                                                  appointment_id = Convert.ToInt64(app.appointment_id),
                                                                                  appointment_timestamp = Convert.ToString(app.appointment_date.AddHours(app.start_hour).AddMinutes(app.start_minute)),
                                                                                  patient_first_name = app.patient_name.Split(',')[0],
                                                                                  patient_last_name = app.patient_name.Split(',')[1],
                                                                                  patient_phone_number = app.patient_phone,
                                                                                  red_cross_flag = target.Any(x => x.ToString().Contains(app.patient_id.ToString())) ? "Y" : "N",
                                                                                  dr_name = pro.first_name.Trim() + ' ' + pro.last_name.Trim(),
                                                                                  dr_phone = HospitalAll[0].phone,
                                                                                  hospital_name = HospitalAll[0].practice_name,
                                                                                  appointment_type = null,
                                                                                  fees = 0,
                                                                                  status = null
                                                                                  //createdDate = DateTime.UtcNow
                                                                              }).ToList();

                                    //Ristrict duplicate records
                                    ExtractorEventLog(Common.Data_Inserting, id.ToString());
                                    List<AppointmentDetail> usethe = GetAppointmentList();
                                    var query = usethe.Select(x => new { x.appointment_id }).ToList();
                                    List<AppointmentDetail> xyz = objAppointment.Where(x => !query.Any(y => y.appointment_id == x.appointment_id)).ToList();
                                    if (xyz != null && xyz.Count != 0)
                                    {
                                        var from = xyz.First().appointment_timestamp;
                                        var to = xyz.Last().appointment_timestamp;
                                        ExtractorEventLog(Common.Get_Appointment_Date + from + "and" + to, id.ToString());
                                    }
                                    else
                                    {
                                        EventLog("No appointmet present");
                                    }
                                    int appointment_count = xyz.Count();
                                    DataTable appointmentDT = ToDataTable(xyz);  // To save appointment table 
                                    using (MySqlConnection sqConn = new MySqlConnection(Common.connectionStringDB))
                                    {
                                        using (SqlBulkCopy blkcopy = new SqlBulkCopy(sqConn.ConnectionString, SqlBulkCopyOptions.KeepNulls))
                                        {
                                            CreateCSVfile(appointmentDT, strFile);
                                            if (!File.Exists(strFile))
                                            {
                                                FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
                                                fs.Close();
                                                fs.Dispose();
                                            }
                                            if (sqConn.State == ConnectionState.Open)
                                            {
                                                sqConn.Close();
                                            }
                                            sqConn.Open();
                                            MySqlBulkLoader bcp1 = new MySqlBulkLoader(sqConn);
                                            bcp1.TableName = "appointment";
                                            //bcp1.TableName = "Appointment";                        //Create Appointment table into MYSQL database.
                                            bcp1.FieldTerminator = ",";
                                            bcp1.LineTerminator = "\r\n";
                                            bcp1.FileName = strFile;
                                            bcp1.NumberOfLinesToSkip = 0;
                                            bcp1.Load();
                                            try
                                            {
                                                File.Delete(strFile);
                                            }
                                            catch (Exception ex)
                                            {
                                                ExtractorEventLog("appointment-ex", null);
                                                ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
                                            }
                                            ExtractorEventLog(appointment_count + " " + Common.No_Of_Appointment_Retrive, id.ToString());
                                        }
                                        ExtractorEventLog(Common.Done, id.ToString());
                                        this.ScheduleService();
                                    }
                                    #endregion
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ExtractorEventLog("a-ex", null);
                            ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
                        }
                    }

                }
                else{
                    this.ScheduleService();
                }
            }
            catch (Exception ex)
            {
                ExtractorEventLog(ex.Message +"b-ex", null);
                //ExceptionLog(ex.Message, ex.GetType().Name.ToString(), ex.StackTrace, id);
            }

            //EventLog("this ScheduleService()");
            // this.ScheduleService();m
        }
        catch(Exception ex)
        {
            ExtractorEventLog("zz-ex", null);
        }
    }

0 个答案:

没有答案