Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Api limits #37

Merged
merged 2 commits into from
Sep 24, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/SalesforceSharp/SalesforceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using HelperSharp;
using Newtonsoft.Json.Linq;
using RestSharp;
Expand All @@ -23,6 +24,7 @@ public class SalesforceClient
private IRestClient m_restClient;
private GenericJsonDeserializer genericJsonDeserializer;
private GenericJsonSerializer updateJsonSerializer;
private static readonly Regex apiUsageRegexp = new Regex(@"api-usage=(\d+)/(\d+)", RegexOptions.Compiled);
#endregion

#region Constructors
Expand Down Expand Up @@ -75,6 +77,22 @@ protected internal SalesforceClient(IRestClient restClient)
/// The instance URL.
/// </value>
public string InstanceUrl { get; private set; }

/// <summary>
/// Get current API calls number
/// </summary>
/// <value>
/// current API calls number
/// </value>
public int ApiCallsUsed { get; private set; }

/// <summary>
/// Get total API calls limit
/// </summary>
/// <value>
/// API calls limit
/// </value>
public int ApiCallsLimit { get; private set; }
#endregion

#region Methods
Expand Down Expand Up @@ -461,6 +479,7 @@ protected IRestResponse RequestRaw(string baseUrl, string objectName = null, obj

var response = m_restClient.Execute(request);
CheckApiException(response);
ExtractLimitsInfo(response);

return response;
}
Expand Down Expand Up @@ -522,6 +541,20 @@ private void CheckApiException(IRestResponse response)
throw ex;
}
}

private void ExtractLimitsInfo(IRestResponse response)
{
var limitHeader = response.Headers?.FirstOrDefault(h => h.Name == "Sforce-Limit-Info");
if (limitHeader?.Value != null)
{
var match = apiUsageRegexp.Match(limitHeader.Value.ToString());
if (match.Success)
{
ApiCallsUsed = int.Parse(match.Groups[1].Value);
ApiCallsLimit = int.Parse(match.Groups[2].Value);
}
}
}
#endregion

#region Helpers
Expand Down