Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 与数据库的连接丢失时,服务停止_C#_Service - Fatal编程技术网

C# 与数据库的连接丢失时,服务停止

C# 与数据库的连接丢失时,服务停止,c#,service,C#,Service,我用C#编写了一个服务,它运行并更新CRM解决方案。我正试图让服务重新建立与数据库的连接,如果它因某种原因而中断。到目前为止,当我分离数据库并重新连接它时,服务会自行停止。。另一件事是,然后我分离数据库,我的同步应用程序没有记录任何异常-它只是停止死亡 我调用同步的部分类: namespace Vessel_Schedule_Synch { [DisplayName("CRM Vessel Synch")] partial class st

我用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];
            }

        }
    }

我是不是遗漏了什么

我在代码中发现问题,我忘记发送InitialiseCRMConnection=true;因此,在我的SQL异常中,它永远无法重新初始化连接,因为它总是返回

修正:

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