连接丢失到数据库时服务停止

时间:2016-01-14 10:56:57

标签: c# service

我已在C#中编写了一个服务,用于运行和更新CRM解决方案。我试图让服务重新建立与数据库的连接,如果由于某种原因必须丢弃。到目前为止,当我分离数据库然后重新连接它时,服务自行停止。另一件事是,然后我分离数据库,我的同步应用程序没有记录异常 - 它只是停止了。

我的部分课程,我称之为同步:

        namespace Vessel_Schedule_Synch
    {
        [DisplayName("CRM Vessel Synch")]
        partial class startVessel : ServiceBase
        {

            System.Threading.Timer t;

            VesselUpdater v;

            protected override void OnStart(string[] args)
            {
                //System.Threading.Thread.Sleep(20000);

                v = new VesselUpdater();

                t = new System.Threading.Timer(new System.Threading.TimerCallback(t_TimerCallback), null, 0, 300000);

                //InfoLogger.Info("Starting service " + this.ServiceName, true);

            }

            private void t_TimerCallback(object state)
            {
                t.Change(Timeout.Infinite, Timeout.Infinite);
                lock (v)
                {
                    InfoLogger.Info("Timer fired... updating vessels");
                    try
                    {
                        v.Process();
                        v.updateCRM();
                    }
                    catch (Exception e)
                    {
                        if (v == null)
                        { throw e; }
                        else
                        {
                            InfoLogger.Exception(e);
                        }
                    }
                    finally
                    {
                        InfoLogger.Info("End of Timer Trigger... Restarting Timer.");
                        t.Change(30000, 30000);
                    }
                }
            }
            protected override void OnStop()
            {
                InfoLogger.Info("Service Stopped " + this.ServiceName, true);
            }
        }
    }

我的同步课我尝试使用bool来测试连接:

        namespace Vessel_Schedule_Synch
    {
        class VesselUpdater
        {   
            private OrganizationServiceProxy _serviceProxy;
            private IOrganizationService _service;
            private Logger logger = LogManager.GetLogger("VesselUpdater");
            public string ConnectionString { get; set; }
            public string ServiceUrl { get; set; }
            int i = 0;

            private bool InitialiseCRMConnection;

            public VesselUpdater()
            {
                InitialiseCRMConnection = true;
                Console.WriteLine("Starting the service");
                LogMessage("Starting service");
                ServiceUrl = ConfigurationManager.AppSettings["CRMUrl"];
                LogMessage(ConnectionString);
                ConnectionString = ConfigurationManager.ConnectionStrings["iRoot"].ConnectionString;
                LogMessage(ServiceUrl);
                Console.WriteLine(ServiceUrl);
            }

            public void Process()
            {
                if (!InitialiseCRMConnection)
                    return;

                LogMessage("Process Starting");

                ClientCredentials UserCredentials = new ClientCredentials();

                string UserName = ConfigurationManager.AppSettings["User"];
                string Password = ConfigurationManager.AppSettings["Password"];

                UserCredentials.UserName.UserName = UserName;
                UserCredentials.UserName.Password = Password;

                ClientCredentials DivCredentials = null;
                Uri HomeRealmURI = null;
                Uri serviceurl = new Uri(ServiceUrl);

                _serviceProxy = new OrganizationServiceProxy(serviceurl, HomeRealmURI, UserCredentials, DivCredentials);
                _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                _service = (IOrganizationService)_serviceProxy;
                _serviceProxy.EnableProxyTypes();

                LogMessage("CRM Connection Initiated");

                InitialiseCRMConnection = false;
            }

            public void updateCRM()
            {

                try
                {
                    ProcessVesselSchedule("Insert");
                    ProcessVesselSchedule("Modification");
                }
                catch (Exception e)
                {
                    InitialiseCRMConnection = true;
                    InfoLogger.Exception(e);
                    LogMessage("Exception " + e);
                }

            }

            private void ProcessVesselSchedule(string Type)
            {
                if (InitialiseCRMConnection)
                    return;

                try
                {

                    LogMessage(string.Format("Processing Vessesl Schedules {0}", Type));

                    using (SqlConnection con = new SqlConnection(ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("VesselScheduleInformation", con);

                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Type", Type);
                        con.Open();

                        SqlDataReader dr = cmd.ExecuteReader();

                        while (dr.Read())
                        {
                            try
                            {
                                LogMessage("Processing Record");
                                LogMessage(dr["new_Name"].ToString());
                                string Name = dr["new_Name"].ToString() + " " + dr["new_VoyageNo"].ToString();
                                string Vesselname = dr["new_Name"].ToString();
                                int LineNo = (int)dr["Line Number"];
                                string NAVVesselScheduleCode = dr["new_NAVVesselScheduleCode"].ToString();
                                string CarrierService = dr["new_CarrierService"].ToString();
                                string ETA = dr["new_ETA"].ToString();
                                string ETD = dr["new_ETD"].ToString();
                                string VesselCode = dr["new_Vessel"].ToString();//Vessel Code
                                string VoyageNo = dr["new_VoyageNo"].ToString();
                                string TranshipmentVessel = dr["new_TranshipmentVessel"].ToString();
                                string TranshipmentVoyageNo = dr["new_TranshipmentVoyageNo"].ToString();
                                string Port = dr["new_Port"].ToString();
                                string PortOfDis = dr["new_DischargePort"].ToString();
                                string PortOfLoad = dr["new_LoadPort"].ToString();
                                //string StackStart = dr["new_StackStart"].ToString();
                                //string StackEnd = dr["new_StackEnd"].ToString();
                                bool Create = false;

                                LogMessage("Assigned all variables");
                                Console.WriteLine("Assigned all variables");

                                new_vesselschedule VesselS = FindVessleSchedule(NAVVesselScheduleCode, LineNo, out Create);
                                //if (DateTime.Parse(StackStart).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
                                //{
                                //    VesselS["new_stackstart"] = DateTime.Parse(StackStart).ToUniversalTime();
                                //}
                                //if (DateTime.Parse(StackEnd).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
                                //{
                                //    VesselS["new_stackend"] = DateTime.Parse(StackEnd).ToUniversalTime();
                                //}

                                VesselS.new_name = Name;
                                VesselS.new_navvesselschedulecode = NAVVesselScheduleCode;
                                VesselS.new_CarrierService = CarrierService;
                                if (DateTime.Parse(ETA).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
                                {
                                    VesselS.new_ETA = DateTime.Parse(ETA).ToUniversalTime();
                                }
                                if (DateTime.Parse(ETD).ToUniversalTime() >= DateTime.Parse("1900-01-01"))
                                {
                                    VesselS.new_ETD = DateTime.Parse(ETD).ToUniversalTime();
                                }
                                VesselS.new_vesselcodeimport = VesselCode;
                                VesselS.new_vesselnameimport = Vesselname;
                                VesselS.new_VoyageNo = VoyageNo;
                                VesselS.new_TransshipmentVessel = TranshipmentVessel;
                                VesselS.new_TransshipmentVoyageNo = TranshipmentVoyageNo;
                                VesselS.new_dischargeportimport = PortOfDis;
                                VesselS.new_loadportimport = PortOfLoad;
                                if (Create)
                                {
                                    LogMessage(string.Format("Created {0} {1}", NAVVesselScheduleCode, LineNo));
                                    _serviceProxy.Create(VesselS);
                                }
                                else
                                {
                                    LogMessage(string.Format("Updated {0} {1}", NAVVesselScheduleCode, LineNo));
                                    _serviceProxy.Update(VesselS);
                                }

                                using (SqlCommand cmdUpdateMates = new SqlCommand())
                                {
                                    SqlConnection con2 = new SqlConnection(ConnectionString);
                                    con2.Open();
                                    cmdUpdateMates.Connection = con2;
                                    cmdUpdateMates.CommandText = "ProcessedVessSched";
                                    cmdUpdateMates.CommandType = CommandType.StoredProcedure;
                                    cmdUpdateMates.Parameters.AddWithValue("@VesselSched", NAVVesselScheduleCode);
                                    cmdUpdateMates.Parameters.AddWithValue("@LineNo", LineNo);
                                    cmdUpdateMates.ExecuteNonQuery();
                                    i++;
                                    Console.WriteLine("Created/Updated" + " " + i);
                                }
                            }

                            catch (Exception e)
                            {
                                InitialiseCRMConnection = true;
                                InfoLogger.Exception(e);
                                LogMessage("Exception " + e);
                            }
                        }
                    }
                }
                catch (SqlException e)
                {
                    InfoLogger.Exception(e);
                    LogMessage("SQL Exception " + e);
                }
                catch (Exception e)
                {
                    InitialiseCRMConnection = true;
                    InfoLogger.Exception(e);
                    LogMessage("Exception " + e);
                }
            }

            public void LogMessage(string Message)
            {
                LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", Message);
                myEvent.LoggerName = logger.Name;
                logger.Log(myEvent);        
            }

            private new_vesselschedule FindVessleSchedule(string NAVVesselScheduleCode, int LineNo, out bool Create)
            {
                QueryExpression query = new QueryExpression(new_vesselschedule.EntityLogicalName);
                query.ColumnSet.AllColumns = true;
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition("new_navvesselschedulecode", ConditionOperator.Equal, NAVVesselScheduleCode);
                query.Criteria.AddCondition("new_lineno", ConditionOperator.Equal, LineNo);

                EntityCollection entitycollection = _serviceProxy.RetrieveMultiple(query);
                if (entitycollection.Entities.Count == 0)
                {
                    new_vesselschedule n = new new_vesselschedule();
                    n.new_navvesselschedulecode = NAVVesselScheduleCode;
                    n.new_lineno = LineNo;
                    Create = true;
                    return n;
                }
                Create = false;
                return (new_vesselschedule)entitycollection.Entities[0];
            }

        }
    }

我在这里遗漏了什么吗?

1 个答案:

答案 0 :(得分:0)

我在代码中发现了这个问题,我忘了发送InitialiseCRMConnection = true;在我的SQL异常中因此它永远不会经历重新初始化连接的动作,因为它总会返回;

修正:

            catch (SqlException e)
            {
                InitialiseCRMConnection = true;
                InfoLogger.Exception(e);
                LogMessage("SQL Exception " + e);
            }