JSON Example

Parent Previous Next

This example happens to be from a C# console application and uses the RestSharp and the NewtonSoft JSON helper libraries.  There are literally hundreds of ways to write this in almost any language or operating system available.



// Let's take an image!  This code snippet is from Main or some other control location

// Take a 1x1 image for 15 sec with the shutter open


SgImage img = new SgImage() { BinningMode = 1, ExposureLength = 15, FrameType = "Light", Path = @"Z:\temp\myImage.fit" };

Guid imgReceipt;

if (!TakeImage(img, out imgReceipt))

   return;


Console.WriteLine("Camera image started!");

Console.WriteLine("Checking for image done with receipt " + imgReceipt);


string path = "NA";

// Check every second or so to see if the image is ready

while (!File.Exists(path))

{

   GetImagePath(imgReceipt, out path);

   System.Threading.Thread.Sleep(1000);

}


if (path == "abort")

   Console.WriteLine("Exposure aborted by user from SGPro...");

else

   Console.WriteLine("Image found at: " + path);



// The guts of TakeImage

private static bool TakeImage(SgImage img, out Guid receipt)

{

   RestSharp.IRestClient client = new RestClient();


   var request = new RestRequest(Method.POST);

   request.Resource = uriBase + "image";

   request.RequestFormat = DataFormat.Json;

   request.AddHeader("Accept", "application/json");

           

   request.AddBody(img);


   IRestResponse response = client.Execute(request);


   SgImageResponse good = JsonConvert.DeserializeObject<SgImageResponse>(response.Content);


   if (!good.Success)

   {

       Console.WriteLine(good.Message);

       receipt = Guid.Empty;

       return false;

   }


   receipt = good.Receipt;

   return true;

}


private static bool GetImagePath(Guid receipt, out string path)

{

   RestSharp.IRestClient client = new RestClient();


   var request = new RestRequest(Method.GET);

   request.Resource = uriBase + "imagepath/" + receipt;

   request.RequestFormat = DataFormat.Json;

   request.AddHeader("Accept", "application/json");


   IRestResponse response = client.Execute(request);

   SgGenericResponse good = JsonConvert.DeserializeObject<SgGenericResponse>(response.Content);


   if (!good.Success)

   {

       Console.WriteLine(good.Message);

       path = "NA";

       return false;

   }


   // When successful, Message will contain the path to the image (this might not be the same path you passed in)

   path = good.Message;

   return true;

}


// DTOs

public class SgGenericResponse

{

   public bool Success { get; set; }

   public string Message { get; set; }

}


public class SgImage

{

   public int BinningMode { get; set; }

   public int IsoMode { get; set; }

   public int ExposureLength { get; set; }

   public string Gain { get; set; }

   public string Speed { get; set; }

   public string FrameType { get; set; }

   public string Path { get; set; }

}