Giter Site home page Giter Site logo

tiny.restclient's People

Contributors

jgiacomini avatar lordinaire avatar makanwg avatar thomaslevesque 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  avatar

tiny.restclient's Issues

Add Form Properties by object

I suggest you a feature to add properties in a form by passing a class.
this can also be used for querystring and multipart stringcontent

public IFormRequest AddFormParameters<TParameters>(TParameters parameters)
    where TParameters : class
{
    if (_formParameters == null)
    {
        _formParameters = new List<KeyValuePair<string, string>>();
        _content = new FormParametersContent(_formParameters, null);
    }

    foreach (var property in typeof(TParameters).GetProperties())
    {
        var getValue = property.GetValue(parameters);
        string value = null;
        if (getValue != null)
        {
            if (IsGenericList(property.PropertyType))
            {
                var values = (IEnumerable)getValue;
                value = string.Join(",", values.OfType<object>());
            }
            else if (property.PropertyType == typeof(DateTime)
                     || property.PropertyType == typeof(DateTime?))
            {
                value = ((DateTime)getValue).ToString("s");
            }
            else
            {
                value = getValue.ToString();
            }
        }

        if (!string.IsNullOrEmpty(value))
        {
            _formParameters.Add(new KeyValuePair<string, string>(property.Name, value));
        }
    }

    return this;
}

public static bool IsGenericList(Type type)
{
    if (type == null)
    {
        throw new ArgumentNullException(nameof(type));
    }

    foreach (var @interface in type.GetInterfaces())
    {
        if (@interface.IsGenericType)
        {
            if (@interface.GetGenericTypeDefinition() == typeof(IList<>))
            {
                return true;
            }
        }
    }

    return false;
}


AddUriParameter Support in Tiny.RestClient- Example Code Snippnet

Tiny.RestClient is a great library. Some of us believe it could upgraded to surpass all Http Client programs

Reference to old Issue on AddUriParameter, here is an Example

public void GET_with_resource_containing_tokens()
        {
            RestRequest request = new RestRequest("resource/{foo}");
            request.AddUrlSegment("foo", "bar");
            RestClient client = new RestClient(new Uri("http://example.com"));
            Uri expected = new Uri("http://example.com/resource/bar");
            Uri output = client.BuildUri(request);
            Assert.AreEqual(expected, output);
        }

public void POST_with_resource_containing_tokens()
        {
            RestRequest request = new RestRequest("resource/{foo}", Method.POST);
            request.AddUrlSegment("foo", "bar");
            RestClient client = new RestClient(new Uri("http://example.com"));
            Uri expected = new Uri("http://example.com/resource/bar");
            Uri output = client.BuildUri(request);
            Assert.AreEqual(expected, output);
        }

Post MultiPart Form with file or bytes throws on HttpContent.Dispose

I am using a release version after 8e16d65, which fixed the 'PATCH' issue.

When I post bytes data to my server, T.RC throws exception. And if I rewrite my request with Builtin HttpClient, it works fine.

var req = client.Post("upload").AddHeader("Authorization", "TOKEN_STRING") as IRequest;
var res = await req.AsMultiPartFromDataRequest()
    .AddByteArray(new byte[]{0x11}, "file", "picture.png", "image/jpg")
    .ExecuteAsHttpResponseMessageAsync();

throws following exception.

Exception: System.NullReferenceException: Object reference not set to an instance of an object
  at System.Net.Http.MultipartContent.Dispose (System.Boolean disposing) [0x00003] in <xxx>:0 
  at System.Net.Http.HttpContent.Dispose () [0x00000] in <xxx>:0 
  at Tiny.RestClient.TinyRestClient+<ExecuteAsHttpResponseMessageResultAsync>d__25.MoveNext () [0x00164] in <xxx>:0 

HttpClient implementation works as expected.

ByteArrayContent content = new ByteArrayContent(new byte[]{0x11});
content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpg");

MultipartFormDataContent formData = new MultipartFormDataContent
{
    { content,"file","picture.jpg" }
};

HttpClient http = new HttpClient { BaseAddress = new Uri("https://api.server.com") };
http.DefaultRequestHeaders.Add("Accept", "application/json");
http.DefaultRequestHeaders.Add("Authorization","TOKEN");

try
{
    return await http.PostAsync("/upload", formData);
}
finally
{
    formData.Dispose();
    content.Dispose();
    http.Dispose();
}

Compressed responses dispose before they can be read

I couldn't get GZip result decompression to return anything but null, so I took a look.

In TinyRestClient.DecompressAsync:

try
{
return await compression.DecompressAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false);
}
finally
{
stream.Dispose();
}

Because this is a finally clause instead of a catch clause, it's always disposed. Which means the stream.CanRead fails here:

if (stream == null || !stream.CanRead)
{
return null;
}

Would it be sufficient to switch this to a catch? Will it be disposed later otherwise?

TinyRestClient, usage pattern

Hi, thanks for this nice library. Wanted to know if var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api"); object should be created globally and 1 per application just like recommended for HttpClient or should be used with using pattern.

Thanks

Support for System.Text.Json

The built-in JSON serializer uses Newtonsoft.Json.
But in ASP.NET Core 3.0, the default serializer is System.Text.Json. It would be nice if Tiny.RestClient supported it, because:

  • It has better performance than Newtonsoft.Json
  • If the rest of the application uses System.Text.Json, it would be better if everything used it. It would be more consistent, and would allow reuse of the same settings, converters, etc.

It's easy enough to implement a IFormatter that uses System.Text.Json, but there's a bit of an impedance mismatch between the IFormatter and System.Text.Json APIs... IFormatter only has synchronous methods that take a Stream. But System.Text.Json doesn't have synchronous methods that accept a stream, only async ones. And they return a ValueTask, so we can't just use .Result.
Maybe the solution would be to add a IAsyncFormatter interface. If the formatter implements it, use the async methods, if not, use the sync methods.

Add shortcuts for verb requests

Example :
client.GetRequest("City").ExecuteAsync();
client.PostRequest(city, "City").ExecuteAsync();
client.PutRequest(city, "City").ExecuteAsync();
client.DeleteRequest("City").ExecuteAsync();

How to log

I want to uniformly set the pre and post request processing actions

Use jsonSerializer for Serialization

StringWriter stringWriter = new StringWriter(new StringBuilder(256), (IFormatProvider) CultureInfo.InvariantCulture);
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter) stringWriter))
{
jsonTextWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize((JsonWriter) jsonTextWriter, value, type);
}
return stringWriter.ToString();

License info missing

Hello,
i would like to use Tiny.RestClient in our project, but there is no license info.

PostRequest Bearer

Hello,

First at all thank you for this RestClient i love it.

I got some question for you i didnt find same methods form GET or POST, specially for the bearer authentication

GET Version

var response = await client.GetRequest(uriPath)
                    .WithOAuthBearer(_adminToken)
                    .WithTimeout(TimeSpan.FromSeconds(TIMEOUT_SEC))
                    .ExecuteAsync<object>();

POST VERSION

var responseEmail = await client.PostRequest(uriPath, myObject)
                    .WithOAuthBearer(_adminToken) // <=== DO NOT EXIST
                    .WithTimeout(TimeSpan.FromSeconds(TIMEOUT_SEC)) // <=== DO NOT EXIST
                    .ExecuteAsync<object>();

I think i should use like this :

.AddHeader("Authorization", "Bearer " + _adminToken) ?

and how add timeout parameter?

Thanks

Add several files in multipart

add multiple files dynamically

public IMultipartFromDataRequest AddFiles(List<FileMultiPart> files)
{
    foreach (var file in files)
    {
        AddByteArray(file.Bytes, file.Name, file.FileName, file.ContentType);
    }

    return this;
}

public class FileMultiPart
{
    public string Name { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public byte[] Bytes { get; set; }

    public FileMultiPart(string name, string fileName, byte[] bytes, string contentType = null)
    {
        Name = name;
        FileName = fileName;
        Bytes = bytes;
        ContentType = contentType;
    }

    public static List<FileMultiPart> Factory(string name, List<KeyValuePair<string, byte[]>> fileKeyValuePairs) =>
        fileKeyValuePairs.Select(p => new FileMultiPart(name, p.Key, p.Value))
            .ToList();
}

Http librairie should not through http exception

Hi,

I think that this libraries should not through exception when http 400 code is returned. The status code is an information not a crash. It is the same for 500 status code. The response can contain useful information. The exception behavior intricate the code behind. It is the consumer choice to through an Exception or not and that depends of your needs.

What do you think about?

Regards,

IFormFile object in API controller is null

Hello, I'm trying to send IFormFile from razor post form, to a web API project. The controller API method is being called successfully but the object that is passed to API controller from razor view controller is null "IFormFile object".
What should I do ?
EDIT
I Tried the AddContent, and AddFileContent methods, and nothing worked. I tried to add the IFormFile object in an object of class, and in the method parameters, in first one all the object is null, and second one only IFormFile is null.

Deserialize by HttpStatus

Would it be possible to deserialize the return object compared to the http status.
Example of signature of one of my methods

[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginAuthModel))]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))]
[Consumes("application/json")]
public async Task<IActionResult> Login([FromBody] LoginRequest model)

Support `-F` / `--form` in MultiPartFromDataRequest

I'd like to translate the following cURL to the Tiny.RestClient request:

curl -v -u yourapikey:X -F "attachments[]=@/path/to/attachment1.ext" -F "attachments[]=@/path/to/attachment2.ext" -F "[email protected]" -F "subject=Ticket Title" -F "description=this is a sample ticket" -X POST 'https://domain.freshdesk.com/api/v2/tickets'

When I use the client to post the request:

var rs = await client.PostRequest("tickets")
                     .AsMultiPartFromDataRequest()
                     .AddString("[email protected]", "email")
                     .ExecuteAsStringAsync(CancellationToken.None);

...And I have a cURL listener (client.Settings.Listeners.AddCurl()), the translated cURL is (some data stripped off):

curl -X POST [...] -d "--1c3acb07-77bd-494d-bc56-21290dcd5088
Content-Type: text/plain
Content-Disposition: form-data; name=email

[email protected]
[...]

The "email" param is passed with the -d flag; how can I make the param passed by -F flag?

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.