public BaseClient(string url, IdServerResourceOwnerClientSettings settings, bool setTestRequestHeader = false, TimeSpan?timeout = null) : this() { if (String.IsNullOrEmpty(url)) { throw new ArgumentException("Required arguments: url"); } if (settings == null) { throw new ArgumentException("Required arguments: IdServerResourceOwnerClientSettings"); } if (string.IsNullOrEmpty(settings.BaseAddress) | string.IsNullOrEmpty(settings.ClientId) | string.IsNullOrEmpty(settings.ClientSecret) | string.IsNullOrEmpty(settings.UserName) | string.IsNullOrEmpty(settings.Password) | string.IsNullOrEmpty(settings.Scopes)) { throw new ArgumentException("Required IdServerResourceOwnerClientSettings: BaseAddress, ClientId, ClientSecret, UserName, Password, Scopes"); } _url = url; _setTestRequestHeader = setTestRequestHeader; _hasIDServerResourceOwnerClientSettings = true; _idServerResourceOwnerClientSettings = settings; _timeout = timeout == null?TimeSpan.FromSeconds(480) : timeout.Value; }
private static async Task UpdateAnAsset() { var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; var organisationGroupId = long.Parse(ConfigurationManager.AppSettings["OrganisationGroupId"]); try { var group = await GetGroupSummary(organisationGroupId, apiBaseUrl, idServerResourceOwnerClientSettings); var assets = await GetAssets(group, apiBaseUrl, idServerResourceOwnerClientSettings); if (assets.Count == 0) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("No assets found!"); return; } Asset asset = assets[0]; asset.Notes = "Updated by MiX.Integrate"; Console.WriteLine($"Updating asset with description '{0}'", asset.Description); var assetsClient = new AssetsClient(apiBaseUrl, idServerResourceOwnerClientSettings); assetsClient.Update(asset); asset = assetsClient.Get(asset.AssetId); Console.WriteLine($"Asset with description '{asset.Description }' notes updated to '{asset.Notes}'"); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); Console.WriteLine("Press any key to finish."); Console.ReadKey(); } return; }
private static async Task ShowAssetsDriversAsync() { var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; try { var group = await GetFirstAvailableOrganisationsAsync(apiBaseUrl, idServerResourceOwnerClientSettings); if (group == null) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("No available organisations found for user."); } else { var assets = await GetAssetsAsync(group, apiBaseUrl, idServerResourceOwnerClientSettings); PrintAssetDetails(group, assets); var drivers = await GetDriversAsync(group, apiBaseUrl, idServerResourceOwnerClientSettings); PrintDriverDetails(group, drivers); } } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); Console.WriteLine("Press any key to finish."); Console.ReadKey(); } return; }
private static async Task ShowSiteLocationsAsync() { var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; Console.WriteLine($"Connecting to: {apiBaseUrl}"); try { var group = await GetFirstAvailableOrganisationsAsync(apiBaseUrl, idServerResourceOwnerClientSettings); var defaultSite = GetDefaultSite(group); if (defaultSite == null) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Default Site not found!"); return; } var locations = await GetLocationsAsync(defaultSite, apiBaseUrl, idServerResourceOwnerClientSettings); PrintLocationDetails(defaultSite, locations); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); Console.WriteLine("Press any key to finish."); Console.ReadKey(); } return; }
public static void ClearIdServerAccessToken(IdServerResourceOwnerClientSettings settings) { lock (_lock) { if (settings == null) { throw new ArgumentException("Parameter IdServerResourceOwnerClientSettings not provided"); } int settingsHash = $"{settings.BaseAddress}|{settings.ClientId}|{settings.ClientSecret}|{settings.Scopes}|{settings.UserName}|{settings.Password}".GetHashCode(); if (_idServerAccessTokens.ContainsKey(settingsHash)) { _idServerAccessTokens.Remove(settingsHash); } } }
public static async Task <string> GetIdServerAccessToken(IdServerResourceOwnerClientSettings settings, HttpClientHandler httpClientHandler) { await semaphoreSlim.WaitAsync(); try { if (settings == null) { throw new ArgumentException("Parameter IdServerResourceOwnerClientSettings not provided"); } int settingsHash = $"{settings.BaseAddress}|{settings.ClientId}|{settings.ClientSecret}|{settings.Scopes}|{settings.UserName}|{settings.Password}".GetHashCode(); if (_idServerAccessTokens.ContainsKey(settingsHash) && _idServerAccessTokens[settingsHash] != null) { TokenResponse response = _idServerAccessTokens[settingsHash]; //ToDo: possibly preemptively check if token is still valid return(response.AccessToken); } try { IdentityClient identityClient = new IdentityClient(settings.BaseAddress, settings.ClientId, settings.ClientSecret, httpClientHandler); TokenResponse reponse = await identityClient.RequestTokenAsync(settings.UserName, settings.Password, settings.Scopes).ConfigureAwait(false); if (reponse == null || string.IsNullOrEmpty(reponse.AccessToken)) { throw new HttpClientException(System.Net.HttpStatusCode.Unauthorized, "Authorisation error: No AccessToken returned"); } _idServerAccessTokens.Add(settingsHash, reponse); return(reponse.AccessToken); } catch (Exception exc) { throw new HttpClientException(System.Net.HttpStatusCode.Unauthorized, $"Authorisation error: {exc.Message}"); } } finally { semaphoreSlim.Release(); } }
private static async Task ShowOrganisationNamesAsync() { var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; try { var allowedOrganisations = await GetAllowedOrganisationsAsync(apiBaseUrl, idServerResourceOwnerClientSettings); PrintOrganisationDetails(allowedOrganisations); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); Console.WriteLine("Press any key to finish."); Console.ReadKey(); } return; }
private static async Task <Group> GetFirstAvailableOrganisationsAsync(string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving Organisation details"); var groupsClient = new GroupsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var groups = await groupsClient.GetAvailableOrganisationsAsync(); return(groups?[0]); }
private static async Task <List <Driver> > GetDriversAsync(Group organisation, string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving Driver list..."); var driversClient = new DriversClient(apiBaseUrl, idServerResourceOwnerClientSettings); var drivers = await driversClient.GetAllDriversAsync(organisation.GroupId, "", ""); return(drivers); }
private static async Task ShowPositions() { try { // // Retrieve base URI from configuration file: var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; Console.WriteLine($"Connecting to: {apiBaseUrl}"); // // Retrieve security settings from configuration file: // note: the helper client does the authentication with these settings and attached the // returned token to all other calls. var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; // // Retrieve list of groups the authenticated user has access to: var groups = await GetAvailableOrganisationsAsync(apiBaseUrl, idServerResourceOwnerClientSettings); if ((groups?.Count ?? 0) < 1) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("No available organisations found - terminating."); return; } // the rest of this sample will only process using the first available organisation var group = groups[36]; // 0]; // // Retrieve a list of Assets available in the organisation var assets = await GetAssetsAsync(group.GroupId, apiBaseUrl, idServerResourceOwnerClientSettings); if (assets.Count < 1) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine($"No assets found for {group.Name}, terminating."); return; } else { Console.WriteLine($"{assets.Count} assets found for {group.Name}."); } // // For this sample code the start point will be 1 hour before the sample // is executed. In a production service this sould only be seeded on // first execution and persisted between executions so that the stream // is read correctly string getSinceToken = DateTime.UtcNow.AddHours(-1).ToString("yyyyMMddHHmmssfff"); // // Setup helper client and go into process loop var positionClient = new PositionsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var groupIds = new List <long> { group.GroupId }; do { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Requesting positions...."); var haveMoreItems = false; do { var requestResult = await positionClient.GetCreatedSinceForGroupsAsync(groupIds, "Asset", getSinceToken, 50).ConfigureAwait(false); haveMoreItems = requestResult.HasMoreItems; var positions = requestResult.Items; Console.WriteLine($"Retrieved {positions.Count} positions."); ProcessPositions(positions, assets); // persist token for next retrieval. getSinceToken = requestResult.GetSinceToken; } while (haveMoreItems); // // pause to prevent excessive calls to API. await Task.Delay(30000, _cancelToken); //wait 30 seconds } while (!_cancelToken.IsCancellationRequested); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); } return; }
private static async Task ShowPositions() { var apiBaseUrl = ConfigurationManager.AppSettings["ApiUrl"]; var idServerResourceOwnerClientSettings = new IdServerResourceOwnerClientSettings() { BaseAddress = ConfigurationManager.AppSettings["IdentityServerBaseAddress"], ClientId = ConfigurationManager.AppSettings["IdentityServerClientId"], ClientSecret = ConfigurationManager.AppSettings["IdentityServerClientSecret"], UserName = ConfigurationManager.AppSettings["IdentityServerUserName"], Password = ConfigurationManager.AppSettings["IdentityServerPassword"], Scopes = ConfigurationManager.AppSettings["IdentityServerScopes"] }; Console.WriteLine($"Connecting to: {apiBaseUrl}"); try { var group = await GetFirstAvailableOrganisationsAsync(apiBaseUrl, idServerResourceOwnerClientSettings); var assets = await GetAssetsAsync(group.GroupId, apiBaseUrl, idServerResourceOwnerClientSettings); if (assets.Count < 1) { Console.WriteLine($"No assets found for {group.Name}, terminating."); return; } else { Console.WriteLine($"{assets.Count} assets found for {group.Name}."); } var positionClient = new PositionsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var lastRequest = DateTime.MinValue; var groupList = new List <long> { group.GroupId }; for (int i = 0; i < INTERATIONS; i++) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Retrieving positions...."); var positions = await positionClient.GetLatestByGroupIdsAsync(groupList, 1, lastRequest).ConfigureAwait(false); lastRequest = DateTime.UtcNow; Console.WriteLine($"Retrieved {positions.Count} positions."); foreach (var item in from pos in positions //.Take(10) // for sample, only print first ten positions. join ast in assets on pos.AssetId equals ast.AssetId select new { Registration = ast.RegistrationNumber, Timestamp = pos.Timestamp, Latitude = pos.Latitude, Longitutde = pos.Longitude, Odometer = pos.OdometerKilometres }) { Console.WriteLine($"{item.Registration,-15} {item.Timestamp} {item.Latitude:N6} - {item.Longitutde:N6} {item.Odometer,10:N1} Km"); } if (i < INTERATIONS - 1) { await Task.Delay(30000); //wait 30 seconds } } } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("Unexpected error:"); PrintException(ex); } finally { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine(""); Console.WriteLine("Press any key to finish."); Console.ReadKey(); } return; }
private static async Task <GroupSummary> GetGroupSummary(long organisationGroupId, string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving Organisation details"); var groupsClient = new GroupsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var group = await groupsClient.GetSubGroupsAsync(organisationGroupId); return(group); }
private static async Task <List <Location> > GetLocationsAsync(GroupSummary group, string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine($"Retrieving Locations for {group.Name}..."); var locationsClient = new LocationsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var locations = await locationsClient.GetAllAsync(group.GroupId); return(locations); }
public BaseClient(string url, IdServerResourceOwnerClientSettings settings, bool setTestRequestHeader = false) : this(url, settings, setTestRequestHeader, null) { }
private static async Task <GroupSummary> GetFirstAvailableOrganisationsAsync(string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving Organisation details"); var groupsClient = new GroupsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var groups = await groupsClient.GetAvailableOrganisationsAsync(); if (groups.Count > 0) { var organisation = groups[0]; var group = await groupsClient.GetSubGroupsAsync(organisation.GroupId); return(group); } else { Console.WriteLine(""); Console.WriteLine("======================================================================="); Console.WriteLine("No available organisations found."); return(null); } }
private static async Task <List <Asset> > GetAssetsAsync(Group organisation, string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving Asset list..."); var assetsClient = new AssetsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var assets = await assetsClient.GetAllAsync(organisation.GroupId); return(assets); }
/// <summary> /// Initializes a new instance of the <see cref="JourneysClient"/> class. /// </summary> /// <param name="url">The URL.</param> /// <param name="settings">The settings.</param> /// <param name="setTestRequestHeader">if set to <c>true</c> [set test request header].</param> public JourneysClient(string url, IdServerResourceOwnerClientSettings settings, bool setTestRequestHeader = false) : base(url, settings, setTestRequestHeader) { }
public static async Task RetryOnExceptionAsync(int times, Func <Task> operation, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { if (times <= 0) { throw new ArgumentOutOfRangeException(nameof(times)); } var attempts = 0; bool hasClearedAccessToken = false; do { try { attempts++; await operation().ConfigureAwait(false); break; } catch (HttpClientException ex) { //If Unauthorized exception decrement attempts and clear the access token - only do once if (!hasClearedAccessToken && ex.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized && idServerResourceOwnerClientSettings != null) { hasClearedAccessToken = true; attempts--; AccessTokenCache.ClearIdServerAccessToken(idServerResourceOwnerClientSettings); } if (attempts == times) { throw ex; } await CreateDelay(attempts).ConfigureAwait(false); } catch (HttpServerException ex) { if (attempts == times) { throw ex; } await CreateDelay(attempts).ConfigureAwait(false); } catch (Exception ex) { if (attempts == times) { throw ex; } await CreateDelay(attempts).ConfigureAwait(false); } } while (true); }
private static async Task <List <Group> > GetAllowedOrganisationsAsync(string apiBaseUrl, IdServerResourceOwnerClientSettings idServerResourceOwnerClientSettings) { Console.WriteLine("Retrieving allowed organisation list"); var groupsClient = new GroupsClient(apiBaseUrl, idServerResourceOwnerClientSettings); var group = await groupsClient.GetAvailableOrganisationsAsync(); return(group); }