private dynamic Convert(string key, dynamic val) { if (key.Equals("id")) { ARMObjectCache._cache[val] = this; } if (val == null) { return(null); } if (val.GetType() == typeof(Newtonsoft.Json.Linq.JArray)) { val = ((Newtonsoft.Json.Linq.JArray)val).ToObject <List <dynamic> >(); } if (val.GetType() == typeof(Newtonsoft.Json.Linq.JObject)) { val = ((Newtonsoft.Json.Linq.JObject)val).ToObject <Dynamo>(); } if (Utils.CheckIfAnonymousType(val.GetType()) && !(val is IList <dynamic>)) { dynamic orig_val = val; val = new Dynamo(); var properties = orig_val.GetType().GetProperties(); foreach (var pi in properties) { ((Dynamo)val).Properties.Add(pi.Name, pi.GetValue(orig_val, null)); } } if (val is Dynamo) { if (((Dynamo)val).Properties.Keys.Contains("object")) { val = ARMObjectCache.GetOrCreate(val); } } if (val is IList <dynamic> ) { var lst = new List <dynamic>(); for (int i = 0; i < ((IList <dynamic>)val).Count; i++) { lst.Add(this.Convert("", ((IList <dynamic>)val)[i])); /*if (lst[i] == null) continue; * * if (lst[i].GetType().GetProperty("object") != null) * lst[i] = ARMObjectCache.GetOrCreate(lst[i]);*/ } val = lst; } return(val); }
public dynamic request(string method, string id = null, object parameters = null, object json = null) { var spec = this.Object.GetSpec(); var endpoint = spec.GetType().GetProperty("endpoint") != null ? spec.endpoint : "/" + spec.sobject + "s"; if (!string.IsNullOrEmpty(id)) { endpoint += "/" + id; } for (int i = 0; i < this._attrs.Count; i++) { this._filters.Add("fields[" + i.ToString() + "]", (string)this._attrs[i]); } if (this._filters.Count > 0 || parameters != null) { endpoint += "?"; } if (this._filters.Count > 0) { endpoint += Utils.ToQueryString(this._filters); if (parameters != null) { endpoint += "&"; } } if (parameters != null) { endpoint += Utils.ToQueryString(parameters); } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pl.api_url + endpoint); req.Method = method; string _auth = string.Concat(pl.api_key, ":"); string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth)); string _cred = string.Concat("Basic ", _enc); req.Headers.Add("Authorization", _cred); req.Accept = "application/json"; if (json != null) { string post_data = JsonConvert.SerializeObject( json, Formatting.None, jsonsettings); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(post_data); if (DEBUG) { Console.WriteLine("-------------------REQ-------------------"); Console.WriteLine(post_data); } req.ContentType = "application/json"; req.ContentLength = bytes.Length; var writer = req.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); } // else // req.ContentLength = 0; HttpWebResponse response = null; try { response = (HttpWebResponse)req.GetResponse(); } catch (WebException we) { response = we.Response as HttpWebResponse; if (response == null) { throw; } } string response_value = ""; using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); response_value = reader.ReadToEnd(); } response.Close(); if (DEBUG) { Console.WriteLine("-------------------RESP------------------"); Console.WriteLine(response_value); } var obj = JsonConvert.DeserializeObject <ARMObject <object> >(response_value); if (response.StatusCode == HttpStatusCode.OK) { if (!string.IsNullOrEmpty(id) || (method == "POST" && !obj["object"].Equals("list"))) { dynamic result = ARMObjectCache.GetOrCreate(obj); return(result); } else { var return_list = new List <dynamic>(); foreach (var i in (Newtonsoft.Json.Linq.JArray)obj["values"]) { var item = i.ToObject <ARMObject <object> >(); dynamic result = ARMObjectCache.GetOrCreate(item); return_list.Add(result); } return(return_list); } } else { Type type = Utils.GetErrorClass(obj, (int)response.StatusCode); if (type != null) { throw (PayloadError)Activator.CreateInstance(type, (string)obj["error_description"], obj); } throw new pl.UnknownResponse((string)obj["error_description"], obj); } }
public dynamic request(string method, string id = null, object parameters = null, object json = null) { var spec = this.Object.GetSpec(); var endpoint = spec.GetType().GetProperty("endpoint") != null ? spec.endpoint : "/" + spec.sobject + "s"; if (!string.IsNullOrEmpty(id)) { endpoint += "/" + id; } for (int i = 0; i < this._attrs.Count; i++) { this._filters.Add("fields[" + i.ToString() + "]", (string)this._attrs[i]); } if (this._filters.Count > 0 || parameters != null) { endpoint += "?"; } if (this._filters.Count > 0) { endpoint += Utils.ToQueryString(this._filters); if (parameters != null) { endpoint += "&"; } } if (parameters != null) { endpoint += Utils.ToQueryString(parameters); } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pl.api_url + endpoint); req.Method = method; string _auth = string.Concat(pl.api_key, ":"); string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth)); string _cred = string.Concat("Basic ", _enc); req.Headers.Add("Authorization", _cred); req.Accept = "application/json"; if (json != null) { var use_multipart = false; var data = Utils.JSONFlatten(json); foreach (var item in data) { if (item.Value is FileStream) { use_multipart = true; break; } } if (use_multipart) { string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); req.ContentType = "multipart/form-data; boundary=" + boundary; /// The first boundary byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); /// the last boundary. byte[] trailer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); /// the form data, properly formatted string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; /// the form-data file upload, properly formatted string fileheaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n"; int content_len = trailer.Length; foreach (string key in data.Keys) { content_len += boundarybytes.Length + 2; if (data[key] is FileStream) { var file = (FileStream)data[key]; string contentType = MimeTypeMap.GetMimeType(Path.GetExtension(file.Name)); content_len += string.Format(fileheaderTemplate, key, file.Name, contentType).Length; content_len += (int)file.Length; } else { content_len += string.Format(formdataTemplate, key, data[key]).Length; } } req.ContentLength = content_len; var writer = req.GetRequestStream(); foreach (string key in data.Keys) { WriteToStream(writer, boundarybytes); if (data[key] is FileStream) { var file = (FileStream)data[key]; string contentType = MimeTypeMap.GetMimeType(Path.GetExtension(file.Name)); WriteToStream(writer, string.Format(fileheaderTemplate, key, file.Name, contentType)); int CHUNK = 1024; int numBytesToRead = (int)file.Length; while (numBytesToRead > 0) { byte[] bytes = new byte[Math.Min(CHUNK, numBytesToRead)]; int n = file.Read(bytes, 0, bytes.Length); if (n == 0) { break; } numBytesToRead -= n; WriteToStream(writer, bytes); } } else if (data[key] is bool) { WriteToStream(writer, string.Format(formdataTemplate, key, ((bool)data[key])?"true":"false")); } else { WriteToStream(writer, string.Format(formdataTemplate, key, data[key])); } WriteToStream(writer, "\r\n"); } WriteToStream(writer, trailer); } else { string post_data = JsonConvert.SerializeObject( json, Formatting.None, jsonsettings); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(post_data); if (DEBUG) { Console.WriteLine("-------------------REQ-------------------"); Console.WriteLine(post_data); } req.ContentType = "application/json"; req.ContentLength = bytes.Length; var writer = req.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); } } // else // req.ContentLength = 0; HttpWebResponse response = null; try { response = (HttpWebResponse)req.GetResponse(); } catch (WebException we) { response = we.Response as HttpWebResponse; if (response == null) { throw; } } string response_value = ""; using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); response_value = reader.ReadToEnd(); } response.Close(); if (DEBUG) { Console.WriteLine("-------------------RESP------------------"); Console.WriteLine(response_value); } var obj = JsonConvert.DeserializeObject <ARMObject <object> >(response_value); if (response.StatusCode == HttpStatusCode.OK) { if (!string.IsNullOrEmpty(id) || (method == "POST" && !obj["object"].Equals("list"))) { dynamic result = ARMObjectCache.GetOrCreate(obj); return(result); } else { var return_list = new List <dynamic>(); foreach (var i in (Newtonsoft.Json.Linq.JArray)obj["values"]) { var item = i.ToObject <ARMObject <object> >(); dynamic result = ARMObjectCache.GetOrCreate(item); return_list.Add(result); } return(return_list); } } else { Type type = Utils.GetErrorClass(obj, (int)response.StatusCode); if (type != null) { throw (PayloadError)Activator.CreateInstance(type, (string)obj["error_description"], obj); } throw new pl.UnknownResponse((string)obj["error_description"], obj); } }