Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Call C# functions from anywhere using URL (HTTP server)
#5
C# client examples.

Code:
Copy      Help
using System.Net.Http;

#region examples
LaHttp.Call("Simple"); //"http://localhost:4455/Simple"

LaHttp.Call("http://:password278351@localhost:4455/Simple");

string s1 = LaHttp.CallS("Returns");
print.it(s1);

LaHttp.Call("Parameters", "a=aa", "c=10", "d=true");

int i1 = 3, i2 = 4;
int i3 = LaHttp.CallS("Add", $"x={i1}", $"y={i2}").ToInt();
print.it(i3);

POINT p1 = new POINT(2, 3);
POINT p2 = LaHttp.CallJ("Json", p1).Json<POINT>();
print.it(p2);
#endregion

/// <summary>
///
Calls C# functions on a computer where <see href="https://www.libreautomate.com/forum/showthread.php?tid=7468">LibreAutomate HTTP server</see> is running.
/// </summary>
///
<example>
///
<code><![CDATA[
/// LaHttp.Call("Simple"); //"http://localhost:4455/Simple"
///
/// LaHttp.Call("http://:password278351@localhost:4455/Simple");
///
/// string s1 = LaHttp.CallS("Returns");
/// print.it(s1);
///
/// LaHttp.Call("Parameters", "a=aa", "c=10", "d=true");
///
/// int i1 = 3, i2 = 4;
/// int i3 = LaHttp.CallS("Add", $"x={i1}", $"y={i2}").ToInt();
/// print.it(i3);
///
/// POINT p1 = new POINT(2, 3);
/// POINT p2 = LaHttp.CallJ("Json", p1).Json<POINT>();
/// print.it(p2);
/// ]]></code>
///
</example>
public class LaHttp {
    /// <summary>
    ///
Calls a function with 0 or more parameters.
    /// </summary>
    ///
<param name="url">
    ///
URL like "http://HOST:4455/FunctionName".
    /// <br/>• HOST can be: localhost (this computer); IP; LAN computer name; web server (like www.example.com).
    /// <br/>• Password can be specified like "http://:password@HOST:4455/FunctionName".
    /// <br/>• If the HTTP server is on the same computer and don't need a password, can be just function name.
    /// </param>
    ///
<param name="a">Parameter like <c>"name=value"</c>.</param>
    public static HttpResponseMessage Call(string url, params string[] a) {
        _Url(ref url, out var auth);
        var c = new MultipartFormDataContent();
        foreach (var s in a) {
            string n, v;
            int i = s.IndexOf('='); if (i < 1) throw new ArgumentException("Expected \"name=value\"", "a");
            n = s[..i]; v = s[++i..];
            if (n[0] == '@') c.AddFile(n[1..], v); else c.Add(n, v);
        }

        return _Post(url, c, auth);
    }

    
    /// <summary>
    ///
Calls a function and passes an object of any type converted to JSON.
    /// </summary>
    ///
<inheritdoc cref="Call(string, string[])"/>
    public static HttpResponseMessage CallJ<T>(string url, T x) {
        _Url(ref url, out var auth);
        return _Post(url, internet.jsonContent(x), auth);
    }

    
    static void _Url(ref string url, out string auth) {
        auth = null;
        if (!url.RxIsMatch("^https?://")) url = "http://localhost:4455/" + url;
        else if (url.RxMatch(@"^https?://(.*?:.*?)@", 1, out RXGroup g)) { auth = g.Value; url = url.Remove(g.Start, g.Length + 1); }
    }

    
    static HttpResponseMessage _Post(string url, HttpContent c, string auth) {
        var r = internet.http.Post(url, c, auth: auth);
        if (!r.IsSuccessStatusCode) {
            var text = r.Text(ignoreError: true);
            if (text.NE()) r.EnsureSuccessStatusCode();
            else throw new HttpRequestException($"Status {(int)r.StatusCode}. {text}", null, r.StatusCode);
        }

        return r;
    }

    
    /// <summary>
    ///
Calls a function with 0 or more parameters, and returns the response text.
    /// </summary>
    ///
<inheritdoc cref="Call(string, string[])"/>
    public static string CallS(string url, params string[] a)
        => Call(url, a).Text();
    
    /// <summary>
    ///
Calls a function, passes an object of any type converted to JSON, and returns the response text.
    /// </summary>
    ///
<inheritdoc cref="Call(string, string[])"/>
    public static string CallJS<T>(string url, T x) //note: not CallS overload. Then goes here if single parameter.
        => CallJ(url, x).Text();
    
    //rejected. It's easier to use code Call(...).Json<TReturn>();.
    //public static TReturn CallJJ<TParam, TReturn>(string url, TParam x)
    //    => Call(url, x).Json<TReturn>();

}

Changes
2023-06-22:
- Supports error descriptions in response body, to match the updated HTTP server code.
- Some functions renamed.
- Changed the type of parameters. Was tuple ("name", "value"), now string "name=value".
- And more improvements.


Messages In This Thread
RE: Call C# functions from anywhere using URL (HTTP server) - by Gintaras - 06-07-2023, 05:43 AM

Forum Jump:


Users browsing this thread: 4 Guest(s)