internal IEnumerable <T> Get <T>(string[] path, int pos, bool attempt_conversion) { string key = path[pos]; int index; // The key is an index; otherwise ignore if (key[0] == '[' && key[key.Length - 1] == ']') { // The key refers to all items ("[*]") if (key.Length == 3 && key[1] == '*') { foreach (var item in _array) { foreach (var value in GSObject.Get <T>(path, pos, item, attempt_conversion)) { yield return(value); } } } // The key is a specific index (e.g. "[2]") and within the array bounds else if (int.TryParse(key.Substring(1, key.Length - 2), out index) && index < Length) { foreach (var value in GSObject.Get <T>(path, pos, _array[index], attempt_conversion)) { yield return(value); } } } }
private void ConstructFromJSONString(JSONObject jsonObj) { string key; object value; foreach (KeyValuePair <string, object> kvp in jsonObj) { key = kvp.Key; value = kvp.Value; if (value == null) { this.Put(key, value); // null values are allowed } else if (value is decimal) { this.Put(key, (double)(decimal)value); } else if (value.GetType().IsPrimitive || value is string) { this.Put(key, value); } else if (value is JSONObject) // value itself is a json object { // Create a new GSObject to put as the value of the current key. the source for this child is the current value GSObject child = new GSObject((JSONObject)value); this.Put(key, child); } else if (value is JSONArray) // value is an array { GSArray childArray = new GSArray((JSONArray)value); this.Put(key, childArray); } } }
/// <summary> /// Returns a deep clone of the current instance /// </summary> /// <returns></returns> public GSObject Clone() { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = null; System.IO.MemoryStream stream = null; GSObject ret = null; try { // Serialize object formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); stream = new System.IO.MemoryStream(); formater.Serialize(stream, this); // Deserialize it stream.Position = 0; ret = (GSObject)formater.Deserialize(stream); } catch (Exception) { if (stream != null) { stream.Close(); } } return(ret); }
/* * internal String GetErrorResponseText(int errorCode, String errorMessage) * { * return GSRequest.GetErrorResponseText(this.method, errorCode, errorMessage); * } * * internal String GetErrorResponseText(int errorCode) * { * return GetErrorResponseText(errorCode, null); * }*/ internal static String GetErrorResponseText(String method, GSObject clientParams, int errorCode, String errorMessage) { if (errorMessage == null || errorMessage.Length == 0) { errorMessage = GetErrorMessage(errorCode); } String format = "json"; if (clientParams != null) { format = clientParams.GetString("format", "json"); } if (format.Equals("json")) { return("{errorCode:" + errorCode + ",errorMessage:\"" + errorMessage + "\"}"); } else { StringBuilder sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.Append("<" + method + "Response xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:com:gigya:api http://socialize-api.gigya.com/schema\" xmlns=\"urn:com:gigya:api\">"); sb.Append("<errorCode>" + errorCode + "</errorCode>"); sb.Append("<errorMessage>" + errorMessage + "</errorMessager>"); sb.Append("</" + method + "Response>"); return(sb.ToString()); } }
public static string CalcAuthorizationBearer(string userKey, string privateKey) { const string algorithm = "RS256"; const string jwtName = "JWT"; const string hAlg = "SHA256"; var header = new GSObject(new { alg = algorithm, typ = jwtName, kid = userKey }); var epochTime = new DateTime(1970, 1, 1); var issued = (long)DateTime.UtcNow.Subtract(epochTime).TotalSeconds; var payload = new GSObject(new { iat = issued, jti = Guid.NewGuid().ToString() }); var headerBytes = Encoding.UTF8.GetBytes(header.ToJsonString()); var payloadBytes = Encoding.UTF8.GetBytes(payload.ToJsonString()); var baseString = string.Join(".", new[] { Convert.ToBase64String(headerBytes), Convert.ToBase64String(payloadBytes) }); using (var rsa = RsaUtils.DecodeRsaPrivateKey(privateKey)) { var signature = rsa.SignData(Encoding.UTF8.GetBytes(baseString), hAlg); var signatureString = Convert.ToBase64String(signature); return("Bearer " + string.Join(".", new[] { baseString, signatureString })); } }
/// <summary> /// Returns the value to which the specified key inside the response params is associated with, or defaultValue /// if the response params does not contain such a key. /// </summary> /// <param name="key">the key whose associated value is to be returned. /// The key can specify a dot-delimited path down the objects hierarchy, with brackets to access array items. /// For example, "users[0].identities[0].provider" (see socialize.exportUsers API).</param> /// <param name="defaultValue">the value to be returned if the request params doesn't contain the specified key.</param> /// <returns>the value to which the specified key is mapped, or the defaultValue if the request params /// does not contain such a key</returns> public GSObject GetObject(string key, GSObject defaultValue) { if (data == null) { throw new GSResponseNotInitializedException(); } return(this.data.GetObject(key, defaultValue)); }
/// <summary> /// Associates the specified value with the specified key in this dictionary. /// If the dictionary previously contained a mapping for the key, the old value is replaced by the specified value. /// </summary> /// <param name="key">key with which the specified value is to be associated</param> /// <param name="value">a GSObject value to be associated with the specified key </param> public GSObject Put(string key, GSObject value) { if (key != null) { this._map[key] = value; } return(this); }
/// <summary> /// Returns the GSObject value to which the specified key is mapped, or the defaultValue /// if this dictionary contains no mapping for the key. /// </summary> /// <param name="key">the key whose associated value is to be returned</param> /// <param name="defaultValue">the GSObject value to be returned if this dictionary doesn't contain the specified key.</param> /// <returns>the GSObject value to which the specified key is mapped, or the defaultValue if this /// dictionary contains no mapping for the key</returns> public GSObject GetObject(string key, GSObject defaultValue) { GSObject retVal = defaultValue; try { retVal = this.GetTypedObject(key, defaultValue, true); } catch { } return(retVal); }
private void ReflectObject(object clientParams) { Type clientParamsType = clientParams.GetType(); List <MemberInfo> members = GetTypeMembers(clientParamsType); foreach (MemberInfo member in members) { object value = GetMemberValue(clientParams, member); String memberName = member.Name; if (null == value) { this.Put(memberName, value); } else { Type type = value.GetType(); if (type.IsPrimitive || type == typeof(String)) { this.Put(memberName, value); } else if (value is IEnumerable) { IEnumerable enu = value as IEnumerable; GSArray gsArr = new GSArray(); foreach (object obj in enu) { if (null == obj) { gsArr.Add(null as Object); } else { Type arrItemType = obj.GetType(); if (arrItemType == typeof(String) || arrItemType.IsPrimitive) { gsArr.Add(obj); } else { GSObject gsObjArrItem = new GSObject(obj); gsArr.Add(gsObjArrItem); } } } this.Put(memberName, gsArr); } else if (type.IsClass) { value = new GSObject(value); this.Put(memberName, value); } } } }
/* GET GSOBJECT */ public T GetObject <T>(string key) where T : class, new() { GSObject obj = GetObject(key, null); if (null != obj) { return(obj.Cast <T>()); } return(default(T)); }
/// <summary> /// converts xml string to GSObject /// </summary> /// <param name="responseText">XML string </param> /// <returns>GSObject based on the XML string</returns> private GSObject XmlToJSON(string responseText) { GSObject dictionary = new GSObject(); try { XmlDocument document = new XmlDocument(); document.LoadXml(responseText); XmlToDictionaryEntry(document.DocumentElement, dictionary); } catch (Exception) { dictionary = null; } return(dictionary); }
/// <summary> /// Adds XML node as a dictionary entry /// </summary> /// <param name="node">the node to convert</param> /// <param name="dic">the GSObject to add the converted node to</param> private void XmlToDictionaryEntry(XmlElement node, GSObject dic) { // Build a sorted list of key-value pairs // where key is case-sensitive nodeName // value is an ArrayList of string or XmlElement // so that we know whether the nodeName is an array or not. SortedList childNodeNames = new SortedList(); // Add in all nodes foreach (XmlNode cnode in node.ChildNodes) { if (cnode is XmlText) { StoreChildNode(childNodeNames, "value", cnode.InnerText); } else if (cnode is XmlElement) { StoreChildNode(childNodeNames, cnode.Name, cnode); } } foreach (string childname in childNodeNames.Keys) { ArrayList alChild = (ArrayList)childNodeNames[childname]; if (alChild.Count == 1) { OutputNode(childname, alChild[0], dic, true); } else { GSArray arr = new GSArray(); dic.Put(node.Name, arr); for (int i = 0; i < alChild.Count; i++) { GSObject cDic = new GSObject(); OutputNode(null, alChild[i], cDic, false); arr[i] = cDic; } dic.Put(childname, arr); } } }
/// <summary> /// This is a utility method for generating a base string for calculating the OAuth1 cryptographic signature. /// </summary> /// <param name="httpMethod">"POST" or "GET"</param> /// <param name="url">the full url without params</param> /// <param name="requestParams">list of params in the form of a GSObject</param> /// <returns>the base string to act on for calculating the OAuth1 cryptographic signature</returns> public static string CalcOAuth1Basestring(string httpMethod, string url, GSObject requestParams) { // Normalize the URL per the OAuth requirements StringBuilder normalizedUrlSB = new StringBuilder(); Uri u = new Uri(url); normalizedUrlSB.Append(u.Scheme.ToLowerInvariant()); normalizedUrlSB.Append("://"); normalizedUrlSB.Append(u.Host.ToLowerInvariant()); if ((u.Scheme == "HTTP" && u.Port != 80) || (u.Scheme == "HTTPS" && u.Port != 443)) { normalizedUrlSB.Append(':'); normalizedUrlSB.Append(u.Port); } normalizedUrlSB.Append(u.LocalPath); // Create a sorted list of query parameters StringBuilder querystring = new StringBuilder(); foreach (string key in requestParams.GetKeys()) { if (requestParams.GetString(key) != null) { querystring.Append(key); querystring.Append("="); querystring.Append(GSRequest.UrlEncode(requestParams.GetString(key) ?? String.Empty)); querystring.Append("&"); } } if (querystring.Length > 0) { querystring.Length--; // remove the last ampersand } // Construct the base string from the HTTP method, the URL and the parameters string basestring = httpMethod.ToUpperInvariant() + "&" + GSRequest.UrlEncode(normalizedUrlSB.ToString()) + "&" + GSRequest.UrlEncode(querystring.ToString()); return(basestring); }
public GSResponse(String method, Dictionary <string, string> headers, string responseText, GSLogger logSoFar) { logger.Write(logSoFar); this.headers = headers; this.responseText = responseText.Trim(); if (responseText == null || responseText.Length == 0) { return; } else { logger.Write("response", responseText); } if (responseText.StartsWith("{")) // JSON format { try { this.data = new GSObject(responseText); this.errorCode = data.GetInt("errorCode", 0); this.errorMessage = data.GetString("errorMessage", null); } catch (Exception ex) { this.errorCode = 500; this.errorMessage = ex.Message; } } else { // using string search to avoid dependency on parser String errCodeStr = GetStringBetween(responseText, "<errorCode>", "</errorCode>"); if (errCodeStr != null) { this.errorCode = int.Parse(errCodeStr); this.errorMessage = GetStringBetween(responseText, "<errorMessage>", "</errorMessage>"); } //initializing the data with XML transformed to GSObject this.data = XmlToJSON(responseText); } }
/// <summary> /// /// </summary> /// <param name="childname"></param> /// <param name="alChild"></param> /// <param name="dictionary"></param> /// <param name="showNodeName"></param> private void OutputNode(string childname, object alChild, GSObject dictionary, bool showNodeName) { if (alChild == null) { if (showNodeName) { dictionary.Put(childname, String.Empty); } } else if (alChild is string) { if (showNodeName) { dictionary.Put(childname, alChild.ToString()); } } else { XmlToDictionaryEntry((XmlElement)alChild, dictionary); } }
internal GSArray(JSONArray jsonArray) { for (int i = 0; i < jsonArray.Count; i++) { object value = jsonArray[i]; if (value is JSONObject) { GSObject obj = new GSObject((JSONObject)value); _array.Add(obj); } else if (value is JSONArray) { GSArray arr = new GSArray((JSONArray)value); _array.Add(arr); } else { _array.Add(value); } } }
public GSResponse(String method, GSObject clientParams, int errorCode, String errorMessage, GSLogger logSoFar) : this(method, GetErrorResponseText(method, clientParams, errorCode, errorMessage ?? GetErrorMessage(errorCode)), logSoFar) { }
/// <summary> /// Returns the GSObject value to which the specified key is mapped. /// </summary> /// <param name="key">the key whose associated value is to be returned</param> /// <returns>the GSObject value to which the specified key is mapped.</returns> /// <exception cref="Gigya.Socialize.SDK.GSKeyNotFoundException">thrown if the key is not found</exception> /// <exception cref="System.InvalidCastException">thrown if the value cannot be cast to GSObject</exception> public GSObject GetObject(string key) { GSObject retVal = this.GetTypedObject <GSObject>(key, null, false); return(retVal); }
public void Add(GSObject val) { _array.Add(val); }
public GSSession(GSObject currDictionaryParams) : this(currDictionaryParams.GetString("access_token"), currDictionaryParams.GetString("access_token_secret"), currDictionaryParams.GetLong("expires_in")) { }
public T GetObject <T>(int index) where T : class, new() { GSObject obj = GetObject(index); return(obj.Cast <T>()); }