nmklotas / gitlabapiclient Goto Github PK
View Code? Open in Web Editor NEWGitLab API client
License: MIT License
GitLab API client
License: MIT License
Trying to list all projects never returns a response.
var projects = await _client.Projects.GetAsync();
From running fiddler the above command seems not to actually make a request.
Right now it is only possible to fetch group members. However fetching project members would be as much needed.
https://docs.gitlab.com/ee/api/projects.html#project-members
Looking at https://travis-ci.org/nmklotas/GitLabApiClient/pull_requests
I thought my change in #9 would address this, but was wrong. Even though it had built successfully multiple times, it again started to fail with 401 and other errors that lead me to believe the GitLab service was not setup properly for the test run.
Will continue discussion here.
static async Task Main(string[] args)
{
var gitLabClient = new GitLabClient("http://www.gitlab.com/", "------");
Project project = await gitLabClient.Projects.GetAsync("-----");
await gitLabClient.Issues.CreateNoteAsync(project.Id, 10, new CreateIssueNoteRequest
{
Body = "Hello!"
});
}
Newtonsoft.Json.JsonSerializationException:
'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'GitLabApiClient.Models.Notes.Responses.Note'
because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
I am trying to get All issues in a project by Calling client.Issues.GetAsync(projectID);
. Obviously it will return all "Opened" issues in that Project. What i was looking for is to get "ALL" Types of Issues (opened,closed etc). I know the overloaded method takes, Action<ProjectQueryOption>
. I tried different ways, but unable to get it working. Could some one help me in guiding right way to implement it
Extend commit client for refs endpoint. With this, you can get the references that the commit is in (branches / tags).
Hi
How i can get merge requests list filter by field "merge_status" ?
And i not found in GetAsync method field "title", "description"?
I'd like to fix up the request classes to move id / path out of the request object and onto the parameter as type object id
So this pattern
GitLabApiClient/src/GitLabApiClient/ProjectsClient.cs
Lines 129 to 133 in 2f5c1bc
is replaced with
public async Task<Project> UpdateAsync(object id, UpdateProjectRequest request)
{
Guard.NotNull(request, nameof(request));
return await _httpFacade.Put<Project>($"projects/{id.ProjectIdOrPath}", request);
}
public static string ProjectIdOrPath(this object obj)
{
switch (obj)
{
case null:
throw new ArgumentException("ID or Path cannot be null");
case int id:
return id.ToString();
case string path:
return path.UrlEncode();
case Project project:
{
int id = project.Id;
if (id > 0)
{
return id.ToString();
}
string path = project.PathWithNamespace?.Trim();
if (!string.IsNullOrEmpty(path))
{
return path.UrlEncode();
}
break;
}
}
throw new ArgumentException($"Cannot determine project ID or Path from provided {obj.GetType().Name} instance. " +
"Must be int, string, Project instance");
}
reason being id
is path parameter and not a body parameter. Same reason for all these query parameter PRs ๐
Would be great to switch all int id
, int projectId
, int groupId
and int userId
out with object id
so we can allow users to pass string without worrying about URL encoding or finding the damn project id.
When I make a call to client.LoginAsync
, the method never returns. The call in
var accessTokenResponse = await _requestor.Post<AccessTokenResponse>(url, accessTokenRequest);
in GitlabHttpFacade never returns.
Either my self hosted gitlab server blocked the API calls or some thing related to network happened , because my Client application using GitLabAPIClient was working fine until yesterday. Do you have any probable scenarios that may trigger this issue. In either case, the wait should do a timeout . Implemented Cancelation Token in POST request like below,
public async Task<T> Post<T>(string url, object data = null)
{
**var ct = new CancellationTokenSource();
ct.CancelAfter(3000);**
StringContent content = SerializeToString(data);
var responseMessage = await _client.PostAsync(url, content,ct.Token);
await EnsureSuccessStatusCode(responseMessage);
return await ReadResponse<T>(responseMessage);
}
it works, but not fits to the existing code flow. Since I am very new to this API, just getting used to the workflow. The timeout value can be set at GitlabClient level, but putting this cancellation token in all request, must be there a better way to do this.
But the Big question, Why the Gitlab not returning the request? tried both Private key method and then calling client.Project.getAsync() , and issue is same. Iam able to access the Gitlab through browser, restarted my gitlab instance, but still same issue.
Also, When i make a URL request in browser, it returns Jsons
http://myserver/api/v4/projects
Add the ability to get all issues from Group.
Doc Gitlab API :
https://docs.gitlab.com/ee/api/issues.html#list-group-issues
The authentitaion should be wider than the PRIVATE_TOKEN
With Oauth we should also be able to send a Bearer Token
https://docs.gitlab.com/ee/api/oauth2.html#access-gitlab-api-with-access-token
For what i can see the change is on private GitLabHttpFacade:
in this moment:
The request is made with the header Key Authorization and value: Bearer {Token}
...
[JsonProperty("closed_by")]
public string ClosedBy { get; set; }
...
...
"closed_by" : {
"state" : "active",
"web_url" : "https://gitlab.example.com/root",
"avatar_url" : null,
"username" : "root",
"id" : 1,
"name" : "Administrator"
},
...
Please, fix it
[JsonProperty("closed_by")]
public ClosedBy ClosedBy { get; set; }
public class ClosedBy
{
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("web_url")]
public Uri WebUrl { get; set; }
[JsonProperty("avatar_url")]
public Uri AvatarUrl { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
Version : 1.4.0
When I want to create a MergeRequest with these following instruction :
await _client.MergeRequests.CreateAsync("projectId", new CreateMergeRequest("issue/1", "master", "Title")
{
Description = "Closes #1",
RemoveSourceBranch = true
});
My app throw this exception :
System.AggregateException
HResult=0x80131500
Message=Une ou plusieurs erreurs se sont produites.
Source=PGM.GUI
StackTrace:
at PGM.GUI.Utilities.CustomCommand.<>c__DisplayClass11_0.<HandleErrors>b__0(Object o) in D:\GIT\projectgitmanager\PGM.GUI\Utilities\CustomCommand.cs:line 89
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at PGM.GUI.App.Main()
This exception was originally thrown at this call stack:
Newtonsoft.Json.Utilities.EnumUtils.ParseEnum(System.Type, Newtonsoft.Json.Serialization.NamingStrategy, string, bool)
Newtonsoft.Json.Converters.StringEnumConverter.ReadJson(Newtonsoft.Json.JsonReader, System.Type, object, Newtonsoft.Json.JsonSerializer)
Inner Exception 1:
JsonSerializationException: Error converting value "checking" to type 'GitLabApiClient.Models.MergeRequests.Responses.MergeStatus'. Path 'merge_status', line 1, position 791.
Inner Exception 2:
ArgumentException: Requested value 'checking' was not found.
HttpRequestException: The SSL connection could not be established, see inner exception. i have this error , whenever i run my app , i'm using a gitlab server locally for project reasons , i just need to enable ssl connection ...
Hello, I'd like to report a following bug:
What happened:
Calling MergeRequestsClient.GetAsync
method with ProjectMergeRequestsQueryOptions
and specifying MergeRequestsIds
does not filter it.
Repro steps:
Example code:
client.MergeRequests.GetAsync(projectId, o => { o.State = GitLabApiClient.Models.MergeRequests.Requests.QueryMergeRequestState.Merged; o.MergeRequestsIds.Add(mergeRequestId); });
Such call returns all merged requests for given project, not just the one specified in the options property.
Desired output:
Only merge request with given id is returned.
I have also looked into the code and I think I know where the problem lays:
The two query builders (generic & project) are incorrectly switched in GetAsync
methods in MergeRequestsClient.cs
_projectMergeRequestsQueryBuilder
this method is for project options but uses generic _mergeRequestsQueryBuilder
I Have this code.
public class GitLabProvider
{
public static GitLabClient Client { get; private set; }
private static string gitlabHost = "https://gitlab.com";
private static string gitlabToken = "token";
public static void ConnectToGitLab()
{
Console.WriteLine("Connecting to GitLab client via Token..");
Client ??= new GitLabClient(gitlabHost, gitlabToken);
}
}
Why can't used withawait
like
var groups = await GitLabProvider.Client.Groups.SearchAsync("azhe");
Instead of .Result
var groups = GitLabProvider.Client.Groups.SearchAsync("azhe").Result;
use await
will return empty.
GitLab API has two ways to access the project info (see doc).
Add this functionality please.
The issue weight and issue time stats (including estimated and spent time) are missing the response model of the IssueClient.
hi all!
in the issue web page there is a button to let the user to move the issue into another project.. how can I do this by code?
thank you!
From the Environments docs:
Environments allow control of the continuous deployment of your software, all within GitLab.
...
- Provides a full history of your deployments for each environment.
- Keeps track of your deployments, so you always know what is currently being deployed on your servers.
API endpoints are available on https://docs.gitlab.com/ee/api/environments.html
Release drafter uses Pull requests and labels to generate release notes :)
Read more about release drafter here: https://github.com/toolmantim/release-drafter
See usage here: https://github.com/jenkinsci/configuration-as-code-plugin/releases
See example config here: https://github.com/jenkinsci/.github/blob/master/.github/release-drafter.yml
See documentation:
https://docs.gitlab.com/ee/api/merge_request_approvals.html
I think this
should be the IssueIid. While using the lib i noticed a 404 error after passing the IssueId instead of the Iid here. Also the comment indicates that the Iid should be passed here.Anyway great lib ๐
For example, the operations to branches?
I created a function to also import issue attachements. I still need to add it to this lib. For anyone looking to do the work by yourself:
See: https://docs.gitlab.com/ee/api/projects.html#upload-a-file
private async Task<string> GitLabFileUploadAsync(string url, string token, string projectId, byte[] file, string fileName)
{
using (var httpClient = new HttpClient())
{
var form = new MultipartFormDataContent
{
{ new ByteArrayContent(file, 0, file.Length), "file", fileName }
};
form.Headers.Add("PRIVATE-TOKEN", token);
using (HttpResponseMessage response = await httpClient.PostAsync($"{url}/api/v4/projects/{projectId}/uploads", form))
{
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
}
}
The returning string contains the markdown to add the uploaded files to your issues,
The issue model from GitLab has information about the tasks inside of the issue. This should be also repesented in our model (like we already do for time statistic).
"task_completion_status":{
"count":0,
"completed_count":0
}
When using Octokit for querying GitHub, it is possible to do something like:
var gitHubClientRepositoryCommitsCompare = await _gitHubClient.Repository.Commit.Compare(user, repository, "master", currentMilestone.Title).ConfigureAwait(false);
return gitHubClientRepositoryCommitsCompare.AheadBy;
Which returns the number of commits between the current milestone/tag and the master branch. Do you know if there is something similar in the GitLab API for getting the same information?
I'd like to contribute models for webhooks events :)
https://docs.gitlab.com/ee/user/project/integrations/webhooks.html
It seems the only way to limit things to a certain project is the int id. And getting the int id is not easy on a large gitlab setup (took 2 minutes for me to client.Projects.GetAsync()
)
The gitlab API does support escaped group/project
endpoints. I.e. $"projects/{group}%2F{project}/repository/commits"
I do not see a way to specify it in that fashion, but it would be very helpful
Hi!
I am trying to do a search action in a given project (basically do this)
Does this lib support it?
Thanks!
Consider dropping .NET 4.5.2
Let's target .NET Standard 2.0 and .NET Core 3.0.
Hopefully with .NET Core 3.0 we can slowly convert the API to have nullable references
Switch to use System.Text.Json for improved performance.
I noticed a 2 second reduction in a simple data set of 1050 slack users with only the slack id and emails attributes while deserializing into a POCO
I get an cast exception on empty header values for next page. I use GitLab 12.3.5. If I try the request in Postman, I see, that X-Prev-Page
is empty. GetFirstHeaderValueOrDefault
checks only for null
. The same for X-Next-Page
, if there a only one page of data.
I will create a PR with fix for this.
System.FormatException : Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at GitLabApiClient.Internal.Http.HttpResponseHeadersExtensions.GetFirstHeaderValueOrDefault[T](HttpResponseHeaders headers, String headerKey) in C:\src\External\GitLabApiClient\src\GitLabApiClient\Internal\Http\GitLabApiPagedRequestor.cs:line 110
at GitLabApiClient.Internal.Http.GitLabApiPagedRequestor.GetPagedList[T](String url) in C:\src\External\GitLabApiClient\src\GitLabApiClient\Internal\Http\GitLabApiPagedRequestor.cs:line 27
I have just attempted to create a GitLab Release through the API when the tag doesn't currently exist on the Repository. When I did this, I got the following response in Fiddler:
Looking at the documentation, it suggests that when the tag doesn't exist, I can specify a Ref
to point to:
https://docs.gitlab.com/ee/api/releases/#create-a-release
However, I don't see anywhere in the CreateReleaseRequest
class that maps to the Ref
parameter.
Does this exist somewhere? Or is this something that needs to be added to the GitLabApiClient?
The /namespaces API (https://docs.gitlab.com/ee/api/namespaces.html) returns a list of all namespaces available to a user.
It seems like the type returned from that API is compatable with GitLabApiClient.Models.Projects.Responses.Namespace.
I'd like to contribute pipelining support to this library, as mentioned in #25.
I think the basic functionality could be done like all other clients currently, as long as there is no other way forward.
Thoughts?
Properly need to avoid using too many internal options.
System.ArgumentException: Item has already been added. Key in dictionary: 'recursive' Key being added: 'recursive'
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at System.Collections.Hashtable.Add(Object key, Object value)
at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
at System.Collections.Specialized.NameValueCollection.Add(String name, String value)
at GitLabApiClient.Internal.Queries.QueryBuilder`1.Add(String name, String value)
at GitLabApiClient.Internal.Queries.QueryBuilder`1.Add(String name, Boolean value)
at GitLabApiClient.Internal.Queries.TreeQueryBuilder.BuildCore(TreeQueryOptions options)
at GitLabApiClient.Internal.Queries.QueryBuilder`1.Build(String baseUrl, T options)
at GitLabApiClient.TreesClient.GetAsync(ProjectId projectId, Action`1 options)
Hello.
Is there a reason, why all clients are sealed? With sealed classes it is realy hard to extend the clients with own implementations (e.g. labels of groups or pipeline).
With not sealed classed it would be fine to test the new function with extended classes and all works as expected, perhaps make an merge request with the changes to the origin client.
Support for AutoDevopsEnabled (auto_devops_enabled) property for groups
@nmklotas Could you generate a new API key and add to appveyor.yml?
Error publishing package.
NuGet server returned 403: The specified API key is invalid, has expired, or does not have permission to access the specified package.
I want to filter out the projects I retrieve from Git based on Path, Name or any other criteria.
Currently I'm retrieving projects like so:
var gitProjects = await gitClient.Projects.GetAsync();
Is there some parameter I can pass to the GetAsync function which will filter out the projects before retrieving them?
I checked the code for Projects.GetAsync() and found that it takes
Action<ProjectQueryOptions> options
as a parameter. But I cannot instantiate a class of ProjectQueryOptions as the constructor is not public.
Need help?
Hi.
Are you planning to add support for Markdown API ?
Is there a way to access the wiki content using this library?
Hello~
I need "Closed_at" & "Closed_by" Property in 'Issue' (& 'Merge request') Model.
Can you add it ?
I think type the next code somewhere.
[JsonProperty("closed_at")]
public DateTime? ClosedAt { get; set; }
[JsonProperty("closed_by")]
public string ClosedBy { get; set; }
Thanks~
Hey,
This project seems very interesting, I would like to know if there is any documentation for
functions usage?
Do you have any plans to support MockHttp or Moq.Contrib.HttpClient for unit test?
This could be a silly question, and I apologise in advance if this is covered elsewhere, but I can't immediately find a way to get what I need...
I want to be able to get all the Milestones for a project that I have on gitlab.com. The project in question is https://gitlab.com/gep13/fakeproject. In order to get the milestones, I have to provide the project id, and I don't see a way to get this information easily. Can you please provide an example to explain what I am missing?
Thanks!
I'm currently working on a feature to support the Branches API from Gitlab
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.