This topic is locked
[SOLVED]

Creating a GET API call ...... equivalent MVC function to MVCFunctions.runner_post_request

12/23/2023 5:34:42 AM
ASPRunner.NET General questions
D
david powell author

HI,

I am using this sample of code

dynamic _params = XVar.Array();
_params.InitAndSetArrayItem("Beer", "CategoryName");
_params.InitAndSetArrayItem("Beer and stuff", "Description");
dynamic url = "http://localhost:8086/api/v1?table=categories&action=insert";
dynamic result = MVCFunctions.runner_post_request(url, _params);
MVCFunctions.print_r(result);

to create an POST API call.

I am modifying it to do a GET, but this function

dynamic result = MVCFunctions.runner_get_request(url, _params)

does not exist.

There are of posts about MVCFunction lists, and I understand they are to be avoided and replaceable by a c# code function. Can anyone help me with what that c# syntax would be... or what the undocumented MVCFunction equivalent would be???

Many thanks!

Sergey Kornilov 12/23/2023

Why don't you use the sample C# code from the manual:
https://xlinesoft.com/asprunnernet/docs/rest-api-list.htm

D
david powell author 12/23/2023

Because trying to use RestSharp, which would be fine, I am still failing to get asprunner to compile, as it gives a series of errors starting with:

The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51

Include file has

using RestSharp;
using RestSharp.Authenticators;

Test script has

var client = new RestClient("http://localhost:8086/api/v1.php?table=customers&action=list");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

I have tried using latest verion of ..net available on asprunner, and changed to visual studio 2019 , all to no avail.

Hence trying to use the code above instead, but defeated by that because of the apparent absence of MVCFunctions.runner_get_request(url, _params)

I have tried using c# script using https client but that fails because of an SSL connection error which I cant overcome. Each avenue seems to be out to defeat me!

D
david powell author 12/26/2023

OK, I have tried a variety of methods to try and get API calls working programmatically. I couldnt get RestSharp to compile properly, probably because it requires Net Standard version 2.0.0.0 and doesnt like the versions which ASPrunner offers (though I may be wrong about this). Using the built in HTTPs functions produces SSL problems.

However, I have managed to make it work using NewtonSoft.Json.

I attach what I did to install this third party dll, and a couple of code fragments - one to get a list, one to do an insert, both using basic authentication. The coding is not pretty, but they do work for the APIs I need to interface with.

I put it here so if you are stuck like I was you might find a way forward using this as a basis.

Good luck!

  1. Download newtonsoft.json.dll eg from https://www.dllme.com/dll/files/newtonsoft_json


  2. In Asprunner go to style page, scroll to bottom of list on left and under 'custom files' create a folder called bin


  3. Right click 'bin' and import the dll. Your style page will look like this:


  4. In Asprunner go to events, scroll to bottom of list to left and in the c# imports section type in the following lines:
    using System;
    using System.IO;
    using System.Web;
    using System.Text;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;


  5. To test, create a couple of buttons and in the server events try code sections like the following: with third party API I am using these work fine, but they will need adjusting to suit the API documentation you are using - but the principle will hopefully work.

    // perform a 'list' API call - structure depends on API documentation
    //declare endpoint
    string url = "https://xxxxxxxxxx/api/v1?table=tablename&action=list";
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
    //basic authentication criteria
    string username = "xxxyyy";
    string password = "eeefff";
    myReq.Credentials = new NetworkCredential(username, password);
    //perform api call
    WebResponse wr = myReq.GetResponse();
    Stream receiveStream = wr.GetResponseStream();
    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
    string content = reader.ReadToEnd();
    var json = "[" + content + "]"; // change this to array
    //convert incoming json into an array
    var objects = JArray.Parse(json); // parse as array

    foreach (JObject o in objects.Children<JObject>())
    {
    foreach (JProperty p in o.Properties())
    {
    string name = p.Name;
    string value = p.Value.ToString();
    //process data
    "')");
    }
    }

    //perform a POST using basic authentication
    //declare url
    string url = "https://xxxxxx/api/v1";
    //declare a couple of variables to insert
    string firstname = "john";
    string lastname = "doe";
    // This example uses key-value pairs rather than a json
    var formData = new Dictionary<string, string>
    {
    { "firstname", firstname },
    { "lastname", lastname }
    };



string username = "user";
string password = "password";
// Create an HttpClient instance
using (HttpClient client = new HttpClient())
{
// Set the Authorization header using Basic Authentication
string credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + credentials);

try
{
// Update the URL to include the parameters in the query string
string fullUrl = url + "?table=tablename&action=insert";

// Make the POST request with key-value pairs in the request body
HttpResponseMessage response = client.PostAsync(fullUrl, new FormUrlEncodedContent(formData)).Result;

// Check if the request was successful
if (response.IsSuccessStatusCode)
{
// Read and display the response content
string responseContent = response.Content.ReadAsStringAsync().Result;
//process results
}
else
{
// Display the error status code

}
}
catch (Exception ex)
{
// Handle exceptions, e.g., network errors
Console.WriteLine("Exception: " + ex.Message);
}

}