Coder Social home page Coder Social logo

gitlabapiclient's People

Contributors

ap0llo avatar bonzani avatar db2222 avatar dnagl avatar dteuchert avatar ilijamitkov avatar jadentom avatar jeremybeier avatar jetersen avatar jhenkens avatar mannimanfred avatar mberginbh avatar mindaugaslaganeckas avatar mlinduska avatar mypowerhd avatar nmklotas avatar pmsudhi avatar ponomnikita avatar qayshp avatar redblueflame avatar robnasby avatar saber-wang avatar sandercox avatar sfmskywalker avatar tellespallabob avatar tpayne84 avatar viarzhbouski avatar webducer avatar xzxzxc avatar yankun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gitlabapiclient's Issues

Unable to list all projects

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.

Can't create issue note.

Sample Code

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!"
      });
}
  • The number of issue is 10.
    image

Exception

image

  • message
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.
  • reference code
    • GitLabApiClient.Internal.Http.Serialization.RequestsJsonSerializer.Deserialize(string) in JsonSerializer.cs
    • GitLabApiClient.Internal.Http.GitLabApiRequestor.ReadResponse(System.Net.Http.HttpResponseMessage) in GitlabApiRequestor.cs

Accessing All Issues in a project

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

Get list MR?

Hi

How i can get merge requests list filter by field "merge_status" ?

And i not found in GetAsync method field "title", "description"?

fixup request classes and use id/path as a object on method being called

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

public async Task<Project> UpdateAsync(UpdateProjectRequest request)
{
Guard.NotNull(request, nameof(request));
return await _httpFacade.Put<Project>($"projects/{request.ProjectId}", request);
}

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.

This should help solve #18 and #33

LoginAsync waiting Infinitely

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

Oauth Bearer Token Authorization

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:

private const string PrivateToken = "PRIVATE-TOKEN";

in this moment:

_httpClient.DefaultRequestHeaders.Add(PrivateToken, authenticationToken);

The request is made with the header Key Authorization and value: Bearer {Token}

Error deserialize closed issue json

Issue.cs#L40:

...
[JsonProperty("closed_by")]
public string ClosedBy { get; set; }
...

GitLab API Documentation:

...
   "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; }
}

The "checking" merge_status are missing on MergeStatus Model

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.

how to enable ssl connection please?

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 ...

ProjectMergeRequestsQueryOptions

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

string query = _projectMergeRequestsQueryBuilder.
this method is for generic options but uses _projectMergeRequestsQueryBuilder

string query = _mergeRequestsQueryBuilder.
this method is for project options but uses generic _mergeRequestsQueryBuilder

Use await vs .Result

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.

how can I move an issue?

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!

Project file upload

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,

Extend issue model with task status

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
}

Question: Is there something similar to the GitHub Compare API

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?

Ability to use project name as id

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

Search user in project

Hi!

I am trying to do a search action in a given project (basically do this)

Does this lib support it?

Thanks!

Target Core 3.0?

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

Cast exception on empty header values

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

Issue when creating Release through API

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:

image

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

image

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?

Add support for Pipelines

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?

Trees Client cannot handle parallism

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)

Sealed clients

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.

NuGet API key expired

@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.

Unable to filter projects when retrieving them

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?

how to search "!="

I want to use "not" condition for search.
image

  • public Task<IList<Issue>> GetAllAsync(ProjectId projectId = null, GroupId groupId = null, Action<IssuesQueryOptions> options = null);

  • how to use IssuesQueryOptions?

ProtectBranchAsync throws exception

image
Here's my code
ProtectBranchAsync( project, new ProtectBranchRequest( "master", ProtectedRefAccessLevels.MAINTAINER_ACCESS, ProtectedRefAccessLevels.MAINTAINER_ACCESS, ProtectedRefAccessLevels.MAINTAINER_ACCESS))

Add 'Closed_~' Property in some models

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~

Project documentation

Hey,
This project seems very interesting, I would like to know if there is any documentation for
functions usage?

How to get project id?

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.