Call cloud function with c#

How can I call my cloud function from visual studio in c#? I have a windows application that is tied to some other database functions and I just need to be able to update my photon after I’ve updated the database. I’ve tried dozens of general suggestions on the internet. Here’s what I have so far(function is replaced with my function name and access_token is my access token) In my photon code, to test, I just want to return a 1 any time this function is called, regardless of the content, thus the “test” for the argument:

string jsonContent = "{" + "\"" + "arg" + "\"" + ":" + "\"" + "test" + "\"" + "}";
            string url = "https://api.particle.io/v1/devices/" + coreid + "function/?access_token=123";
            POST(url, jsonContent);

void POST(string url, string jsonContent)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            long length = 0;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                }
            }
            catch (WebException ex)
            {
                // Log exception and throw as for GET example above
            }
        }

You can look how it’s donw here
https://docs.particle.io/reference/discontinued/windows/#windows-cloud-sdk
and

1 Like

Thank you for your reply ScruffR. I was looking for a more general purpose solution. I ended up getting it to work with this using restsharp:

/*Needs to use the following additional libraries:
using RestSharp;
using RestSharp.Authenticators;
*/

private void button1_Click(object sender, EventArgs e)
{
      var client = new RestClient();
      client.BaseUrl = new Uri("https://api.particle.io/v1/devices/deviceID/functionName");

      var request = new RestRequest(Method.POST);
      request.AddParameter("arg","command");
      request.AddParameter("access_token","1234");

      IRestResponse response = client.Execute(request);

      MessageBox.Show(response.StatusDescription.ToString());
}
1 Like