public ResultUrlClient(ApiConnection connection) { Ensure.ArgumentNotNull(connection, nameof(connection)); Ensure.ArgumentNotNull(connection.Callback, nameof(connection.Callback)); _callback = connection.Callback; }
public async Task EnsuresArgumentNotNull() { var getUri = new Uri("anything", UriKind.Relative); var client = new ApiConnection(Substitute.For<IConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get<object>(null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get<object>(getUri, new Dictionary<string, string>(), null)); }
/// <summary> /// Create a new instance of the GitHub API v3 client using the specified connection. /// </summary> /// <param name="connection">The underlying <seealso cref="IConnection"/> used to make requests</param> public GitHubClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); Connection = connection; var apiConnection = new ApiConnection(connection); Activity = new ActivitiesClient(apiConnection); Authorization = new AuthorizationsClient(apiConnection); Deployment = new DeploymentsClient(apiConnection); Enterprise = new EnterpriseClient(apiConnection); Gist = new GistsClient(apiConnection); Git = new GitDatabaseClient(apiConnection); Issue = new IssuesClient(apiConnection); Migration = new MigrationClient(apiConnection); Miscellaneous = new MiscellaneousClient(connection); Notification = new NotificationsClient(apiConnection); Oauth = new OauthClient(connection); Organization = new OrganizationsClient(apiConnection); PullRequest = new PullRequestsClient(apiConnection); Repository = new RepositoriesClient(apiConnection); Search = new SearchClient(apiConnection); SshKey = new SshKeysClient(apiConnection); User = new UsersClient(apiConnection); Reaction = new ReactionsClient(apiConnection); }
public List<Developer> page(int page = 1, int size = 40) { var credentials = new Octokit.Credentials(ConfigurationManager.AppSettings["user_git"], ConfigurationManager.AppSettings["pass_git"]); Octokit.Connection connection = new Connection(new ProductHeaderValue("DevStore")); Octokit.ApiConnection apiConn = new ApiConnection(connection); Octokit.SearchUsersRequest search = new SearchUsersRequest("a"); search.AccountType = AccountSearchType.User; search.PerPage = size; search.Page = page; Octokit.UsersClient userCliente = new UsersClient(apiConn); Octokit.SearchClient searchUserService = new SearchClient(apiConn); SearchUsersResult usersResult = searchUserService.SearchUsers(search).Result; Octokit.GitHubClient gitClient = new GitHubClient(connection); Octokit.UsersClient userClient = new UsersClient(apiConn); List<Developer> developers = (from userGit in usersResult.Items select new Developer { User = userGit.Login, UrlAvatar = userGit.AvatarUrl.ToString(), TotalRepo = userGit.PublicRepos, TotalFollowers = userGit.Followers, Price = ((userGit.PublicRepos * pesoTotalRepository) + (userGit.Followers * pesoTotalFollowers)) / (pesoTotalRepository + pesoTotalFollowers) }).ToList(); return developers; }
public PlatronClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); _connection = new ApiConnection(connection); ResultUrl = new ResultUrlClient(_connection); }
public async Task Can_hit_endpoint_if_I_pass_credentials_into_api() { IApi api = new ApiConnection(); var request = api.Create<Status>(); var status = await request.Please(); Assert.That(status, Is.Not.Null); Assert.That(status.ServerTime.Day, Is.EqualTo(DateTime.Now.Day)); }
/// <summary> /// Initialize the API using the config.json file. /// </summary> public virtual void Initialize(int userId, string token) { _connection = new ApiConnection(userId, token); _marketHoursDatabase = MarketHoursDatabase.FromDataFolder(); //Allow proper decoding of orders from the API. JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = { new OrderJsonConverter() } }; }
public async static Task<UserData> GetMe(ApiConnection connection) { var request = new HttpRequestMessage(HttpMethod.Get, connection.Endpoints.Me); request.Headers.Add(connection.Endpoints.Headers.ApiKey, connection.Token); request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(content_type)); var client = new HttpClient(); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); return new UserData(content); }
public override async Task Execute(string[] parameters, IResponse response) { if (parameters.Length < 5) { await response.Send($"I don't understand '{string.Join(" ", parameters.Select(x => "[" + x + "]"))}'."); return; } var repo = parameters[1]; var issueNumberString = parameters[2]; var from = parameters[3]; var to = parameters[4]; string accessToken; if (!TryGetCredential("github-accesstoken", out accessToken)) { await response.Send("I couldnt find a github access token in your credentials. If you add one I will be able to create the pull request on your behalf. Does it sound good? Here are the instructions https://github.com/Particular/Housekeeping/wiki/Generate-GitHub-access-token-for-PBot"); return; } var client = GitHubClientBuilder.Build(accessToken); var apiConnection = new ApiConnection(client.Connection); int issueNumber; if (!int.TryParse(issueNumberString, out issueNumber)) { await response.Send("Issue number should be a valid number dude!"); return; } try { var result = await apiConnection.Post<PullRequest>(ApiUrls.PullRequests("Particular", repo), new ConvertedPullRequest { Issue = issueNumber.ToString(), Head = from, Base = to }, null, "application/json"); await response.Send($"Issue {issueNumber} has been converted into a pull request {result.HtmlUrl}."); } catch (NotFoundException) { response.Send("Sorry, GitHub could not find the issue or repository you are talking about.").ConfigureAwait(false).GetAwaiter().GetResult(); } catch (ApiValidationException ex) { const string errorMessage = "Sorry, your request was rejected by GitHub as invalid."; response.Send(string.Join(Environment.NewLine, errorMessage, ex.GetExtendedErrorMessage())).ConfigureAwait(false).GetAwaiter().GetResult(); } }
public async Task MakesGetRequestForItem() { var getUri = new Uri("anything", UriKind.Relative); IApiResponse<object> response = new ApiResponse<object>(new Response()); var connection = Substitute.For<IConnection>(); connection.Get<object>(Args.Uri, null, null).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var data = await apiConnection.Get<object>(getUri); Assert.Same(response.Body, data); connection.Received().GetResponse<object>(getUri); }
public async Task MakesHtmlRequest() { var getUri = new Uri("anything", UriKind.Relative); IApiResponse<string> response = new ApiResponse<string>(new Response(), "<html />"); var connection = Substitute.For<IConnection>(); connection.GetHtml(Args.Uri, null).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var data = await apiConnection.GetHtml(getUri); Assert.Equal("<html />", data); connection.Received().GetHtml(getUri); }
public async Task MakesGetRequestForItemWithAcceptsOverride() { var getUri = new Uri("anything", UriKind.Relative); var accepts = "custom/accepts"; IResponse<object> response = new ApiResponse<object> { BodyAsObject = new object() }; var connection = Substitute.For<IConnection>(); connection.GetAsync<object>(Args.Uri, null, Args.String).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var data = await apiConnection.Get<object>(getUri, null, accepts); Assert.Same(response.BodyAsObject, data); connection.Received().GetAsync<object>(getUri, null, accepts); }
/// <summary> /// Create a new instance of the GitHub API v3 client using the specified connection. /// </summary> /// <param name="connection">The underlying <seealso cref="IConnection"/> used to make requests.</param> public GitHubClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); Connection = connection; var apiConnection = new ApiConnection(connection); Authorization = new AuthorizationsClient(apiConnection); Issue = new IssuesClient(apiConnection); Miscellaneous = new MiscellaneousClient(connection); Notification = new NotificationsClient(apiConnection); Organization = new OrganizationsClient(apiConnection); Repository = new RepositoriesClient(apiConnection); Release = new ReleasesClient(apiConnection); User = new UsersClient(apiConnection); SshKey = new SshKeysClient(apiConnection); }
public async Task MakesGetRequestForAllItems() { var getAllUri = new Uri("anything", UriKind.Relative); var links = new Dictionary<string, Uri>(); var scopes = new List<string>(); IResponse<List<object>> response = new ApiResponse<List<object>> { ApiInfo = new ApiInfo(links, scopes, scopes, "etag", new RateLimit(new Dictionary<string, string>())), BodyAsObject = new List<object> {new object(), new object()} }; var connection = Substitute.For<IConnection>(); connection.GetAsync<List<object>>(Args.Uri, null, null).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var data = await apiConnection.GetAll<object>(getAllUri); Assert.Equal(2, data.Count); connection.Received().GetAsync<List<object>>(getAllUri, null, null); }
/// <summary> /// Create a new instance of the GitHub API v3 client using the specified connection. /// </summary> /// <param name="connection">The underlying <seealso cref="IConnection"/> used to make requests</param> public GitHubClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); Connection = connection; var apiConnection = new ApiConnection(connection); Authorization = new AuthorizationsClient(apiConnection); Activity = new ActivitiesClient(apiConnection); Blob = new BlobsClient(apiConnection); Issue = new IssuesClient(apiConnection); Miscellaneous = new MiscellaneousClient(connection); Notification = new NotificationsClient(apiConnection); Organization = new OrganizationsClient(apiConnection); Repository = new RepositoriesClient(apiConnection); Gist = new GistsClient(apiConnection); Release = new ReleasesClient(apiConnection); User = new UsersClient(apiConnection); SshKey = new SshKeysClient(apiConnection); GitDatabase = new GitDatabaseClient(apiConnection); Tree = new TreesClient(apiConnection); Search = new SearchClient(apiConnection); }
public async Task WhenGetReturnsOkThenBodyAsObjectIsReturned() { var queuedOperationUrl = new Uri("anything", UriKind.Relative); var result = new object(); const HttpStatusCode statusCode = HttpStatusCode.OK; IApiResponse<object> response = new ApiResponse<object>(new Response(statusCode, null, new Dictionary<string, string>(), "application/json"), result); var connection = Substitute.For<IConnection>(); connection.GetResponse<object>(queuedOperationUrl, Args.CancellationToken).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var actualResult = await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, Args.CancellationToken); Assert.Same(actualResult,result); }
public async Task CanCancelQueuedOperation() { var queuedOperationUrl = new Uri("anything", UriKind.Relative); var result = new object(); IApiResponse<object> accepted = new ApiResponse<object>(new Response(HttpStatusCode.Accepted, null, new Dictionary<string, string>(), "application/json"), result); var connection = Substitute.For<IConnection>(); connection.GetResponse<object>(queuedOperationUrl, Args.CancellationToken).Returns(x => Task.FromResult(accepted)); var apiConnection = new ApiConnection(connection); var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(100); var canceled = false; var operationResult = await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, cancellationTokenSource.Token) .ContinueWith(task => { canceled = task.IsCanceled; return task; }, TaskContinuationOptions.OnlyOnCanceled) .ContinueWith(task => task, TaskContinuationOptions.OnlyOnFaulted); Assert.True(canceled); Assert.Null(operationResult); }
/// <summary> /// Retries the audit trail for all the language files in the given project /// </summary> /// This method requires authentication. /// <param name="projectId">The id of the project</param> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> public Task <IReadOnlyList <AuditTrial> > AuditTrial(string projectId) { Ensure.ArgumentNotNullOrEmptyString(projectId, "projectid"); return(ApiConnection.GetAll <AuditTrial>(ApiUrls.AuditTrial(projectId), null)); }
public async Task MakesGetRequest() { var queuedOperationUrl = new Uri("anything", UriKind.Relative); const HttpStatusCode statusCode = HttpStatusCode.OK; IApiResponse<object> response = new ApiResponse<object>(new Response(statusCode, null, new Dictionary<string, string>(), "application/json"), new object()); var connection = Substitute.For<IConnection>(); connection.GetResponse<object>(queuedOperationUrl,Args.CancellationToken).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); await apiConnection.GetQueuedOperation<object>(queuedOperationUrl,CancellationToken.None); connection.Received().GetResponse<object>(queuedOperationUrl, Args.CancellationToken); }
/// <summary> /// Dispose resources. /// </summary> /// <param name="disposing"></param> public virtual void Dispose(bool disposing) { if (disposing) { if (_connection != null) { _connection.Dispose(); _connection = null; } } }
public IndexManagementClient(ApiConnection connection) { _connection = connection; }
public async Task <IPagination <UserFollower> > GetAsync() { return(await ApiConnection.ExecutePaginationGetAsync <UserFollower>($"{Route}/users", new PageQueryOption()).ConfigureAwait(false)); }
public BaseApi(Passport passport) { _passport = passport; ApiConnection = new ApiConnection(passport); }
private ApiConnection GetConnectionInfo(IShellState shellState, HttpState programState, string rootAddress, string baseAddress, string swaggerAddress, IPreferences preferences, bool isVerbosityEnabled) { rootAddress = rootAddress?.Trim(); baseAddress = baseAddress?.Trim(); swaggerAddress = swaggerAddress?.Trim(); if (string.IsNullOrWhiteSpace(rootAddress) && string.IsNullOrWhiteSpace(baseAddress) && string.IsNullOrWhiteSpace(swaggerAddress)) { shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_NothingSpecified); return(null); } if (!string.IsNullOrWhiteSpace(rootAddress) && !Uri.IsWellFormedUriString(rootAddress, UriKind.Absolute)) { shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_RootAddressNotValid); return(null); } // Even if verbosity is not enabled, we still want to be verbose about finding OpenAPI Descriptions // if they specified one directly. bool logVerboseMessages = isVerbosityEnabled || !string.IsNullOrWhiteSpace(swaggerAddress); ApiConnection apiConnection = new ApiConnection(programState, preferences, shellState.ConsoleManager, logVerboseMessages); if (!string.IsNullOrWhiteSpace(rootAddress)) { // The `dotnet new webapi` template now has a default start url of `swagger`. Because // the default Swashbuckle-generated OpenAPI description doesn't contain a Servers element // this will put HttpRepl users into a pit of failure by having a base address of // https://localhost:{port}/swagger/, even though the API is, by default, based at the root. // Since it is unlikely a user would put their API inside the /swagger path, we will // special-case this scenario and remove that from the url. We will give the user an escape // hatch via the preference if they do put their API under that path. if (rootAddress.EndsWith(WebApiDefaultPathSuffix, StringComparison.OrdinalIgnoreCase)) { WebApiF5FixEvent fixEvent; if (preferences.GetBoolValue(WellKnownPreference.ConnectCommandSkipRootFix)) { fixEvent = new WebApiF5FixEvent(skippedByPreference: true); } else { rootAddress = rootAddress.Substring(0, rootAddress.Length - WebApiDefaultPathSuffix.Length); fixEvent = new WebApiF5FixEvent(); } _telemetry.TrackEvent(fixEvent); } apiConnection.RootUri = new Uri(rootAddress, UriKind.Absolute); } if (!SetupBaseAddress(shellState, baseAddress, apiConnection) || !SetupSwaggerAddress(shellState, swaggerAddress, apiConnection)) { return(null); } apiConnection.AllowBaseOverrideBySwagger = !apiConnection.HasBaseUri; if (apiConnection.HasRootUri && !apiConnection.HasBaseUri) { apiConnection.BaseUri = apiConnection.RootUri; } return(apiConnection); }
private static bool SetupBaseAddress(IShellState shellState, string baseAddress, ApiConnection connectionInfo) { if (!string.IsNullOrWhiteSpace(baseAddress)) { if (!connectionInfo.HasRootUri && !Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute)) { shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_NoRootNoAbsoluteBase); return(false); } else if (connectionInfo.HasRootUri && !Uri.IsWellFormedUriString(baseAddress, UriKind.RelativeOrAbsolute)) { shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_InvalidBase); return(false); } if (Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute)) { connectionInfo.BaseUri = new Uri(baseAddress, UriKind.Absolute); } else if (Uri.IsWellFormedUriString(baseAddress, UriKind.Relative)) { connectionInfo.BaseUri = new Uri(connectionInfo.RootUri, baseAddress); } } return(true); }
public PublicitesApiClient(ApiConnection connection) : base(connection) { }
public IndexQueryClient(ApiConnection connection) { _connection = connection; }
public IndexModel(ILogger <IndexModel> logger) { _logger = logger; GetApi = new ApiConnection(); }
/// <summary> /// Checks if the given language file is check-out to someone other than the user making this call /// </summary> /// <param name="languageFileId">The if of the language file</param> /// <remarks> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// </remarks> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> public async Task <bool> IsCheckoutToSomeoneElse(string languageFileId) { Ensure.ArgumentNotNullOrEmptyString(languageFileId, "LanguageFileId"); return(await ApiConnection.Get <bool>(ApiUrls.IsCheckoutToSomeoneElse(languageFileId), null)); }
public AlarmDAL(ApiConnection apiConnection) { this.ApiConn = apiConnection; }
public async Task EnsuresArgumentNotNull() { var client = new ApiConnection(Substitute.For<IConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetHtml(null)); }
public Index3Model(ILogger <IndexModel> logger, IServiceAlarms alarmService) { _logger = logger; GetApi = new ApiConnection(); _alarmService = alarmService; }
/// <summary> /// Gets all <see cref="Project"/>s for the organization. /// </summary> /// <remarks> /// <param name="organizationName">string</param> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// </remarks> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A list of <see cref="ProjectDetails"/>s.</returns> public List <ProjectDetails> GetProjectsForOrganization(string organizationName) { var allProjects = ApiConnection.Get <Project>(ApiUrls.GetAllProjects(), null); return(allProjects.Result.Items.Where(o => o.OrganizationName == organizationName).ToList()); }
public ArticlesApiClient(ApiConnection connection) : base(connection) { }
/// <summary> /// Initializes a new instance of the <see cref="UsersClient"/> class. /// </summary> /// <param name="connection">The connection.</param> public UsersClient(ApiConnection connection) : base(connection) { }
public HomeController(ApiConnection apiConnection) { _apiConnection = apiConnection; }
public async Task <IPagination <ReadingList> > GetAsync() { return(await ApiConnection.ExecutePaginationGetAsync <ReadingList>(Route, new PageQueryOption()).ConfigureAwait(false)); }
public async Task <dynamic> SuggestSchoolByName(string name) { var connection = ApiConnection.Create(_searchInstance, _key); var client = new IndexQueryClient(connection); Func <SuggestionResultRecord, ExpandoObject> processResult = r => { dynamic retVal = new ExpandoObject(); var postCode = r.Properties["Postcode"] as string; var town = r.Properties["Town"] as string; var schoolName = r.Properties["EstablishmentName"] as string; retVal.Id = r.Properties["URN"]?.ToString(); if (!string.IsNullOrWhiteSpace(postCode) && !string.IsNullOrWhiteSpace(town)) // town and postcode { retVal.Text = $"{schoolName} ({town}, {postCode})"; } else if (!string.IsNullOrWhiteSpace(postCode) && string.IsNullOrWhiteSpace(town)) // just postcode { retVal.Text = $"{schoolName} ({postCode})"; } else if (string.IsNullOrWhiteSpace(postCode) && !string.IsNullOrWhiteSpace(town)) // just town { retVal.Text = $"{schoolName} ({town})"; } else if (string.IsNullOrWhiteSpace(postCode) && string.IsNullOrWhiteSpace(town) ) // neither town nor post code { retVal.Text = schoolName; } if (r.Properties["EstablishmentStatus"].ToString() == "Closed") { retVal.Text += " (Closed)"; } return(retVal); }; var response = await client.SuggestAsync(_index, new SuggestionQuery(name) .SuggesterName("nameSuggester") .Fuzzy(false) .Select("EstablishmentName") .Select("URN") .Select("Town") .Select("Postcode") .Select("EstablishmentStatus") //.Filter("EstablishmentStatus eq 'Open'" + // " and TypeOfEstablishment ne 'Higher Education Institutions'" + // " and TypeOfEstablishment ne 'LA Nursery School'" + // " and TypeOfEstablishment ne 'Other Independent School'" + // " and TypeOfEstablishment ne 'Other Independent Special School'" + // " and TypeOfEstablishment ne 'Welsh Establishment'" + // " and TypeOfEstablishment ne 'Special Post 16 Institution'" + // " and TypeOfEstablishment ne 'Sixth Form Centres'" + // " and TypeOfEstablishment ne 'Service Childrens Education'" + // " and TypeOfEstablishment ne 'Secure Units'" + // " and TypeOfEstablishment ne 'Offshore Schools'" + // " and TypeOfEstablishment ne 'Institution funded by other Government Department'" + // " and TypeOfEstablishment ne 'Free Schools - 16-19'" + // " and TypeOfEstablishment ne 'British Schools Overseas'" + // " and TypeOfEstablishment ne 'Academy 16-19 Sponsor Led'" + // " and TypeOfEstablishment ne 'Academy 16-19 Converter'" + // " and StatutoryLowAge ne '16'" + // " and StatutoryLowAge ne '17'" + // " and StatutoryLowAge ne '18'" + // " and StatutoryLowAge ne '19'") //.Filter("StatutoryHighAge ne '1'" + // " and StatutoryHighAge ne '2'" + // " and StatutoryHighAge ne '3'" + // " and StatutoryHighAge ne '4'" + // " and StatutoryHighAge ne '5'")//Todo: Remove .Do not filter out nurseries. .SearchField("EstablishmentName") .Top(10)); if (!response.IsSuccess) { throw new ApplicationException( $"Edubase school suggestion error {response.Error.Code}: {response.Error.Message}"); } var results = response.Body.Records; var matches = (from r in results select processResult(r)); dynamic ret = new ExpandoObject(); ret.Matches = matches; return(ret); }
/// <summary> /// Gets the dashboard data /// </summary> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> public async Task <Dashboard> Dashboard() { return(await ApiConnection.Get <Dashboard>(ApiUrls.Dashboard(), null)); }
public async Task EnsuresArgumentNotNull() { var connection = new ApiConnection(Substitute.For <IConnection>()); await AssertEx.Throws <ArgumentNullException>(async() => await connection.GetQueuedOperation <object>(null, CancellationToken.None)); }
public async Task WhenGetReturnsNotOkOrAcceptedApiExceptionIsThrown() { var queuedOperationUrl = new Uri("anything", UriKind.Relative); const HttpStatusCode statusCode = HttpStatusCode.PartialContent; IApiResponse<object> response = new ApiResponse<object>(new Response(statusCode, null, new Dictionary<string, string>(), "application/json"), new object()); var connection = Substitute.For<IConnection>(); connection.GetResponse<object>(queuedOperationUrl, Args.CancellationToken).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); await Assert.ThrowsAsync<ApiException>(() => apiConnection.GetQueuedOperation<object>(queuedOperationUrl, Args.CancellationToken)); }
public async Task EnsuresArgumentNotNull() { var client = new ApiConnection(Substitute.For <IConnection>()); await AssertEx.Throws <ArgumentNullException>(async() => await client.GetHtml(null)); }
public async Task GetIsRepeatedUntilHttpStatusCodeOkIsReturned() { var queuedOperationUrl = new Uri("anything", UriKind.Relative); var result = new object(); IApiResponse<object> firstResponse = new ApiResponse<object>(new Response(HttpStatusCode.Accepted, null, new Dictionary<string, string>(), "application/json"), result); IApiResponse<object> completedResponse = new ApiResponse<object>(new Response(HttpStatusCode.OK, null, new Dictionary<string, string>(), "application/json"), result); var connection = Substitute.For<IConnection>(); connection.GetResponse<object>(queuedOperationUrl, Args.CancellationToken) .Returns(x => Task.FromResult(firstResponse), x => Task.FromResult(firstResponse), x => Task.FromResult(completedResponse)); var apiConnection = new ApiConnection(connection); await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, CancellationToken.None); connection.Received(3).GetResponse<object>(queuedOperationUrl, Args.CancellationToken); }
/// <summary> ///Deletes a template /// </summary> /// <param name="templateId">string</param> /// <remarks> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// </remarks> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> public async Task Delete(string templateId) { Ensure.ArgumentNotNullOrEmptyString(templateId, "templateId"); await ApiConnection.Delete(ApiUrls.ProjectTemplates(templateId)); }
public async Task EnsuresArgumentNotNull() { var connection = new ApiConnection(Substitute.For<IConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => connection.GetQueuedOperation<object>(null, CancellationToken.None)); }
/// <summary> /// Health check call used to keep the OE license seat taken /// </summary> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> public async Task <string> OnlineCheckoutHealthCheck() { var response = await ApiConnection.Get <string>(ApiUrls.OnlineCheckoutHealthCheck(), null); return(response); }
public async Task MakesGetRequestForAllItems() { var getAllUri = new Uri("anything", UriKind.Relative); IApiResponse<List<object>> response = new ApiResponse<List<object>>( new Response(), new List<object> { new object(), new object() }); var connection = Substitute.For<IConnection>(); connection.Get<List<object>>(Args.Uri, null, null).Returns(Task.FromResult(response)); var apiConnection = new ApiConnection(connection); var data = await apiConnection.GetAll<object>(getAllUri); Assert.Equal(2, data.Count); connection.Received().Get<List<object>>(getAllUri, null, null); }
public TaxesApiClient(ApiConnection connection) : base(connection) { }
public async Task AllowsEmptyBody() { var connection = Substitute.For<IConnection>(); var apiConnection = new ApiConnection(connection); var client = new TeamsClient(apiConnection); await client.AddMembership(1, "user"); connection.Received().Put<Dictionary<string, string>>( Arg.Is<Uri>(u => u.ToString() == "teams/1/memberships/user"), Arg.Is<object>(u => u == RequestBody.Empty)); }
public async Task <IReadOnlyList <FollowedTag> > GetTagsAsync() { return(await ApiConnection.ExecuteGetCollectionAsync <FollowedTag>($"{Route}/tags").ConfigureAwait(false)); }
public async Task EnsuresArgumentNotNull() { var connection = new ApiConnection(Substitute.For <IConnection>()); await Assert.ThrowsAsync <ArgumentNullException>(() => connection.Delete(null)); }
/// <summary> /// Initializes a new instance of the <see cref="RulesClient"/> class. /// </summary> /// <param name="connection">The connection.</param> public RulesClient(ApiConnection connection) : base(connection) { }
/// <summary> /// Creates a new instance of the Client Grants client. /// </summary> /// <param name="connection">The <see cref="IApiConnection" /> which is used to communicate with the API.</param> public ClientGrantsClient(ApiConnection connection) : base(connection) { }
/// <summary> /// Gets file versions informations<see cref="FileVersion"/>. /// </summary> /// <param name="languageFileId">Language file id></param> /// <remarks> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// </remarks> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns> List <see cref="FileVersion"/>s.</returns> public async Task <IReadOnlyList <FileVersion> > GetFileVersions(string languageFileId) { Ensure.ArgumentNotNullOrEmptyString(languageFileId, "languageFileId"); return(await ApiConnection.GetAll <FileVersion>(ApiUrls.GetFileVersion(languageFileId), null)); }
/// <summary> /// Gets all <see cref="File"/>s for project. /// </summary> /// <param name="projectId">string</param> /// <remarks> /// This method requires authentication. /// See the <a href="http://gs2017dev.sdl.com:41234/documentation/api/index#/">API documentation</a> for more information. /// </remarks> /// <exception cref="AuthorizationException"> /// Thrown when the current user does not have permission to make the request. /// </exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A list of <see cref="File"/>s.</returns> public Task <IReadOnlyList <File> > GetAllFilesForProject(string projectId) { Ensure.ArgumentNotNullOrEmptyString(projectId, "projectId"); return(ApiConnection.GetAll <File>(ApiUrls.ProjectFiles(projectId))); }
protected override async Task ExecuteAsync(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput, ICoreParseResult parseResult, CancellationToken cancellationToken) { programState = programState ?? throw new ArgumentNullException(nameof(programState)); shellState = shellState ?? throw new ArgumentNullException(nameof(shellState)); commandInput = commandInput ?? throw new ArgumentNullException(nameof(commandInput)); if (programState.SwaggerEndpoint != null) { string swaggerRequeryBehaviorSetting = _preferences.GetValue(WellKnownPreference.SwaggerRequeryBehavior, "auto"); if (swaggerRequeryBehaviorSetting.StartsWith("auto", StringComparison.OrdinalIgnoreCase)) { ApiConnection apiConnection = new ApiConnection(_preferences) { BaseUri = programState.BaseAddress, SwaggerUri = programState.SwaggerEndpoint, AllowBaseOverrideBySwagger = false }; await apiConnection.SetupHttpState(programState, performAutoDetect : false, cancellationToken).ConfigureAwait(false); } } if (programState.BaseAddress is null) { shellState.ConsoleManager.WriteLine(Resources.Strings.ListCommand_Error_NoBaseAddress.SetColor(programState.WarningColor)); return; } if (programState.SwaggerEndpoint is null || programState.Structure is null) { shellState.ConsoleManager.WriteLine(Resources.Strings.ListCommand_Error_NoDirectoryStructure.SetColor(programState.WarningColor)); return; } string path = commandInput.Arguments.Count > 0 ? commandInput.Arguments[0].Text : string.Empty; //If it's an absolute URI, nothing to suggest if (Uri.TryCreate(path, UriKind.Absolute, out Uri _)) { return; } IDirectoryStructure s = programState.Structure.TraverseTo(programState.PathSections.Reverse()).TraverseTo(path); string thisDirMethod = s.RequestInfo.GetDirectoryMethodListing(); List <TreeNode> roots = new List <TreeNode>(); Formatter formatter = new Formatter(); roots.Add(new TreeNode(formatter, ".", thisDirMethod)); if (s.Parent != null) { string parentDirMethod = s.Parent.RequestInfo.GetDirectoryMethodListing(); roots.Add(new TreeNode(formatter, "..", parentDirMethod)); } int recursionDepth = 1; if (commandInput.Options[RecursiveOption].Count > 0) { if (string.IsNullOrEmpty(commandInput.Options[RecursiveOption][0]?.Text)) { recursionDepth = int.MaxValue; } else if (int.TryParse(commandInput.Options[RecursiveOption][0].Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int rd) && rd > 1) { recursionDepth = rd; } } foreach (string child in s.DirectoryNames) { IDirectoryStructure dir = s.GetChildDirectory(child); string methods = dir.RequestInfo.GetDirectoryMethodListing(); TreeNode dirNode = new TreeNode(formatter, child, methods); roots.Add(dirNode); Recurse(dirNode, dir, recursionDepth - 1); } foreach (TreeNode node in roots) { shellState.ConsoleManager.WriteLine(node.ToString()); } }
public StudentService() { apiConnection = new ApiConnection(); }