2015-11-24 54 views
1

我需要確定用戶列表是否位於第三方用戶目錄中。我正在用C#.NET 4.0寫這個方法。用戶列表超過2700個條目。訪問此用戶目錄的API使用REST返回用戶信息。如果用戶不在目錄中,則對HttpWebRequest的響應是404錯誤。我發現了WebException錯誤。HttpWebRequest響應返回404錯誤後繼續

問題是我一次只能得到一個用戶的用戶信息,所以我想做一個for循環來通過用戶列表。但是,當發生404錯誤時,它會跳出循環。有什麼方法可以捕捉到404錯誤,並繼續與下一個用戶的循環?

這是我的代碼:

public void GetRecipientDataFromCortext() 
{ 
    SqlConnection SqlConn = null; 
    CortextUser objCortextResult; 
    try 
    { 
     string strStoredProcedure = "PagingToolGetRecipientsAndDevices"; 
     DataTable tdtRecipientData = new DataTable("RecipientData"); 
     //Create a datatable to store final results 
     DataTable tdtCortextResultData = new DataTable("CortextResults"); 
     tdtCortextResultData.Columns.Add("RecipientID", typeof(int)); 
     tdtCortextResultData.Columns.Add("DeviceTypeID", typeof(int)); 
     tdtCortextResultData.Columns.Add("DeviceAddress", typeof(string)); 
     tdtCortextResultData.Columns.Add("CUID", typeof(string)); 
     tdtCortextResultData.Columns.Add("InviteStatus", typeof(string)); 
     tdtCortextResultData.Columns.Add("IsEnabled", typeof(bool)); 
     tdtCortextResultData.Columns.Add("FirstName", typeof(string)); 
     tdtCortextResultData.Columns.Add("LastName", typeof(string)); 
     tdtCortextResultData.Columns.Add("MiddleName", typeof(string)); 
     tdtCortextResultData.Columns.Add("HonorificPrefix", typeof(string)); 
     tdtCortextResultData.Columns.Add("HonorificSuffix", typeof(string)); 
     tdtCortextResultData.Columns.Add("Email", typeof(string)); 
     tdtCortextResultData.Columns.Add("Mobile", typeof(string)); 
     tdtCortextResultData.Columns.Add("Pager", typeof(string)); 

     string strSqlConnection = ConfigurationManager.ConnectionStrings[CONNECTION_STRING].ConnectionString; 
     //Get the recipient list from the database 
     using (SqlConn = new SqlConnection(strSqlConnection)) 
     { 
      using (SqlCommand SqlCmd = new SqlCommand(strStoredProcedure, SqlConn)) 
      { 
       SqlCmd.CommandType = CommandType.StoredProcedure; 
       SqlConn.Open(); 
       using (SqlDataAdapter dataReturned = new SqlDataAdapter(SqlCmd)) 
       { 
        dataReturned.Fill(tdtRecipientData);       
       } 
      } 
     } 
     //For loop to make a call to cortext to get properties of this device 
     string tstrPropertyValue = string.Empty; 
     string tstrProperty = string.Empty; 
     int tiDeviceTypeID; 
     int tiRecipientID; 

     //This is the for loop to check each recipient to see if he/she is in the directory 
     foreach (DataRow row in tdtRecipientData.Rows) 
     {    
      tstrPropertyValue = row["Address"].ToString(); 
      tiDeviceTypeID = Convert.ToInt32(row["DeviceTypeID"].ToString()); 
      tiRecipientID = Convert.ToInt32(row["RecipientID"].ToString()); 

      //Insert into the Cortext table initial values first 
      //This inserts into a database table the user to check. 
      //This table is used to get the initial recipient list. 
      //Any users in this table are not in the list. 
      InsertCortextInformation(tiRecipientID, tiDeviceTypeID, tstrPropertyValue); 

      switch (tiDeviceTypeID) 
      { 
       case 1: 
        tstrProperty = "mobile"; 
        break; 
       case 2: 
        tstrProperty = "email"; 
        break; 
       case 3: 
        tstrProperty = "pager"; 
        break; 
       default: 
        break; 
      } 

      //Results from cortext call add to data table 
      //User not in the directory results in this method call to return a 404 error. 
      //Exception breaks out of the loop 
      objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue); 
      //Add results to datatable 
      DataRow newRow = tdtCortextResultData.NewRow(); 
      newRow["RecipientID"] = Convert.ToInt32(row["RecipientID"].ToString()); 
      newRow["DeviceTypeID"] = Convert.ToInt32(row["DeviceTypeID"].ToString()); 
      newRow["DeviceAddress"] = row["Address"].ToString(); 
      newRow["CUID"] = objCortextResult.CUID; 
      newRow["InviteStatus"] = objCortextResult.inviteStatus; 
      newRow["IsEnabled"] = objCortextResult.isEnabled; 
      newRow["FirstName"] = objCortextResult.userFirstName; 
      newRow["LastName"] = objCortextResult.userLastName; 
      newRow["MiddleName"] = objCortextResult.userMiddleName; 
      newRow["HonorificPrefix"] = objCortextResult.userHonorificPrefix; 
      newRow["HonorificSuffix"] = objCortextResult.userHonorificSuffix; 
      newRow["Email"] = objCortextResult.email; 
      newRow["Mobile"] = objCortextResult.mobile; 
      newRow["Pager"] = objCortextResult.pager; 

      tdtCortextResultData.Rows.Add(newRow); 

     } 

     //Insert data table results into Paging Tool table, PagingToolCortextInfo 
     int tiRecID, tiDeviceID; 
     bool tbIsEnabled; 
     foreach (DataRow row in tdtCortextResultData.Rows) 
     { 
      tiRecID = Convert.ToInt32(row["RecipientID"].ToString()); 
      tiDeviceID = Convert.ToInt32(row["DeviceTypeID"].ToString()); 
      tbIsEnabled = Convert.ToBoolean(row["IsEnabled"].ToString()); 
      UpdateCortextInformation(tiRecID, tiDeviceID, row["DeviceAddress"].ToString(), 
             row["CUID"].ToString(), row["InviteStatus"].ToString(), tbIsEnabled, 
             row["FirstName"].ToString(), row["LastName"].ToString(), row["MiddleName"].ToString(), 
             row["HonorificPrefix"].ToString(), row["HonorificSuffix"].ToString(), 
             row["Email"].ToString(), row["Mobile"].ToString(), row["Pager"].ToString()); 
     } 

    } 
    //Catches the HttpWebResponse errors like 404 
    catch (WebException e) 
    { 
     using (WebResponse response = e.Response) 
     { 
      HttpWebResponse httpResponse = (HttpWebResponse)response; 
      string errorMessage = string.Format("Error code: {0} ", httpResponse.StatusCode); 
      //   System.Diagnostics.Debug.WriteLine("Error code: {0}", httpResponse.StatusCode); 
      using (Stream data = response.GetResponseStream()) 
      { 
       using (var reader = new StreamReader(data)) 
       { 
        string text = reader.ReadToEnd(); 
        errorMessage += text; 
        // 
        System.Diagnostics.Debug.WriteLine(text); 
        logger.ErrorException(errorMessage, e); 
       } 
      } 
     } 
     throw; 
    } 
    catch (Exception ex) 
    { 
     logger.ErrorException(ex.Message, ex); 
     throw; 
    } 
    finally 
    { 
     if (SqlConn != null) 
     { 
      SqlConn.Close(); 
     } 
    } 
} 

那麼,有沒有什麼辦法可以繼續在for循環中調用HTTP響應返回404錯誤後並獲得下一個用戶?

我想承認404錯誤,並繼續在for循環中獲取所有用戶。

謝謝。

+1

放置一個'try {} catch {}'確定拋出異常的方法。 – AgentFire

+0

我有'WebException' catch捕獲404錯誤。我的問題是,它把我扔出for循環,我不能得到下一個用戶。如何避免404錯誤被拋出時退出for循環?我想承認錯誤並繼續進行循環。 –

+0

在你的循環內放置一個'try {} catch {} ** **範圍出引發異常的方法。 – AgentFire

回答

1

這可以很容易與您的代碼:)

裹線實現

var isNotFound = false; 
try { 
    objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue); 
} 
catch(WebException ex) { 
    if(((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)  
    { 
     isNotFound = true; 
    } 
    else { 
     throw; 
    } 
} 

if (isNotFound) continue; 

... 

的持續狀態代碼404將進入你的循環的下一次迭代並達到所需的行爲。

讓我知道你是否需要別的東西!

+0

謝謝!我會嘗試一下! –

+0

如果我以前的代碼不適合你,上面的編輯應該。進一步的思考使我認爲'繼續'只能在循環的主要範圍內工作,而不能在'catch'語句中工作。 – JDTLH9

+0

第一個代碼確實有效。當出現404錯誤並且獲得了下一個用戶時,它打到了「繼續」。太感謝了! –

0

你可以嘗試保持try catch內循環? 您也可以嘗試爲每個或TPL並行執行此操作。

objCortextResult = GetCortextUserInformation(tstrProperty, tstrPropertyValue); 
在嘗試捕捉