Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Form Properties by object #116

Open
auriou opened this issue Nov 29, 2020 · 0 comments
Open

Add Form Properties by object #116

auriou opened this issue Nov 29, 2020 · 0 comments

Comments

@auriou
Copy link

auriou commented Nov 29, 2020

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


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant