Пример #1
0
        // Gets an object at the given key, central to all JSON class functionality.
        // Only used internally. DO NOT make public. Use getJSON if you need to get sub-JSON.
        private object getObject(string key)
        {
            if (jsonDict == null)
            {
                return(null);
            }

            string[]       parts       = key.Split('.');
            JsonDictionary currentDict = jsonDict;

            for (int i = 0; i < parts.Length - 1; i++)
            {
                if (currentDict != null && currentDict.ContainsKey(parts[i]))
                {
                    currentDict = currentDict[parts[i]] as JsonDictionary;
                }
                else
                {
                    return(null);
                }
            }

            // We need to check currentDict for null before trying to use it, because
            // it's possible for a JSON object to be null even when there is a key.
            // This happens with an empty array in the JSON string like this:
            // "parameters": []

            if (currentDict != null && currentDict.ContainsKey(parts[parts.Length - 1]))
            {
                return(currentDict[parts[parts.Length - 1]]);
            }

            return(null);
        }
        private static async Task SaveUserFacebookDetails()
        {
            var client = new Facebook.FacebookClient(App.AccessToken);
            var result = await client.GetTaskAsync("fql", new
            {
                q = "SELECT uid, name, pic_square, contact_email FROM user WHERE uid = '" + App.FacebookId + "'"
            });

            var jsonCollection = new JsonDictionary(result.ToString().Replace("data:", ""));

            if (jsonCollection.ContainsKey("contact_email"))
            {
                App.UserPreferences.UserDetails.Email = jsonCollection["contact_email"];
            }
            if (jsonCollection.ContainsKey("name"))
            {
                App.UserPreferences.UserDetails.Name = jsonCollection["name"];
            }
            if (jsonCollection.ContainsKey("pic_square"))
            {
                App.UserPreferences.UserDetails.ProfilePicUrl = jsonCollection["pic_square"];
            }
            if (jsonCollection.ContainsKey("user_mobile_phone"))
            {
                App.UserPreferences.UserDetails.ContactNumber = jsonCollection["user_mobile_phone"];
            }
            if (jsonCollection.ContainsKey("uid"))
            {
                App.UserPreferences.UserDetails.FacebookId = jsonCollection["uid"];
            }

            SettingsUtility.UpdateUserSettings(App.UserPreferences);
        }
Пример #3
0
        /// <summary>
        /// Newtonsoft JSon parser fails to parse json containing a "$ref" and an adjacent
        /// object property. Google service discovery currently generates this in the "annotations"
        /// property.
        /// </summary>
        /// <param name="js"></param>
        /// <param name="depth"></param>
        internal static void RemoveAnnotations(JsonDictionary js, int depth)
        {
            if (js.ContainsKey("$ref") && js.ContainsKey("annotations") && depth >= 3)
            {
                js.Remove("annotations");
            }

            foreach (var jd in js.Values
                     .Where(o => o is JsonDictionary)
                     .Select(o => o as JsonDictionary))
            {
                RemoveAnnotations(jd, depth + 1);
            }
        }
Пример #4
0
        private static JsonDictionary <K, V> DictionaryUnion <K, V>(
            JsonDictionary <K, V> thisDict,
            JsonDictionary <K, V> thatDict,
            Func <V, V, object> valueUnionizer = null)
            where K : ICloneable where V : ICloneable
        {
            if (thatDict == null)
            {
                return(thisDict);
            }

            if (thisDict == null)
            {
                return((JsonDictionary <K, V>)thatDict.Clone());
            }

            foreach (KeyValuePair <K, V> item in thatDict)
            {
                if (!thisDict.ContainsKey(item.Key))
                {
                    thisDict.Add(item.Key, item.Value);
                    continue;
                }

                if (valueUnionizer != null)
                {
                    thisDict[item.Key] = (V)valueUnionizer(thisDict[item.Key], item.Value);
                }
            }

            return(thisDict);
        }
Пример #5
0
        /// <summary>
        /// Creates a new resource for the specified discovery version with the specified name and json dictionary.
        /// </summary>
        internal Resource(IServiceFactory factory, string name, JsonDictionary dictionary)
            : base(factory)
        {
            name.ThrowIfNull("name");
            dictionary.ThrowIfNull("dictionary");

            logger.Debug("Constructing Resource [{0}]", name);
            Name        = name;
            information = dictionary;
            if (information == null)
            {
                throw new ArgumentException("got no valid dictionary");
            }

            // Initialize subresources.
            if (information.ContainsKey("resources"))
            {
                var resourceJson = (JsonDictionary)information["resources"];
                resources = new Dictionary <string, IResource>();
                foreach (KeyValuePair <string, object> pair in resourceJson)
                {
                    // Create the subresource.
                    var subResource = (Resource)Factory.CreateResource(pair.Key, pair.Value as JsonDictionary);
                    subResource.Parent = this;
                    resources.Add(pair.Key, subResource);
                }
            }
        }
Пример #6
0
        private Dictionary <string, IDiscoveryParameter> FetchParameters()
        {
            if (information.ContainsKey(ServiceFactory.Parameters) == false)
            {
                return(new Dictionary <string, IDiscoveryParameter> {
                });
            }

            JsonDictionary js = information[ServiceFactory.Parameters] as JsonDictionary;

            if (js == null)
            {
                return(new Dictionary <string, IDiscoveryParameter> {
                });
            }

            var parameters = new Dictionary <string, IDiscoveryParameter>();

            foreach (KeyValuePair <string, object> kvp in js)
            {
                IDiscoveryParameter p = CreateParameter(kvp);
                parameters.Add(kvp.Key, p);
            }
            return(parameters);
        }
Пример #7
0
 public static T TryGet <T>(this JsonDictionary dict, string key, T defaultObj)
 {
     if (dict.ContainsKey(key))
     {
         return((T)dict[key]);
     }
     else
     {
         return(defaultObj);
     }
 }
Пример #8
0
        public void Remove(int count)
        {
            var keys    = RandomKeys().Take(count).ToArray();
            var removes = keys.Where((key, i) => i % 3 == 0).ToArray();

            foreach (var key in keys)
            {
                _dict.Add(key, _value);
            }
            foreach (var key in removes)
            {
                _dict.Remove(key);
            }
            var n = 0;

            foreach (var key in keys)
            {
                Assert.AreEqual(!removes.Contains(key), _dict.ContainsKey(key), n++.ToString());
            }
        }
Пример #9
0
        private JsonDictionary AssertNode(JsonDictionary dict, params string[] nodes)
        {
            JsonDictionary cur = dict;

            for (int i = 0; i < nodes.Length; i++)
            {
                Assert.That(cur.ContainsKey(nodes[i]));
                Assert.That(cur[nodes[i]], Is.TypeOf(typeof(JsonDictionary)));
                cur = cur[nodes[i]] as JsonDictionary;
            }
            return(cur);
        }
Пример #10
0
        public void TestJsonDictionaryKeyComparisonIsCaseInsensitive()
        {
            // Arrange
            var jsonDictionary = new JsonDictionary <int>
            {
                { "one", 1 }
            };

            // Act

            // ReSharper disable InconsistentNaming
            var oneKeyExists = jsonDictionary.ContainsKey("one");
            var OneKeyExists = jsonDictionary.ContainsKey("One");
            var ONEKeyExists = jsonDictionary.ContainsKey("ONE");

            var twoKeyExists = jsonDictionary.ContainsKey("two");
            var TwoKeyExists = jsonDictionary.ContainsKey("Two");
            var TWOKeyExists = jsonDictionary.ContainsKey("TWO");

            // ReSharper restore InconsistentNaming

            // Assert
            Assert.True(oneKeyExists);
            Assert.True(OneKeyExists);
            Assert.True(ONEKeyExists);

            Assert.False(twoKeyExists);
            Assert.False(TwoKeyExists);
            Assert.False(TWOKeyExists);
        }
Пример #11
0
        private Dictionary <string, IMethod> FetchMethods()
        {
            if (information.ContainsKey(ServiceFactory.Methods) == false)
            {
                return(new Dictionary <string, IMethod>(0)); // return empty, not null.
            }

            JsonDictionary js = information[ServiceFactory.Methods] as JsonDictionary;

            if (js == null)
            {
                return(new Dictionary <string, IMethod>(0)); // return empty, not null.
            }

            var methods = new Dictionary <string, IMethod>();

            foreach (KeyValuePair <string, object> kvp in js)
            {
                IMethod m = CreateMethod(kvp);
                methods.Add(kvp.Key, m);
            }
            return(methods);
        }
        public void ParseEmptyObjectTest()
        {
            string jsonAsText = "{}";
            object o          = JsonReader.Parse(jsonAsText);

            Assert.IsInstanceOf(typeof(JsonDictionary), o);
            JsonDictionary dict = o as JsonDictionary;

            Assert.AreEqual(0, dict.Count);

            jsonAsText = "{'simpleProp':1, 'emptyObject':{}}";
            o          = JsonReader.Parse(jsonAsText);
            Assert.IsInstanceOf(typeof(JsonDictionary), o);
            dict = o as JsonDictionary;
            Assert.AreEqual(2, dict.Count);
            Assert.AreEqual(1, dict["simpleProp"]);
            Assert.That(dict.ContainsKey("emptyObject"), "Parsed object did not contian emptyObject");
            JsonDictionary empty = dict["emptyObject"] as JsonDictionary;

            Assert.IsNotNull(empty);
            Assert.AreEqual(0, empty.Count);
        }
Пример #13
0
        private bool CurrentStockInformation(string collectionName, Func <string, bool> callback)
        {
            Console.WriteLine("{0} Collector Start : {1}", collectionName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            var file      = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "stocklist.json");
            var stockText = File.ReadAllText(file);
            var stockJson = JsonValue.Parse(stockText);
            var progress  = 1;

            foreach (var stock in stockJson)
            {
                try
                {
                    var result = new SetDataSourceReq();
                    result.rawdata      = new List <JsonDictionary>();
                    result.source       = collectionName;
                    result.category     = "종목코드";
                    result.collected_at = "날짜";

                    var code  = stock.Value["code"].ReadAs <string>();
                    var name  = stock.Value["name"].ReadAs <string>();
                    var type  = stock.Value["type"].ReadAs <string>();
                    var cnt   = stock.Value["cnt"].ReadAs <string>();
                    var state = stock.Value.ContainsKey("state") ? stock.Value["state"].ReadAs <bool>() : false;

                    var      nvParser = new nvParser(code);
                    string[] siseInfo;
                    var      date = this.config["CurrentStockInformation"]["date"].ReadAs <string>();
                    if (string.IsNullOrWhiteSpace(date))
                    {
                        siseInfo = nvParser.getSise(2);
                    }
                    else
                    {
                        siseInfo = nvParser.getSise(date, 2);
                    }

                    if (siseInfo.Length < 7)
                    {
                        continue;
                    }
                    var columnInfo = new string[] { "날짜", "종가", "전일비", "시가", "고가", "저가", "거래량", "전일비율" };

                    var sise     = new JsonDictionary();
                    var siseDate = DateTime.Parse(siseInfo[0]).AddHours(16);
                    var siseUnix = EnvironmentHelper.GetUnixTime(siseDate) / 1000;
                    sise.Add("종목코드", code);
                    sise.Add("종목명", name);
                    sise.Add("종목유형", type);
                    sise.Add("상장주식수", cnt);
                    sise.Add(columnInfo[0], siseUnix);
                    sise.Add(columnInfo[1], siseInfo[1]);
                    var sign = string.Empty;
                    if (1 + 7 < siseInfo.Length)
                    {
                        if (int.Parse(siseInfo[1]) < int.Parse(siseInfo[1 + 7]))
                        {
                            sign = "-";
                        }
                    }
                    sise.Add(columnInfo[2], sign + siseInfo[2]);
                    sise.Add(columnInfo[3], siseInfo[3]);
                    sise.Add(columnInfo[4], siseInfo[4]);
                    sise.Add(columnInfo[5], siseInfo[5]);
                    sise.Add(columnInfo[6], siseInfo[6]);

                    var diff      = double.Parse(sign + siseInfo[2]);
                    var prevPrice = siseInfo.Length > 8 ? int.Parse(siseInfo[1 + 7]) : int.Parse(siseInfo[1]);
                    if (prevPrice > 0)
                    {
                        sise.Add(columnInfo[7], diff / prevPrice * 100);
                    }
                    else
                    {
                        sise.Add(columnInfo[7], 0);
                    }

                    if (sise.ContainsKey("종가"))
                    {
                        Task.Factory.StartNew(() =>
                        {
                            var analysis_sise = StockAnalysis.Instance.AutoAnalysis("day", code, siseUnix, sise);
                            result.rawdata.Add(analysis_sise);
                            var setSourceQuery = MariaQueryBuilder.SetDataSource(result);
                            MariaDBConnector.Instance.SetQuery("DynamicQueryExecuter", setSourceQuery);
                        });
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Current Stock Collector Error");
                }
                EnvironmentHelper.ProgressBar(progress, stockJson.Count);
                progress++;
            }
            callback.DynamicInvoke("test");
            Console.WriteLine("{0} Collector End : {1}", collectionName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            return(true);
        }
        private static async Task SaveUserFacebookDetails()
        {
            var client = new Facebook.FacebookClient(App.AccessToken);
            var result = await client.GetTaskAsync("fql", new
            {
                q = "SELECT uid, name, pic_square, contact_email FROM user WHERE uid = '" + App.FacebookId + "'"
            });
            var jsonCollection = new JsonDictionary(result.ToString().Replace("data:", ""));

            if (jsonCollection.ContainsKey("contact_email"))
            {
                App.UserPreferences.UserDetails.Email = jsonCollection["contact_email"];
            }
            if (jsonCollection.ContainsKey("name"))
            {
                App.UserPreferences.UserDetails.Name = jsonCollection["name"];
            }
            if (jsonCollection.ContainsKey("pic_square"))
            {
                App.UserPreferences.UserDetails.ProfilePicUrl = jsonCollection["pic_square"];
            }
            if (jsonCollection.ContainsKey("user_mobile_phone"))
            {
                App.UserPreferences.UserDetails.ContactNumber = jsonCollection["user_mobile_phone"];
            }
            if (jsonCollection.ContainsKey("uid"))
            {
                App.UserPreferences.UserDetails.FacebookId = jsonCollection["uid"];
            }

            SettingsUtility.UpdateUserSettings(App.UserPreferences);
        }
Пример #15
0
        /// <summary>
        /// Creates a new resource for the specified discovery version with the specified name and json dictionary.
        /// </summary>
        internal BaseResource(DiscoveryVersion version, KeyValuePair<string, object> kvp)
        {
            kvp.ThrowIfNull("kvp");
            kvp.Key.ThrowIfNull("kvp");

            DiscoveryVersion = version;
            logger.Debug("Constructing Resource [{0}]", kvp.Key);
            Name = kvp.Key;
            information = kvp.Value as JsonDictionary;
            if (information == null)
            {
                throw new ArgumentException("got no valid dictionary");
            }

            // Initialize subresources.
            if (information.ContainsKey("resources"))
            {
                var resourceJson = (JsonDictionary)information["resources"];
                resources = new Dictionary<string, IResource>();
                foreach (KeyValuePair<string, object> pair in resourceJson)
                {
                    // Create the subresource.
                    var subResource = (BaseResource)CreateResource(pair);
                    subResource.Parent = this;
                    resources.Add(pair.Key, subResource);
                }
            }
        }
Пример #16
0
 public static bool VariableExists(string name) => _variableDictionary.ContainsKey(name);
Пример #17
0
        private static JsonDictionary ParseObject(TokenStream ts)
        {
            // to parse an object, you get the object name, and then parse the value
            JsonToken token = ts.GetNextToken();

            if (token.Type != JsonToken.TokenType.String && token.Type != JsonToken.TokenType.ObjectEnd)
            {
                throw new ArgumentException(
                    "Unable to parse object. Found object " + token +
                    " while looking for property name or object end.");
            }

            JsonDictionary dict = new JsonDictionary();
            if (token.Type != JsonToken.TokenType.ObjectEnd)
            {
                for (JsonToken cur = ts.GetNextToken(); cur != null; cur = ts.GetNextToken())
                {
                    switch (cur.Type)
                    {
                        case JsonToken.TokenType.ObjectEnd:
                            logger.Debug("Found object end");
                            return dict;
                        case JsonToken.TokenType.MemberSeperator:
                            token = ts.GetNextToken();
                            break;
                        case JsonToken.TokenType.NameSeperator:
                            object value = ParseExpression(null, ts);
                            if (dict.ContainsKey(token.Value))
                            {
                                throw new ArgumentException(
                                    "JsonObject contains duplicate definition for [" + token.Value + "]");
                            }
                            dict.Add(token.Value, value);
                            break;
                        default:
                            throw new ArgumentException(
                                "Found invalid Json was expecting } or , or : found " + cur);
                    }
                }
            }
            return dict;
        }
Пример #18
0
        /// <summary>
        /// Creates a new resource for the specified discovery version with the specified name and json dictionary.
        /// </summary>
        internal Resource(IServiceFactory factory, string name, JsonDictionary dictionary)
            : base(factory)
        {
            name.ThrowIfNull("name");
            dictionary.ThrowIfNull("dictionary");

            logger.Debug("Constructing Resource [{0}]", name);
            Name = name;
            information = dictionary;
            if (information == null)
            {
                throw new ArgumentException("got no valid dictionary");
            }

            // Initialize subresources.
            if (information.ContainsKey("resources"))
            {
                var resourceJson = (JsonDictionary)information["resources"];
                resources = new Dictionary<string, IResource>();
                foreach (KeyValuePair<string, object> pair in resourceJson)
                {
                    // Create the subresource.
                    var subResource = (Resource)Factory.CreateResource(pair.Key, pair.Value as JsonDictionary);
                    subResource.Parent = this;
                    resources.Add(pair.Key, subResource);
                }
            }
        }