C# Client Library
A C# Client Library for the AnalyzeRe REST API
Loading...
Searching...
No Matches
API.Configuration.cs
Go to the documentation of this file.
1using System;
2using System.Diagnostics;
3using System.Net;
4using System.Reflection;
5
9using RestSharp;
10
11namespace AnalyzeRe
12{
14 public static partial class API
15 {
16 #region Private Properties
17 #region Read-Only
19 public static readonly string AnalyzeReServerIdentity = "ARE-API";
20
22 public static readonly string AnalyzeReCustomServerHeader = "ARE-Server";
23
25 public static readonly string DateTimeFormat = @"O";
26
27 internal static readonly string JSON_CONTENT_TYPE = "application/json";
28
30 private static readonly AnalyzeReJsonConverter Converter = new AnalyzeReJsonConverter();
31
34 internal static readonly WebExceptionStatus[] TemporaryFailureStatuses = {
35 WebExceptionStatus.ConnectFailure, WebExceptionStatus.RequestCanceled,
36 WebExceptionStatus.ConnectionClosed, WebExceptionStatus.SendFailure,
37 WebExceptionStatus.PipelineFailure, WebExceptionStatus.UnknownError,
38 // TODO: These statuses can sometimes be associated with timeouts
39 // (see https://support.microsoft.com/en-us/help/2007873) in which case
40 // they should not be retried.
41 WebExceptionStatus.ReceiveFailure, WebExceptionStatus.KeepAliveFailure
42 };
43 #endregion Read-Only
44
47 private static volatile bool _initialized;
48
50 private static volatile RestClient _cachedClient;
51
54 private static volatile bool _disableReadConfigFile;
55
58 private static volatile bool _disableWriteConfigFile;
59
61 private static volatile string _serverURL;
62
64 private static volatile int _parallelism;
65
67 private static volatile int _defaultRequestTimeout;
68
70 private static volatile int _defaultRequestTimeoutCollections;
71 #endregion Private Properties
72
73 #region Public Properties
74 private static string _userAgent = $"ARe.Client {Assembly.GetExecutingAssembly().GetName().Version}";
75
78 public static string UserAgent
79 {
80 get => _userAgent;
81 set
82 {
83 _userAgent = value;
84 if (_cachedClient != null)
85 _cachedClient.UserAgent = _userAgent;
86 }
87 }
88
93 public static volatile int MaxRequestRetries = 3;
94
98 public static bool ManagedSettingsEnabled { get; set; } = true;
99
104 public static int Parallelism
105 {
106 get => _parallelism;
107 set
108 {
109 _parallelism = value;
110 // By default, only 2 connections can be opened simultaneously.
111 // The following increase significantly enhances performance.
112 ServicePointManager.DefaultConnectionLimit = Parallelism;
113 }
114 }
115
119 [GreaterThan(0, true)]
120 public static int DefaultRequestTimeout
121 {
122 get => _defaultRequestTimeout >= 0 ? _defaultRequestTimeout : Int32.MaxValue;
123 set
124 {
125 if (value <= 0)
126 throw new ArgumentException("Timeout must be greater than 0. " +
127 "Set to int.MaxValue to never time out.");
128 _defaultRequestTimeout = value;
129 if (!ManagedSettingsEnabled) return;
130 TrySaveLibrarySettings(() =>
131 {
132 Settings.Default.User_DEFAULT_REQUEST_TIMEOUT = value;
133 });
134 }
135 }
136
141 [GreaterThan(0, true)]
143 {
144 get => _defaultRequestTimeoutCollections >= 0 ?
145 _defaultRequestTimeoutCollections : Int32.MaxValue;
146 set
147 {
148 if (value <= 0)
149 throw new ArgumentException("Timeout must be greater than 0. " +
150 "Set to int.MaxValue to never time out.");
151 _defaultRequestTimeoutCollections = value;
152 if (!ManagedSettingsEnabled) return;
153 TrySaveLibrarySettings(() =>
154 {
155 Settings.Default.User_DEFAULT_REQUEST_TIMEOUT_COLLECTIONS = value;
156 });
157 }
158 }
159
167 public static string ServerURL
168 {
169 get => _serverURL;
170 set
171 {
172 if (value == _serverURL) return;
173
174 // If a previous URL was set, clear the associated prior authentication token
175 if (_serverURL != null && ManagedSettingsEnabled)
176 AuthenticationToken = null;
177
178 // Ensure there is a trailing slash.
179 _serverURL = value == null ? null : value.TrimEnd('/') + "/";
180
181 if (!ManagedSettingsEnabled) return;
182
183 // If server credentials are cached for this URL, restore them.
184 try
185 {
186 RestoreCachedAuthentication();
187 }
188 catch (Exception ex)
189 {
190 Debug.WriteLine("Error restoring cached credentials for the server URL " +
191 $"{_serverURL}:\n{ex.Message}");
192 }
193
194 // Update the last set URL in the application settings file
195 string currentSavedURL = TryGetLibrarySettingObj(() => Settings.Default.ServerURL);
196 if (currentSavedURL != _serverURL)
197 {
198 TrySaveLibrarySettings(() =>
199 {
200 Settings.Default.ServerURL = _serverURL;
201 });
202 }
203 }
204 }
205
210 public static string DefaultServerURL => TryGetLibrarySettingObj(() => Settings.Default.DefaultServerURL);
211 #endregion Public Properties
212
213 #region Public Methods
221 public static void LoadSettings() => LoadSettingsInternal(true);
222
227 private static void LoadSettingsInternal(bool overwrite)
228 {
229 // The following offers a slight increase in request responsiveness (~10%)
230 // as it avoids use of a network optimization that can delay certain small
231 // requests so that they can be bundled with others to reduce the number
232 // of overall packets.
233 ServicePointManager.UseNagleAlgorithm = false;
234
235#if NET40
236 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
237#else
238 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
239#endif
240
241 if (overwrite || _serverURL == null)
242 {
243 string userDefault = TryGetLibrarySettingObj(() => Settings.Default.ServerURL);
244 ServerURL = String.IsNullOrEmpty(userDefault) ? DefaultServerURL : userDefault;
245 }
246
247 if(overwrite || Parallelism == 0)
248 Parallelism = TryGetLibrarySetting(() => Settings.Default.DefaultParallelism) ?? 128;
249
250 if (overwrite || _defaultRequestTimeout == 0)
251 {
252 int timeout =
253 TryGetLibrarySetting(() => Settings.Default.User_DEFAULT_REQUEST_TIMEOUT) ??
254 TryGetLibrarySetting(() => Settings.Default.DEFAULT_REQUEST_TIMEOUT) ?? Int32.MaxValue;
255 _defaultRequestTimeout = timeout > 0 ? timeout : Int32.MaxValue;
256 }
257
258 if (overwrite || _defaultRequestTimeoutCollections == 0)
259 {
260 int timeout =
261 TryGetLibrarySetting(() => Settings.Default.User_DEFAULT_REQUEST_TIMEOUT_COLLECTIONS) ??
262 TryGetLibrarySetting(() => Settings.Default.DEFAULT_REQUEST_TIMEOUT_COLLECTIONS) ?? Int32.MaxValue;
263 _defaultRequestTimeoutCollections = timeout > 0 ? timeout : Int32.MaxValue;
264 }
265
266 _initialized = true;
267 }
268 #endregion Public Methods
269
270 #region Server Connection
274 private static RestClient GetRestClient(int? timeout = null)
275 {
276 return GetRestClient(new Uri(ServerURL), timeout);
277 }
278
287 private static RestClient GetRestClient(Uri serverUri, int? timeout = null)
288 {
289 if (!_initialized)
290 LoadSettingsInternal(false);
291 if (_cachedClient == null || !_cachedClient.BaseUrl.Equals(serverUri))
292 {
293 // First time setup of RestClient
294 _cachedClient = new RestClient(serverUri.AbsoluteUri)
295 {
297 FollowRedirects = false
298 };
299 _cachedClient.AddHandler(JSON_CONTENT_TYPE, Converter);
300 }
301 _cachedClient.Timeout = timeout ?? DefaultRequestTimeout;
302 return _cachedClient;
303 }
304 #endregion Server Connection
305
306 #region Settings Helpers
310 private static T? TryGetLibrarySetting<T>(Func<T> getSetting) where T : struct
311 {
312 return (T?)TryGetLibrarySettingObj(() => (object)getSetting());
313 }
314
318 private static T TryGetLibrarySettingObj<T>(Func<T> getSetting) where T : class
319 {
320 if (_disableReadConfigFile) return null;
321 try
322 {
323 return getSetting();
324 }
325 catch (Exception ex)
326 {
327 _disableReadConfigFile = true;
328 Debug.WriteLine("User scoped settings unavailable:\n" +
329 ex.Message + "\nDisabling reading user-settings.");
330 return null;
331 }
332 }
333
338 private static void TrySaveLibrarySettings(Action modifySetting)
339 {
340 if (_disableWriteConfigFile || !ManagedSettingsEnabled) return;
341 try
342 {
343 modifySetting();
344 Settings.Default.Save();
345 }
346 catch (Exception ex)
347 {
348 _disableWriteConfigFile = true;
349 Debug.WriteLine("The library settings file cannot be modified:\n" +
350 ex.Message + "\nDisabling updates to settings.");
351 }
352 }
353 #endregion Settings Helpers
354 }
355}
API methods / requests made available to the user.
static bool ManagedSettingsEnabled
By Default, the Analyze Re Client Library will automatically save and restore certain configured sett...
static int Parallelism
The maximum number of concurrent requests that can be made.
static IAccessToken AuthenticationToken
The AccessToken storing authentication information for requests made to the server.
static int DefaultRequestTimeout
The default timeout used for all simple server requests, in milliseconds.
static volatile int MaxRequestRetries
When a temporary communication failure occurs (such as a socket error or an authentication failure fo...
static int DefaultRequestTimeoutCollections
The default timeout used when requesting a resource collection from the server, in milliseconds.
static string DefaultServerURL
The Default ServerURL the API is instantiated with, as configured in the settings.
static string ServerURL
The default server URL to be used for all API requests. On change, voids the current cached authentic...
static readonly string DateTimeFormat
The format used when transmitting DateTime information to Analyze Re servers.
static string UserAgent
The UserAgent identifying the requests made by this client. This can be changed if an application wis...
static readonly string AnalyzeReCustomServerHeader
The Custom Server Header returned by valid AnalyzeRe servers.
static readonly string AnalyzeReServerIdentity
The Server identity returned by valid AnalyzeRe servers.
static void LoadSettings()
Reloads all shared client library settings from the current statically configured SharedSettingsProvi...
A pre-configured RestSharp serializer / deserializer which is made to support parsing of AnalyzeRe AP...
This part of the Settings class is not generated from the Settings.settings designer,...
Definition Settings.cs:11
int User_DEFAULT_REQUEST_TIMEOUT
The user-overridden value for the default request timeout.
static Settings Default
The default settings used by the static Analyze Re API client library.
int DEFAULT_REQUEST_TIMEOUT_COLLECTIONS
The default timeout for collection GET requests, which are generally more expensive than simple resou...
int User_DEFAULT_REQUEST_TIMEOUT_COLLECTIONS
The user-overridden value for the default collection request timeout.
string ServerURL
The last API url to connected to. This can be used to override the default URL to restore a previous ...
string DefaultServerURL
The default API url to connect to. This is typically set to an example url.
int DEFAULT_REQUEST_TIMEOUT
The default timeout for simple resource requests.
int DefaultParallelism
The default number of simultaneous connections to allow to the API.