How to call your particle.function from c#


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

To call your function from code, you have to post to the 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 = "" + 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;

                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                WebResponse response = request.GetResponse();
                lblResponse.Text = (((HttpWebResponse)response).StatusDescription);
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                lblResults.Text = responseFromServer;
                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:


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


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