Example #1
0
        public static async Task <CartoResponse> Post(List <Data> data)
        {
            CartoResponse response = new CartoResponse();

            if (data.Count == 0)
            {
                // Realistically should never reach this block.
                // Size check done before. Here for debugging purposes
                response.Error = "No data to send";
                return(response);
            }

            string url = Codec.BaseUrl;
            string sql = Codec.DataToSql(data);

            using (var client = new HttpClient())
            {
                var stringPayload = "{ \"q\": \"" + sql.Replace("\"", @"\""") + "\" }";

                var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");

                HttpResponseMessage httpResponse = null;

                try
                {
                    httpResponse = await client.PostAsync(url, content);
                }
                catch (Exception e)
                {
                    response.Error = e.Message;
                    return(response);
                }

                var responseString = await httpResponse.Content.ReadAsStringAsync();

                response = Codec.DecodePostResponse(responseString);
            }

            // For debugging purposes -> Get the row you just inserted
            //await GetById(response.InstertedRowIds[0]);

            return(response);
        }
        public static CartoResponse DecodePostResponse(string encoded)
        {
            CartoResponse response = new CartoResponse();

            if (encoded.Contains(InternalServerError))
            {
                response.Error = InternalServerError;
                return(response);
            }

            Variant json = Variant.FromString(encoded);

            Variant error = json.GetObjectElement("error");

            if (!error.String.Equals("null"))
            {
                response.Error = error.GetArrayElement(0).String;
                response.Hint  = json.GetObjectElement("hint").String;
                return(response);
            }

            Variant rows = json.GetObjectElement("rows");

            for (int i = 0; i < rows.ArraySize; i++)
            {
                Variant row = rows.GetArrayElement(i);
                int     id  = int.Parse(row.GetObjectElement(FunctionName).String);
                response.InstertedRowIds.Add(id);
            }

            response.TotalRows = int.Parse(json.GetObjectElement("total_rows").String);

            response.Message = "Great success! " + response.TotalRows + " row(s) uploaded";

            return(response);
        }