How to call your particle.function from asp.net c#

I haven’t seen anybody telling how to do this, so I will.

To call your function from asp.net code, you have to post to the api.particle.io web server. Particle’s web server will call your particle’s function, assuming your particle is functioning. Enough of this blather, where is the code?

            string postData = "arg=" + tbMaxChamber.Text + "," + tbMinChamber.Text + "blablabla.";
            string url = "https://api.particle.io/v1/devices/" + DeviceID + "/Settings?access_token=" + AccessToken;

            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;


            try
            {
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();
                lblResponse.Text = (((HttpWebResponse)response).StatusDescription);
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                lblResults.Text = responseFromServer;
                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch
            {
                lblResponse.Text = "Your gizmo did not respond.";
            }



First, test your function thoroughly using the console. If it doesn’t work the way you expect there, fix that first.

So the first line of C# code assembles the string you want to send as an “arg.” That is, the string starts with “arg=.”

The second line assembles the url including the device id and the access token.

From there on the code is pretty boilerplate. You will get an exception if your gizmo is not online, or crashes processing the string (don’t ask me how I know).

If all goes according to plan, the lblResponse.Text gets set to “OK” and the lblResults.Text gets a string with some useful information:

{"id":"thedeviceid","last_app":","command":true,"return_value":0}

You will likely want to do something with this information besides show it to the user. I will too.

1 Like

Oh, yes. The “return_value” in the results is the int returned from your function.