2016-01-14 32 views
0

我已經在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); 
      } 
     } 
    } 

我的同步課堂,我曾嘗試使用一個布爾測試連接:

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

     } 
    } 

我失去了一些東西在這裏?

回答

0

我在我的代碼中發現了問題,我忘了發送InitialiseCRMConnection = true;在我的SQL異常,因此它永遠不會通過reInitialising連接的運動,因爲它總是會返回;

修復:

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