C# and the API

349 views
Skip to first unread message

Trent McDougall

unread,
Mar 28, 2016, 4:41:55 AM3/28/16
to astrometry
Hello,
I cannot login and obtain a session id from c#. I am instead returned the string;

 {"status":"error","errormessage":"no json"}

I believe that my problem is in the headers. I have tried many strings for the content type including; 

x-www-form-encoded
application/x-www-form-encoded
application/json


public static string Login()
        {
            
            string url ="http://nova.astrometry.net/api/login";
            string result = "";
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json.";

                result = client.UploadString(url, "POST", "%7B%22apikey%22%3A+%22lmxqdvfhopgfdpip%22%7D");
            }
            return result;
            
        }

I would be grateful for any help to get me over the line.

Kind Regards,

Trent 

Trent McDougall

unread,
Mar 28, 2016, 7:01:21 AM3/28/16
to astrometry

I have found the solution in an earlier post, here is the successful code;

public static string Login()
        {
            
            string url ="http://nova.astrometry.net/api/login";
            string result = "";
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                result = client.UploadString(url, "POST", "request-json=%7B%22apikey%22%3A+%22XXXX%22%7D");
            }
           
            return result;
            
        }

Trent McDougall

unread,
Apr 4, 2016, 3:19:40 AM4/4/16
to astrometry
Hi Guys,
I am now working on the next phase which is uploading a file. This is proving to be quite a challenge for me. I am using fiddler to monitor comms from a plate solving app. I would be open to hints/outright answers to get over the line,,, 

Trent

Dustin Lang

unread,
Apr 4, 2016, 10:44:36 AM4/4/16
to astrometry
Hi,

Yes, file upload is likely to be a challenge.

Please note that I added significantly to the API documentation on the web,
http://astrometry.net/doc/net/api.html#submitting-a-file

I have one major hint: the formatting is EXACTLY the same as it would be for a regular HTML form containing a text field called "request-json" with the JSON properties for the upload, plus a file upload field.

You may also want to have a look at the python client, even if you don't speak python, because you can probably get it to do the minimal requests required.

cheers,
--dustin


Kevin Sipprell

unread,
Apr 5, 2016, 11:51:48 AM4/5/16
to astrometry
Trent, 
I've just gone through this exercise...this is working for me...maybe it will help you....
please note:  I'm not a programmer just a hobbyist so there are likely some 'no-no's'  

 private async void PostFile(string session, string filename)
        {
            uploading = true;
            Log("Uploading Image");
            FileLog2("Uploading Image" + DateTime.Now);
            JsonObject obj = new JsonObject();
            JsonObject jsonObject = getUploadJson(session);
            String input = jsonObject.ToString();  // was &json-request...
            string baseAddress = "http://nova.astrometry.net/api/upload";
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromMinutes(3);
                using (var content = new MultipartFormDataContent("form-data"))
                {
                    try
                    {
                        //  var fileContent = new ByteArrayContent(File.ReadAllBytes(Path.GetFileName(MainWindow.solveImage)));
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(GlobalVariables.SolveImage));
                        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                        var stringContent = new StringContent(jsonObject.ToString());
                        stringContent.Headers.Add("Content-disposition", "form-data; name=\"request-json\"");
                        content.Add(stringContent, "text/plain");
                        string path2 = GlobalVariables.SolveImage; // for testing @"C:\Users\M81M82.fit";
                        FileStream fs = File.OpenRead(GlobalVariables.SolveImage);

                        var streamContent = new StreamContent(fs);
                        streamContent.Headers.Add("Content-type", "application/octet-strem");
                        streamContent.Headers.Add("Content-disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path2) + "\"");
                        content.Add(streamContent, "file", Path.GetFileName(path2));
                      
                        using (var response = await httpClient.PostAsync(baseAddress, content))
                        {

                            string responseData = await response.Content.ReadAsStringAsync();

                            var serializer = new JavaScriptSerializer();
                            var result2 = serializer.Deserialize<Dictionary<string, string>>(responseData);  //e.g. http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c
                            string sucess = result2["status"];
                            subid = result2["subid"];
                            string hash = result2["hash"];
                            Log("Upload Complete - submission id:   " + subid);
                            FileLog2("Upload Complete - submission id:   " + subid);

                        }
                    }
 catch (Exception e)
                    {
          
                              FileLog("Upload File error:   " + e.ToString());
                    }


                }
            }

        }

Regards, 
Kevin

Kevin Sipprell

unread,
Apr 5, 2016, 11:52:22 AM4/5/16
to astrometry
Very helpful...Thank you!!!
Kevin

Trent McDougall

unread,
Apr 8, 2016, 10:05:59 PM4/8/16
to astrometry
Thank you Kevin!

I am confused by this one line through;

  JsonObject jsonObject = getUploadJson(session);

Cheers,

Trent

Kevin Sipprell

unread,
Apr 8, 2016, 11:04:58 PM4/8/16
to astrometry
whoops...

 internal static JsonObject getUploadJson(string session)
        {
            JsonObject obj = new JsonObject();
            obj["publicly_visible"] = "y";
            obj["allow_modifications"] = "d";
            obj["session"] = session;
            obj["allow_commercial_use"] = "d";
            return obj;
        }

Kevin

Trent McDougall

unread,
Apr 8, 2016, 11:29:51 PM4/8/16
to astrometry

Thanks heaps!

Sándor Kóra

unread,
Jan 14, 2020, 4:07:46 AM1/14/20
to astrometry
I'm using the great c # githb app successfully. Connecting to astrometry server, successfully uploading image to process. I have enclosed a source code snippet for you.

 private void button1_Click(object sender, EventArgs e)
        {
            filepath = "";
            filename = "";
            string dbkonyvtar = AtnezetgridFomenu.Rows[AtnezetgridFomenu.CurrentCell.RowIndex].Cells[1].Value.ToString();
            filepath = filepath + dbkonyvtar + "\\";
            string dbfilename = AtnezetgridFomenu.Rows[AtnezetgridFomenu.CurrentCell.RowIndex].Cells[2].Value.ToString();
            filename = dbfilename;
            string file = filepath + filename;
            try
            {
                //var client = new Client(AstrometryAPIkey, "http://127.0.0.1:8080/api/login");
                //--- astrometry.net kliens apikulcs
                var client = new Client(AstrometryAPIkey);                
                var res = client.Login();

                //--- autentikáció sikeres
                if (res.status.ToString().Equals("success") )
                {
                    var aclientsessionId = res.session;
                    FitsListBoxHDUS.Items.Add("\n Login Apikey : " + AstrometryAPIkey);
                    FitsListBoxHDUS.Items.Add("\n Login message : " + res.message);
                    FitsListBoxHDUS.Items.Add("\n Login session : " + res.session);
                    FitsListBoxHDUS.Items.Add("\n Login error message : " + res.errormessage);
                    FitsListBoxHDUS.Items.Add("\nLogin status : " + res.status);
                }
                //--- autentikáció sikertelen
                else
                {
                    FitsListBoxHDUS.Items.Add("\n Login error message : " + res.errormessage);
                }

                CancellationTokenSource tokenSource = new CancellationTokenSource();
                CancellationToken token = tokenSource.Token;                

                //--- feltöltéskor értékelési paraméterek beállítása
                var uploadArguments = new UploadArgs { publicly_visible = Visibility.n };
                // allow_commercial_use
                // allow_modifications
                // center_dec
                // downsample_factor
                // publicly_visible
                // radius
                // scale_err
                // scale_est
                // scale_lower
                // scale_type
                // scale_units
                // scale_upper
                // session

                //--- file feltöltés válasza
                var uploadResponse = client.Upload(file, uploadArguments);
                //--- feltöltés státusz
                var auploadstatus = uploadResponse.status;

                //--- sikeres képfeltöltés 
                if (uploadResponse.status.Equals("success"))
                {                    
                    var auploadhash = uploadResponse.hash;
                    var auploadsubid = uploadResponse.subid;
                }
                //--- feltöltés sikertelen
                else
                {
                    FitsListBoxHDUS.Items.Add("\n Upload error message : " + uploadResponse.errormessage);
                }

                var jobStatusResponse = client.GetJobStatus(uploadResponse.subid, token);
                var jobstr = client.GetJobStatus(jobStatusResponse.Id.ToString(), tokenSource.Token);
                Task <SubmissionStatusResponse> submissionStatusResponse = client.GetSubmissionStatus(uploadResponse.subid, token);                
                var jobsubstr = client.GetSubmissionStatus(token.ToString(),token);
                var gc = client.GetCalibration(jobstr.Id.ToString());
                var cliberror = gc.error;
                var caldec = gc.dec;
                var calibra = gc.ra;
....

Hope this help...

2016. március 28., hétfő 10:41:55 UTC+2 időpontban Trent McDougall a következőt írta:
Helló,
Nem tudok bejelentkezni és beszerezni a munkamenet azonosítóját a c # -ről. Ehelyett visszaadtam a húrot;

 {"status": "error", " errormessage": "no json"}

Úgy gondolom, hogy a problémám a fejlécekben van. Próbáltam sok szöveget a tartalom típusához, beleértve; 

X-www-form-kódolt
alkalmazás / x-www-formátum-kódolás
application / json


nyilvános statikus karakterlánc Bejelentkezés ()
        {
            
            string url = " http://nova.astrometry.net/ api / login ";
            string eredmény = "";
            használata (var kliens = új WebClient ())
            {
                client.Headers [HttpRequestHeader.ContentType ] = "application / json.";

                eredmény = kliens.UploadString (URL, "POST", "% 7B% 22apikey% 22% 3A +% 22lmxqdvfhopgfdpip% 22% 7D");
            }
            visszatérési eredmény;
            
        }

Hálás lennék minden segítségért, amiért átvittél a vonalon.

Üdvözlettel,

Trent 
Reply all
Reply to author
Forward
0 new messages