Ejemplo n.º 1
2
        async private void loadJsonInfo() 
        {
            try
            {
                //--------- Having content from website--------------
                HttpClient http = new HttpClient();
                var response = await http.GetByteArrayAsync("http://emresevinc.github.io/exrepo.html");
                String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
                source = WebUtility.HtmlDecode(source);
                HtmlDocument resultat = new HtmlDocument();
                resultat.LoadHtml(source);

                List<HtmlNode> toftitle = resultat.DocumentNode.Descendants().Where
                    (x => (x.Name == "div" && x.Attributes["class"] != null &&
                    x.Attributes["class"].Value.Contains("container"))).ToList();
                String text = toftitle[0].InnerText;

                selectedMovie = new Movie();
                //----------------------------------------------------
                _jObject = JsonObject.Parse(text);  // Burada json dosyası parse ediliyor.
                jArr = _jObject.GetNamedArray("movies"); // Json verileri içindeki movies array'i
                fillToMovieList();
            }
            catch (Exception)
            {
               new MessageDialog("Bir hata gerceklesti").ShowAsync();
            }
        }
        public void PostToWall()
        {
            try
            {
                var actionLinks = new JsonArray();

                var learnMore = new JsonObject();
                learnMore.Add("text", "Learn more about Big Profile");
                learnMore.Add("href", "http://myapp.no/BigProfile");

                var appStore = new JsonObject();
                appStore.Add("text", "Visit App Store");
                appStore.Add("href", "http://myapp.no/BigProfileAppStore");

                //actionLinks.Add(learnMore);
                actionLinks.Add(appStore);

                var attachment = new JsonObject();
                attachment.Add("name", "Big Profile");
                attachment.Add("description", "Make your profile stand out with a big profile picture stretched across the new Facebook design. Available in App Store!");
                attachment.Add("href", "http://myapp.no/BigProfile");

                var parameters = new NSMutableDictionary();
                parameters.Add(new NSString("user_message_prompt"), new NSString("Tell your friends"));
                parameters.Add(new NSString("attachment"), new NSString(attachment.ToString()));
                parameters.Add(new NSString("action_links"), new NSString(actionLinks.ToString()));

                _facebook.Dialog("stream.publish", parameters, facebookDialogDelegate);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception when showing dialog: {0}", ex);
            }
        }
Ejemplo n.º 3
0
        public JsonValue GetAll()
        {
            JsonObject parameters = WebOperationContext.Current.IncomingRequest.GetQueryStringAsJsonObject();

            JsonValue term;
            string termValue = parameters.TryGetValue("term", out term) ? term.ReadAs<string>() : String.Empty;

            using (SqlConnection sc = new SqlConnection(connectionString))
            {
                sc.Open();
                using (SqlCommand getAll = new SqlCommand("SELECT Email FROM Contact WHERE (Email LIKE @term)", sc))
                {
                    getAll.Parameters.AddWithValue("@term", termValue + "%");
                    SqlDataReader reader = getAll.ExecuteReader();

                    JsonArray results = new JsonArray();
                    while (reader.Read())
                    {
                        results.Add(Convert.ToString(reader[0], CultureInfo.InvariantCulture));
                    }

                    return results;
                }
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            //var json = new JsonArray(
            //    new JsonObject(
            //        new JsonMember("A", new JsonNumber(1)),
            //        new JsonMember("B", new JsonNumber(2)),
            //        new JsonMember("C", new JsonArray(new JsonNumber(1), new JsonNumber(2)))),
            //    new JsonObject(
            //        new JsonMember("D", new JsonNumber(3)),
            //        new JsonMember("E", new JsonNumber(4))));

            var nested = new JsonObject(
                new JsonMember("A", new JsonNumber(3)),
                new JsonMember("A", new JsonNumber(3.01m)),
                new JsonMember("A", new JsonNumber(3)));

            var array = new JsonArray(nested, nested, nested);
            var array2 = new JsonArray(new JsonNumber(3), new JsonNumber(2), new JsonNumber(1));

            JsonValue json = new JsonObject(
                new JsonMember("A", new JsonString("\u0460\u849c\u8089")),
                new JsonMember("B", new JsonNumber(2)),
                new JsonMember("C",
                    new JsonObject(
                        new JsonMember("A", new JsonNumber(3)),
                        new JsonMember("A", new JsonNumber(3)),
                        new JsonMember("A", new JsonNumber(3)),
                        new JsonMember("ComplexArray", array),
                        new JsonMember("SimpleArray", array2))));

            Console.WriteLine(json.Stringify(true));

            json = Json.CreateAst(json.Stringify(true));
            Console.WriteLine(json.Stringify(true));
        }
Ejemplo n.º 5
0
        private static bool CompareJsonArrayTypes(JsonArray objA, JsonArray objB)
        {
            bool retValue = true;

            if (objA == null || objB == null || objA.Count != objB.Count || objA.IsReadOnly != objB.IsReadOnly)
            {
                return false;
            }

            try
            {
                for (int i = 0; i < objA.Count; i++)
                {
                    if (!Compare(objA[i], objB[i]))
                    {
                        Log.Info("JsonValueVerifier (JsonArrayType) Error: objA[{0}] = {1}", i, objA[i].ToString());
                        Log.Info("JsonValueVerifier (JsonArrayType) Error: objB[{0}] = {1}", i, objB[i].ToString());
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Info("JsonValueVerifier (JsonArrayType) Error: An Exception was thrown: " + e);
                return false;
            }

            return retValue;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 序列化JSONArray对象
        /// </summary>
        /// <param name="jsonArray"></param>
        /// <returns></returns>
        public static string SerializeArray(JsonArray jsonArray)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < jsonArray.Count; i++)
            {
                if (jsonArray[i] is JsonObject)
                {
                    sb.Append(string.Format("{0},", SerializeObject((JsonObject)jsonArray[i])));
                }
                else if (jsonArray[i] is JsonArray)
                {
                    sb.Append(string.Format("{0},", SerializeArray((JsonArray)jsonArray[i])));
                }
                else if (jsonArray[i] is String)
                {
                    sb.Append(string.Format("\"{0}\",", jsonArray[i]));
                }
                else
                {
                    sb.Append(string.Format("\"{0}\",", ""));
                }

            }
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of <see cref="JsonArrayBindingSource"/> with a source <see cref="JsonArray"/> and the type of <see cref="JsonValue"/> that is contained in the array.
        /// </summary>
        /// <param name="sourceArray">The source array containing values.</param>
        /// <param name="valueType">The type of <see cref="JsonValue"/> the <see cref="JsonArray"/> contains.</param>
        /// <remarks>
        /// If the source <see cref="JsonArray"/> is empty, use the constructor with the constructor <see cref="JsonArrayBindingSource.JsonArrayBindingSource(JsonArray, Type, IEnumerable{JsonObject.JsonObjectPropertyDescriptor})"/> to define the properties that should be available.
        /// </remarks>
        public JsonArrayBindingSource(JsonArray sourceArray, Type valueType)
        {
            _array = sourceArray;
            vtype = valueType;

            if (sourceArray.Count > 0)
                ReadProperties();
            else
            {

                if (valueType == typeof(JsonString) || valueType == typeof(JsonNumber) || valueType == typeof(JsonBoolean))
                {
                    PropertyDescriptorCollection c = TypeDescriptor.GetProperties(valueType);
                    PropertyDescriptor[] ca = new PropertyDescriptor[1];
                    foreach (PropertyDescriptor item in c)
                    {
                        if (item.Name == "Value")
                        {
                            ca[0] = item;
                            props = new PropertyDescriptorCollection(ca);
                            break;
                        }
                    }
                }
                else
                    props = TypeDescriptor.GetProperties(valueType);
            }
        }
        protected void LoadData()
        {
            if (isLoading)
                return;

            Task.Factory.StartNew (() => {

                isLoading = true;

                while (lastKnownLocation == null && !this.IsFinishing)
                    Thread.Sleep(2000);

                if (this.lastKnownLocation != null && !this.IsFinishing)
                {
                    poiData = GeoUtils.GetPoiInformation(lastKnownLocation, 20);

                    var js = "World.loadPoisFromJsonData(" + poiData.ToString() + ");";

                    architectView.CallJavascript(js);
                }

                isLoading = false;

            }).ContinueWith (t => {

                isLoading = false;

                var ex = t.Exception;
                Log.Error(Constants.LOG_TAG, ex.ToString());

            }, TaskContinuationOptions.OnlyOnFaulted);
        }
Ejemplo n.º 9
0
    private void CreateJsonTest()
    {
        JsonArray weekDiet = new JsonArray();
        for(int i=0;i<7;i++)
        {
            JsonObject diet = new JsonObject();
            diet["DayNumber"] = i;
            diet["Breakfast"] = "Banana"+ i;
            diet["Lunch"] = "Banana"+ i;
            diet["Dinner"] = "Banana"+ i;
            diet["WithSugar"] = (i % 2 == 0);
            diet["RandomNumber"] = Random.Range(0f,1.5f);

            weekDiet.Add(diet);
        }

        for (int i=0;i<7;i++)
        {
            if (i % 2 == 1)
            {
                weekDiet[i]["RandomNumber"] = 3;
                weekDiet[i]["RandomNumber"] = weekDiet[i]["RandomNumber"] * 2f;
            }
        }

        Debug.Log("Test InputOutputFileTest done: \n"+ weekDiet.ToJsonPrettyPrintString());
    }
Ejemplo n.º 10
0
	// Use this for initialization
	void Start ()
    {
        // json对象构造示例
        JsonObject root = new JsonObject();                                              
        root["age"] = 25;
        root["name"] = "rare";
        JsonObject obj = new JsonObject();
        root["person"] = obj;
        obj["age"] = 1;
        obj["name"] = "even";
        JsonArray arr = new JsonArray();
        arr[0] = "ComputerGrphic";
        arr[1] = "Unity3D";
        arr[2] = "Graphic";
        root["books"] = arr;

        // json取值
        int a = root["age"];
        Debug.Log("age:"+a.ToString());
        string v = root["name"];
        Debug.Log("name:" + v);

        // save json and format
        string strSerializeFile = Application.dataPath + "json/home.json";
        RareJson.Serialize(root, strSerializeFile, true);

        // json解析
        string strJsonName = Application.dataPath + "json/Contents.json";
        JsonNode node = RareJson.ParseJsonFile(strJsonName);

        // json not format
        strSerializeFile = Application.dataPath + "json/serialize.json";
        RareJson.Serialize(node, strSerializeFile, false);
	}
        public static JsonObject ToJson(Dominion.GameDescription gameDescription, int starRating)
        {
            JsonObject root = new Windows.Data.Json.JsonObject();

            root.Add(jsonNameDeck, ToJson(gameDescription));

            JsonArray expansionArray = new JsonArray();
            Dominion.Expansion[] presentExpansions;
            Dominion.Expansion[] missingExpansions;
            gameDescription.GetRequiredExpansions(out presentExpansions, out missingExpansions);

            foreach (var expansion in presentExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(true));
                expansionArray.Add(expansionObject);
            }

            foreach (var expansion in missingExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(false));
                expansionArray.Add(expansionObject);
            }

            root.Add(jsonNameRequiredExpansions, expansionArray);

            root.Add(jsonNameRating, JsonValue.CreateNumberValue(starRating));

            return root;
        }
Ejemplo n.º 12
0
        public string Stringify()
        {
            JsonArray jsonArray = new JsonArray();
            foreach (School school in Education)
            {
                jsonArray.Add(school.ToJsonObject());
            }

            JsonObject jsonObject = new JsonObject();
            jsonObject[idKey] = JsonValue.CreateStringValue(Id);

            // Treating a blank string as null
            if (String.IsNullOrEmpty(Phone))
            {
                jsonObject[phoneKey] = JsonValue.CreateNullValue();
            }
            else
            {
                jsonObject[phoneKey] = JsonValue.CreateStringValue(Phone);
            }

            jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
            jsonObject[educationKey] = jsonArray;
            jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
            jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);

            return jsonObject.Stringify();
        }
Ejemplo n.º 13
0
        private static void CreateFromScratch()
        {
            rootObject = new JsonObject();

            readList = new JsonArray();
            rootObject.Add(ReadListKey, readList);
        }
 public static TwitterCoordinates Parse(JsonArray array) {
     if (array == null) return null;
     return new TwitterCoordinates {
         Latitude = array.GetDouble(1),
         Longitude = array.GetDouble(0)
     };
 }
Ejemplo n.º 15
0
        private static IAsyncAction LoadAsync()
        {
            return AsyncInfo.Run(async (cancellationToken) =>
            {
                if (rootObject != null && readList != null)
                {
                    // File already loaded, there is nothing to do.
                    return;
                }

                string jsonString = await FilesManager.LoadAsync(storageFolder, FileName);

                if (!JsonObject.TryParse(jsonString, out rootObject))
                {
                    Debug.WriteLine("Invalid JSON object in {0}", FileName);
                    CreateFromScratch();
                    return;
                }

                if (!rootObject.ContainsKey(ReadListKey))
                {
                    CreateFromScratch();
                    return;
                }

                readList = rootObject.GetNamedArray(ReadListKey);
            });
        }
Ejemplo n.º 16
0
        public async Task<string> Search(string search)
        {
            using (AutoResetEvent handle = new AutoResetEvent(false))
            {
                JsonObject message = new JsonObject();
                message.Add("method", JsonValue.CreateStringValue("core.library.search"));

                JsonObject queryObject = new JsonObject();
                queryObject.Add("track_name", JsonValue.CreateStringValue(search));

                JsonArray urisArray = new JsonArray();
                urisArray.Add(JsonValue.CreateStringValue("spotify:"));

                JsonObject paramsObject = new JsonObject();
                paramsObject.Add("query", queryObject);
                paramsObject.Add("uris", urisArray);

                message.Add("params", paramsObject);

                string result = null;
                await Send(message, searchResult =>
                {
                    JsonArray tracks = searchResult.GetNamedArray("result")[0].GetObject().GetNamedArray("tracks");
                    result = tracks.First().GetObject().GetNamedString("uri");

                    handle.Set();
                });

                handle.WaitOne(TimeSpan.FromSeconds(30));
                return result;
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Visits a json array.
 /// </summary>
 /// <param name="jsonArray">The json array being visited.</param>
 public void Visit(JsonArray jsonArray)
 {
     ExceptionUtilities.CheckArgumentNotNull(jsonArray, "jsonArray");
     this.writer.StartArrayScope();
     jsonArray.Elements.ForEach(e => e.Accept(this));
     this.writer.EndScope();
 }
Ejemplo n.º 18
0
 public void GetCategoryInfo(HttpContext context)
 {
     Func<Maticsoft.Model.SNS.Categories, bool> predicate = null;
     string categoryId = context.Request.Params["CID"];
     int type = Globals.SafeInt(context.Request.Params["Type"], 0);
     JsonObject obj2 = new JsonObject();
     if (!string.IsNullOrWhiteSpace(categoryId))
     {
         if (predicate == null)
         {
             predicate = c => c.ParentID == Globals.SafeInt(categoryId, 0);
         }
         List<Maticsoft.Model.SNS.Categories> list2 = this.SNSCateBll.GetAllCateByCache(type).Where<Maticsoft.Model.SNS.Categories>(predicate).ToList<Maticsoft.Model.SNS.Categories>();
         if ((list2 != null) && (list2.Count > 0))
         {
             JsonArray data = new JsonArray();
             list2.ForEach(delegate (Maticsoft.Model.SNS.Categories info) {
                 data.Add(new JsonObject(new string[] { "CategoryId", "Name", "ParentID", "HasChildren" }, new object[] { info.CategoryId, info.Name, info.ParentID, info.HasChildren }));
             });
             obj2.Put("STATUS", "Success");
             obj2.Put("DATA", data);
         }
         else
         {
             obj2.Put("STATUS", "Fail");
         }
     }
     else
     {
         obj2.Put("STATUS", "Error");
     }
     context.Response.Write(obj2.ToString());
 }
Ejemplo n.º 19
0
 protected override IJsonToken LibraryResponse(Library library)
 {
     JsonArray artists = new JsonArray();
     foreach (Artist artist in library.GetArtists()) {
         artists.Add(artist.ToJson());
     }
     return artists;
 }
Ejemplo n.º 20
0
 static AnyInstance()
 {
     AnyJsonArray = new JsonArray { 1, 2, 3 };
     AnyJsonObject = new JsonObject { { "one", 1 }, { "two", 2 } };
     AnyJsonArray.Changing += new EventHandler<JsonValueChangeEventArgs>(PreventChanging);
     AnyJsonObject.Changing += new EventHandler<JsonValueChangeEventArgs>(PreventChanging);
     AnyJsonValue2 = AnyJsonArray;
 }
Ejemplo n.º 21
0
 JsonArray GetJson(IEnumerable<Song> songs)
 {
     JsonArray array = new JsonArray();
     foreach (Song song in songs) {
         array.Add(new JsonNumber(song.Id));
     }
     return array;
 }
Ejemplo n.º 22
0
        public void ArrayList()
        {
            var arrayList = new JsonArray {new JsonInteger(1), new JsonDouble(Math.PI), new JsonString("json")}.ToObject<ArrayList>();

            arrayList.Should().Not.Be.Null();

            arrayList.OfType<object>().Should().Have.SameSequenceAs(1, Math.PI, "json");
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Applies pending changes.
 /// </summary>
 public void Apply()
 {
     if (onApply != null) {
         JsonArray<TagGroupOperation> jsonArray = new JsonArray<TagGroupOperation>();
         jsonArray.values = operations.ToArray ();
         onApply (jsonArray.ToJson());
     }
 }
 public static TwitterCoordinates[] ParseMultiple(JsonArray array) {
     if (array == null) return new TwitterCoordinates[0];
     TwitterCoordinates[] temp = new TwitterCoordinates[array.Length];
     for (int i = 0; i < array.Length; i++) {
         temp[i] = Parse(array.GetArray(i));
     }
     return temp;
 }
Ejemplo n.º 25
0
 //把函数转换出来的Json串交给后台数据库服务
 public void Invoke(IAsyncObject obj, Func<JsonValue> method)
 {
     //传递到后台执行
     Uri uri = new Uri(Uri);
     WebClient client = new WebClient();
     client.UploadStringCompleted += (o, e) =>
     {
         obj.IsBusy = false;
         //通知数据提交过程完成
         if (e.Error != null)
         {
             obj.State = State.Error;
             obj.Error = e.Error.GetMessage();
         }
         else
         {
             //返回数据重新赋值给对象
             JsonObject resultJson =  (JsonObject)JsonValue.Parse(e.Result);
             if (resultJson.ContainsKey(obj.Name))
             {
                 (obj as IFromJson).FromJson((JsonObject)resultJson[obj.Name]);
             }
             //判定是否保存成功
             if (resultJson.ContainsKey("success")) 
             {
                 string success = resultJson["success"];
                 MessageBox.Show(success);
             }
             if (resultJson.ContainsKey("error"))
             {
                 obj.Error = resultJson["error"];
                 obj.State = State.Error;
                 obj.OnCompleted(e);
                 return;
             }
             else 
             {
                 obj.State = State.End;
             }
         }
         obj.OnCompleted(e);
     };
     JsonArray array = new JsonArray();
     JsonValue json = method();
     if (json is JsonObject)
     {
         //把执行批处理对象的名字添加进去
         json["name"] = obj.Name;
         array.Add(json);
     }
     else
     {
         array = (JsonArray) json;
     }
     obj.IsBusy = true;
     obj.State = State.Start;
     client.UploadStringAsync(uri, array.ToString());
 }
Ejemplo n.º 26
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
            var selected = new List<object>(TileList.SelectedItems);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
            var file = await picker.PickSaveFileAsync();
            if (file != null) {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, "");
                
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    while (zip.Entries.Count > 0) {
                        zip.Entries[0].Delete();
                    }

                    using (var metaStream = zip.CreateEntry("tiles.json").Open())
                    using (var writer = new StreamWriter(metaStream)) {
                        var array = new JsonArray();

                        selected.ForEachWithIndex<SecondaryTile>((item, index) => {
                            var objet = new JsonObject();
                            objet.Add("Name", item.DisplayName);
                            objet.Add("Arguments", item.Arguments);
                            objet.Add("TileId", item.TileId);
                            objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
                            objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
                            objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
                            
                            array.Add(objet);

                            if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
                                var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
                                
                                zip.CreateEntryFromFile(path, item.TileId + "/normal");
                            }
                        });
                        writer.WriteLine(array.Stringify());
                        
                    }

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if(status == FileUpdateStatus.Complete) {
                        var folder = await file.GetParentAsync();
                        await new MessageDialog("Speichern erfolgreich").ShowAsync();
                    } else {
                        await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
                    }

                    Debug.WriteLine(status);
                }
            }
        }
Ejemplo n.º 27
0
        void JsonObjectVisitor.Visit(JsonArray array)
        {
            writer.BeginSequence();

            foreach (JsonObject item in array)
                ReadValue(item);

            writer.EndSequence();
        }
 public static IEnumerable<TwitterHashTagEntitity> ParseMultiple(JsonArray entities) {
     List<TwitterHashTagEntitity> temp = new List<TwitterHashTagEntitity>();
     if (entities != null) {
         for (int i = 0; i < entities.Length; i++) {
             temp.Add(Parse(entities.GetObject(i)));
         }
     }
     return temp;
 }
 public static IEnumerable<TwitterMentionEntity> ParseMultiple(JsonArray mentions) {
     List<TwitterMentionEntity> temp = new List<TwitterMentionEntity>();
     if (mentions != null) {
         for (int i = 0; i < mentions.Length; i++) {
             temp.Add(Parse(mentions.GetObject(i)));
         }
     }
     return temp;
 }
Ejemplo n.º 30
0
 public JsonValue(JsonArray array)
 {
     Type  = JsonValueType.Array;
     Array = array;
 }
Ejemplo n.º 31
0
        //get schedules for a specidic day
        private async Task DoUpdateOn(string date, string hour, string minute, bool forcelimited = false)
        {
            buses = new List <IDictionary <string, string> >();
            error = false;
            string responseString;
            string napszak = forcelimited ? "3" : "0";

            using (var client = new HttpClient())               // query the server for the bus-line based on LineData
            {
                Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

                var content = new StringContent(
                    "{\"func\":\"getRoutes\",\"params\":{\"datum\":\"" + date +
                    "\",\"erk_stype\":\"megallo\",\"ext_settings\":\"block\",\"filtering\":0,\"helyi\":\"No\",\"honnan\":\"" + from +
                    "\",\"honnan_eovx\":\"0\",\"honnan_eovy\":\"0\",\"honnan_ls_id\":" + FromlsID + ",\"honnan_settlement_id\":\"" + FromsID +
                    "\",\"honnan_site_code\":0,\"honnan_zoom\":0,\"hour\":\"" + hour + "\",\"hova\":\"" + to +
                    "\",\"hova_eovx\":\"0\",\"hova_eovy\":\"0\",\"hova_ls_id\":" + TolsID + ",\"hova_settlement_id\":" + TosID +
                    ",\"hova_site_code\":0,\"hova_zoom\":0,\"ind_stype\":\"megallo\",\"keresztul_stype\":\"megallo\",\"maxatszallas\":\"" + (String)roamingSettings.Values["change"] +
                    "\",\"maxvar\":\"" + (String)roamingSettings.Values["wait"] + "\",\"maxwalk\":\"" + (String)roamingSettings.Values["walk"] +
                    "\",\"min\":\"" + minute + "\",\"napszak\":" + napszak +
                    ",\"naptipus\":0,\"odavissza\":0,\"preferencia\":\"1\",\"rendezes\":\"1\",\"submitted\":1,\"talalatok\":1,\"target\":0,\"utirany\":\"oda\",\"var\":\"0\"}}"
                    , System.Text.Encoding.UTF8, "application/json");

                var response = await client.PostAsync("http://menetrendek.hu/menetrend/interface/index.php", content);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new HttpRequestException();
                }
                responseString = await response.Content.ReadAsStringAsync();
            }

            string     raw  = Regex.Unescape(responseString);       // process recieved data
            JsonObject json = JsonObject.Parse(raw);

            string status = "";

            try { status = json.GetNamedString("status"); }
            catch (Exception) { status = "error"; }

            if (status == "success")
            {
                //try
                {
                    JsonObject results   = json.GetNamedObject("results");
                    JsonObject talalatok = results.GetNamedObject("talalatok");
                    int        t         = 1;
                    while (t > 0)
                    {
                        JsonObject talalat = null;
                        try { talalat = talalatok.GetNamedObject(t.ToString()); }
                        catch (Exception) { t = 0; break; }
                        Dictionary <string, string> jarat = new Dictionary <string, string>();
                        jarat.Add("indulasi_hely", talalat.GetObject().GetNamedString("indulasi_hely"));
                        jarat.Add("erkezesi_hely", talalat.GetObject().GetNamedString("erkezesi_hely"));
                        jarat.Add("indulasi_ido", talalat.GetObject().GetNamedString("indulasi_ido"));
                        jarat.Add("erkezesi_ido", talalat.GetObject().GetNamedString("erkezesi_ido"));
                        jarat.Add("osszido", talalat.GetObject().GetNamedString("osszido"));
                        jarat.Add("ossztav", talalat.GetObject().GetNamedString("ossztav"));
                        JsonObject jaratinfok = talalat.GetObject().GetNamedObject("jaratinfok");
                        JsonArray  nativedata = talalat.GetObject().GetNamedArray("nativeData");
                        int        fare_total = 0, fare50_total = 0, fare90_total = 0, extra_total = 0, j = 0;
                        string     fare = "", fare50 = "", fare90 = "", extra = "", num = "";
                        while (j > -1)
                        {
                            JsonObject jaratinfo = null;
                            try { jaratinfo = jaratinfok.GetObject().GetNamedObject(j.ToString()); }
                            catch (Exception)
                            {
                                if (j == 1)
                                {
                                    num = num.Substring(1) + num;
                                }
                                j = -1;
                                break;
                            }
                            fare   += "|" + jaratinfo.GetObject().GetNamedNumber("fare").ToString();
                            fare50 += "|" + jaratinfo.GetObject().GetNamedNumber("fare_50_percent").ToString();
                            fare90 += "|" + jaratinfo.GetObject().GetNamedNumber("fare_90_percent").ToString();
                            extra  += "|" + jaratinfo.GetObject().GetNamedNumber("additional_ticket_price").ToString();
                            if (j == 1)
                            {
                                num = " ∙∙∙" + num;
                            }
                            //num += "|" + jaratinfo.GetObject().GetNamedString("vonalnev").ToString();
                            string domain = nativedata[j].GetObject().GetNamedString("Domain_code").ToString();
                            num          += "|" + (domain.Length < 4 ? domain : "");
                            fare_total   += (int)jaratinfo.GetObject().GetNamedNumber("fare");
                            fare50_total += (int)jaratinfo.GetObject().GetNamedNumber("fare_50_percent");
                            fare90_total += (int)jaratinfo.GetObject().GetNamedNumber("fare_90_percent");
                            extra_total  += (int)jaratinfo.GetObject().GetNamedNumber("additional_ticket_price");
                            j++;
                        }
                        jarat.Add("fare", fare_total + fare);
                        jarat.Add("fare_50_percent", fare50_total + fare50);
                        jarat.Add("fare_90_percent", fare90_total + fare90);
                        jarat.Add("extra", extra_total + extra);
                        jarat.Add("vonalnev", num);
                        jarat.Add("details", talalat.GetObject().GetNamedObject("kifejtes_postjson").Stringify().Replace(Convert.ToChar(0x0).ToString(), ""));
                        Buses.Add(jarat);
                        t++;
                    }
                }
                //catch (Exception) { }
            }
            else
            {
                error = true;
            }
        }
Ejemplo n.º 32
0
        public static string Stringify <T>(T item)
        {
            if (item == null)
            {
                return(null);
            }

            Type type = typeof(T);

            if (type == typeof(IJsonType))
            {
                return(JsonHelper.Stringify((IJsonType)item));
            }
            else
            {
                if (item is IDictionary dict)
                {
                    JsonObject obj = new JsonObject();
                    foreach (DictionaryEntry entry in dict)
                    {
                        obj[entry.Key.ToString()] = entry.Value;
                    }
                    return(JsonHelper.Stringify(obj));
                }
                else if (item is IEnumerable en)
                {
                    JsonArray arr = new JsonArray();
                    foreach (object o in en)
                    {
                        arr.Add(o);
                    }
                    return(JsonHelper.Stringify(arr));
                }
                else if (item is JsonArray arr)
                {
                    return(JsonHelper.Stringify(arr));
                }
                else if (item is JsonObject j)
                {
                    return(JsonHelper.Stringify(j));
                }
                else
                {
                    JsonObject obj = new JsonObject();

                    IEnumerable <FieldInfo> fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
                                                     .Where(f => !f.IsDefined(typeof(CompilerGeneratedAttribute)));

                    foreach (FieldInfo field in fields)
                    {
                        obj[field.Name] = field.GetValue(item);
                    }

                    IEnumerable <PropertyInfo> props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
                                                       .Where(f => f.CanRead && f.CanWrite);

                    foreach (PropertyInfo prop in props)
                    {
                        obj[prop.Name] = prop.GetValue(item);
                    }

                    return(JsonHelper.Stringify(obj));
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Submit an order to Kraken. The order passed by reference will be updated with info set by Kraken.
        /// </summary>
        /// <param name="order">Order to submit.</param>
        /// <param name="wait">If set to true, the function will wait until the order is closed or canceled.</param>
        /// <returns>PlaceOrderResult containing info about eventual success or failure of the request</returns>
        private PlaceOrderResult PlaceOrder(ref KrakenOrder order, bool wait)
        {
            PlaceOrderResult placeOrderResult = new PlaceOrderResult();

            try
            {
                JsonObject res = _kraken.AddOrder(order);

                JsonArray error = (JsonArray)res["error"];
                if (error.Count() > 0)
                {
                    placeOrderResult.ResultType = PlaceOrderResultType.error;
                    List <string> errorList = new List <string>();
                    foreach (var item in error)
                    {
                        errorList.Add(item.ToString());
                    }
                    placeOrderResult.Errors = errorList;
                    return(placeOrderResult);
                }
                else
                {
                    JsonObject result = (JsonObject)res["result"];
                    JsonObject descr  = (JsonObject)result["descr"];
                    JsonArray  txid   = (JsonArray)result["txid"];

                    if (txid == null)
                    {
                        placeOrderResult.ResultType = PlaceOrderResultType.txid_null;
                        return(placeOrderResult);
                    }
                    else
                    {
                        string transactionIds = "";

                        foreach (var item in txid)
                        {
                            transactionIds += item.ToString() + ",";
                        }
                        transactionIds = transactionIds.TrimEnd(',');

                        order.TxId = transactionIds;

                        if (wait)
                        {
                            #region Repeatedly check order status by calling RefreshOrder

                            bool keepSpinning = true;
                            while (keepSpinning)
                            {
                                RefreshOrderResult refreshOrderResult = RefreshOrder(ref order);
                                switch (refreshOrderResult.ResultType)
                                {
                                case RefreshOrderResultType.success:
                                    switch (order.Status)
                                    {
                                    case "closed":
                                        placeOrderResult.ResultType = PlaceOrderResultType.success;
                                        return(placeOrderResult);

                                    case "pending":
                                        break;

                                    case "open":
                                        break;

                                    case "canceled":
                                        if (order.VolumeExecuted > 0)
                                        {
                                            placeOrderResult.ResultType = PlaceOrderResultType.partial;
                                            return(placeOrderResult);
                                        }
                                        else
                                        {
                                            placeOrderResult.ResultType =
                                                PlaceOrderResultType.canceled_not_partial;
                                            return(placeOrderResult);
                                        }

                                    default:
                                        throw new Exception(string.Format("Unknown type of order status: {0}",
                                                                          order.Status));
                                    }
                                    break;

                                case RefreshOrderResultType.error:
                                    throw new Exception(
                                              string.Format(
                                                  "An error occured while trying to refresh the order.\nError List: {0}",
                                                  refreshOrderResult.Errors.ToString()));

                                case RefreshOrderResultType.order_not_found:
                                    throw new Exception(
                                              "An error occured while trying to refresh the order.\nOrder not found");

                                case RefreshOrderResultType.exception:
                                    throw new Exception(
                                              "An unexpected exception occured while trying to refresh the order.",
                                              refreshOrderResult.Exception);

                                default:
                                    keepSpinning = false;
                                    break;
                                }
                                Thread.Sleep(5000);
                            }

                            #endregion
                        }

                        placeOrderResult.ResultType = PlaceOrderResultType.success;
                        return(placeOrderResult);
                    }
                }
            }
            catch (Exception ex)
            {
                placeOrderResult.ResultType = PlaceOrderResultType.exception;
                placeOrderResult.Exception  = ex;
                return(placeOrderResult);
            }
        }
Ejemplo n.º 34
0
        public ExtraData(JsonObject jsonObjectLotto, string spillnavn) : base(spillnavn)
        {
            var      a = jsonObjectLotto["drawDate"].GetString();
            DateTime trekningspunkt         = DateTime.ParseExact(a, "yyyy,MM,dd,HH,mm,ss", CultureInfo.CurrentCulture);
            string   trekningspunktAsString = trekningspunkt.ToString("dddd d. MMMM", CultureInfo.CurrentCulture);
            string   tmpPremieTall          = "";

            tmpPremieTall += int.Parse(jsonObjectLotto["prizeFirstBoard"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeFirstFrame"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeFirstImage"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeBoard"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeFrame"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeImage"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["prizeExtraCandidate"].GetString()).ToString("### ### ### kr") + "\r\n";
            tmpPremieTall += int.Parse(jsonObjectLotto["extraChancePrize"].GetString()).ToString("### ### ### kr");

            string tmpPremieNavn = Utils.isEnglish() ? "First board\r\n" : "Første brett\r\n";

            tmpPremieNavn += Utils.isEnglish() ? "First frame\r\n" : "Første ramme\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "First image\r\n" : "Første bilde\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "Board\r\n" : "Brett\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "Frame\r\n" : "Ramme\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "Image\r\n" : "Bilde\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "Extra candidate\r\n" : "Extrakandidaten\r\n";
            tmpPremieNavn += Utils.isEnglish() ? "Extra chance" : "Extrasjansen";

            JsonArray     winnerArray          = jsonObjectLotto["winnerList"].GetArray();
            StringBuilder ekstraSjansenVinnere = new StringBuilder();

            foreach (JsonValue andreValue in winnerArray)
            {
                JsonArray array2 = andreValue.GetArray();
                ekstraSjansenVinnere.Append(String.Format("{0} {1}, {2} {3}\r\n", ConvertToProperNameCase(array2[2].GetString().Replace("'", "")), ConvertToProperNameCase(array2[4].GetString().Replace("'", "")), array2[5].GetString().Replace("'", ""), array2[6].GetString().Replace("'", "")));
            }


            JsonArray     numberBuffer        = jsonObjectLotto["numberBuffer"].GetArray();
            StringBuilder numbers             = new StringBuilder();
            StringBuilder ekstraNumbers       = new StringBuilder();
            Boolean       leggTilEkstranummer = false;

            foreach (JsonValue value in numberBuffer)
            {
                if (value.ValueType == JsonValueType.Number)
                {
                    if (leggTilEkstranummer)
                    {
                        ekstraNumbers.Append(String.Format("{0}, ", value.GetNumber()));
                    }
                    else
                    {
                        numbers.Append(String.Format("{0,2}, ", value.GetNumber()));
                    }
                }
                else
                {
                    String bokstav       = value.GetString();
                    String valueToAppend = "";
                    if ("B".Equals(bokstav))
                    {
                        if (Utils.isEnglish())
                        {
                            valueToAppend = "First image";
                        }
                        else
                        {
                            valueToAppend = "Første bilde";
                        }
                    }
                    else if ("R".Equals(bokstav))
                    {
                        if (Utils.isEnglish())
                        {
                            valueToAppend = "First frame";
                        }
                        else
                        {
                            valueToAppend = "Første ramme";
                        }
                    }
                    else if ("F".Equals(bokstav))
                    {
                        if (Utils.isEnglish())
                        {
                            valueToAppend = "First board";
                        }
                        else
                        {
                            valueToAppend = "Første brett";
                        }
                    }
                    else if ("N".Equals(bokstav))
                    {
                        leggTilEkstranummer = true;
                        continue;
                    }
                    numbers.Append(String.Format("{0}, ", valueToAppend));
                }
            }

            this.Trekningsdato        = trekningspunktAsString;
            this.Premienavn           = tmpPremieNavn;
            this.Premietall           = tmpPremieTall;
            this.VinnereEkstrasjansen = ekstraSjansenVinnere.ToString();
            this.Vinnertall           = numbers.ToString().TrimEnd(new[] { ',', ' ' });
            this.Tilleggstall         = ekstraNumbers.ToString().TrimEnd(new[] { ',', ' ' });
        }
Ejemplo n.º 35
0
        void _EnsureFetchedImages()
        {
            var l = GetField <IList <object> >("images");

            if (null == l)
            {
                l = new JsonArray();
                var    json  = Tmdb.InvokeLang(string.Concat("/", string.Join("/", PathIdentity), "/images"));
                var    array = new JsonArray();
                object o;
                if (json.TryGetValue("backdrops", out o))
                {
                    var ll = o as IList <object>;
                    if (null != ll)
                    {
                        for (int ic = ll.Count, i = 0; i < ic; ++i)
                        {
                            var d = ll[i] as IDictionary <string, object>;
                            if (null != d)
                            {
                                d["image_type"] = "backdrop";
                                l.Add(d);
                            }
                        }
                    }
                }
                if (json.TryGetValue("posters", out o))
                {
                    var ll = o as IList <object>;
                    if (null != ll)
                    {
                        for (int ic = ll.Count, i = 0; i < ic; ++i)
                        {
                            var d = ll[i] as IDictionary <string, object>;
                            if (null != d)
                            {
                                d["image_type"] = "poster";
                                l.Add(d);
                            }
                        }
                    }
                }
                if (json.TryGetValue("profiles", out o))
                {
                    var ll = o as IList <object>;
                    if (null != ll)
                    {
                        for (int ic = ll.Count, i = 0; i < ic; ++i)
                        {
                            var d = ll[i] as IDictionary <string, object>;
                            if (null != d)
                            {
                                d["image_type"] = "profile";
                                l.Add(d);
                            }
                        }
                    }
                }
                Json.Add("images", l);
            }
        }
        private async Task loadDataAsync(string prefix)
        {
            lock (_lock)
            {
                if (this._navigationGroups.Count != 0)
                {
                    return;
                }
            }
            Uri    dataUri;
            string fileName;

            if (string.IsNullOrEmpty(prefix))
            {
                fileName = "NavigationData.json";
            }
            else
            {
                fileName = prefix + "NavigationData.json";
            }

            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                dataUri = new Uri("ms-appx:///Data/DesignTimeData/" + fileName);
            }
            else
            {
                dataUri = new Uri("ms-appx:///Data/DemoData/" + fileName);
            }

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

            string jsonText = await FileIO.ReadTextAsync(file);

            JsonObject jsonObject = JsonObject.Parse(jsonText);
            JsonArray  jsonArray  = jsonObject["Groups"].GetArray();

            lock (_lock)
            {
                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject      groupObject = groupValue.GetObject();
                    NavigationGroup group       = new NavigationGroup(groupObject["UniqueId"].GetString(),
                                                                      groupObject["Title"].GetString(),
                                                                      groupObject["Subtitle"].GetString(),
                                                                      groupObject["ImagePath"].GetString(),
                                                                      groupObject["Description"].GetString());


                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject = itemValue.GetObject();
                        var        item       = new NavigationItem(itemObject["UniqueId"].GetString(),
                                                                   itemObject["Title"].GetString(),
                                                                   itemObject["Subtitle"].GetString(),
                                                                   itemObject["ImagePath"].GetString(),
                                                                   itemObject["Description"].GetString(),
                                                                   itemObject["Content"].GetString(),
                                                                   itemObject["TargetUri"].GetString(),
                                                                   itemObject["TargetParamaters"].GetString()
                                                                   );
                        //if (itemObject.ContainsKey("Docs"))
                        //{
                        //    foreach (JsonValue docValue in itemObject["Docs"].GetArray())
                        //    {
                        //        JsonObject docObject = docValue.GetObject();
                        //        item.Docs.Add(new ControlInfoDocLink(docObject["Title"].GetString(), docObject["Uri"].GetString()));
                        //    }
                        //}
                        if (itemObject.ContainsKey("RelatedItems"))
                        {
                            foreach (JsonValue relateddItemValue in itemObject["RelatedItems"].GetArray())
                            {
                                item.RelatedItems.Add(relateddItemValue.GetString());
                            }
                        }
                        group.Items.Add(item);
                    }
                    if (!this.NavigationGroups.Any(g => g.Title == group.Title))
                    {
                        this.NavigationGroups.Add(group);
                    }
                }
            }
        }
Ejemplo n.º 37
0
        public static async Task GetSpotifyTrackInfoAsync(LocalSpotifyTrackInfo trackInfo)
        {
            string webResponse = string.Empty;

            try
            {
                HttpClient client = new HttpClient();

                string searchQuery = string.Format("artist:{0} track:{1}", trackInfo.artist, trackInfo.name);
                searchQuery = WebUtility.UrlEncode(searchQuery);

                string         spotifyUrl = string.Format("https://api.spotify.com/v1/search?q={0}&type=track&limit=2&offset=0", searchQuery);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(spotifyUrl);
                webRequest.Method      = "GET";
                webRequest.ContentType = "application/json";
                webRequest.Accept      = "application/json";
                webRequest.Headers.Add("Authorization: Bearer " + token.Access_token);

                HttpWebResponse resp = (HttpWebResponse)await webRequest.GetResponseAsync();

                string json = "";

                using (Stream respStr = resp.GetResponseStream())
                {
                    using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8))
                    {
                        // should get back a string we can turn into a json
                        json = await rdr.ReadToEndAsync();

                        rdr.Close();
                    }
                }

                IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(json);
                jsonObj.TryGetValue("tracks", out object trackObj);
                IDictionary <string, object> trackDict = (trackObj == null) ? null : (IDictionary <string, object>)trackObj;
                JsonArray items = null;
                if (trackDict != null)
                {
                    trackDict.TryGetValue("items", out object itemsObj);
                    items = (itemsObj == null) ? null : (JsonArray)itemsObj;
                }

                // need: id, name (already have it), artist (already have it), state, duration
                // type = "spotify"
                // other attributes to send: genre, start, end
                if (items != null && items.Count > 0)
                {
                    IDictionary <string, object> trackData = (IDictionary <string, object>)items[0];
                    trackData.TryGetValue("uri", out object spotifyIdObj);
                    string spotifyId = (spotifyIdObj == null) ? null : Convert.ToString(spotifyIdObj);
                    trackData.TryGetValue("duration_ms", out object durationMsObj);
                    long durationSec = (durationMsObj == null) ? 0L : Convert.ToInt64(durationMsObj);

                    trackInfo.duration = durationSec;
                    trackInfo.type     = "spotify";
                    trackInfo.state    = "playing";
                    trackInfo.genre    = "";
                    trackInfo.id       = spotifyId;
                    trackInfo.start    = SoftwareCoUtil.getNowInSeconds();
                    double offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes;
                    trackInfo.local_start = trackInfo.start + ((int)offset * 60);
                }
            }
            catch (Exception tex)
            {
                Logger.Error("error: " + tex.Message);
            }
        }
Ejemplo n.º 38
0
        public static void AddCsgoInventory(string inventoryString, string Steam64Id, string csgoInventoryId)
        {
            using (SqliteConnection db = new SqliteConnection(DbConnectionString))
            {
                JsonObject CsgoInventoryJsonObject = new JsonObject();
                try
                {
                    CsgoInventoryJsonObject = JsonObject.Parse(inventoryString);
                }
                catch (Exception)
                {
                    //CsgoInventoryJsonObject = JsonObject.Parse(inventoryString);
                    System.Diagnostics.Debug.Print("inventoryString ungültig");
                    return;
                }

                db.Open();

                List <Object> parameters = new List <Object>
                {
                    csgoInventoryId,
                    CsgoInventoryJsonObject.GetNamedBoolean("success"),
                    CsgoInventoryJsonObject.GetNamedBoolean("more"),
                    CsgoInventoryJsonObject.GetNamedBoolean("more_start"),
                    Steam64Id
                };

                InsertIntoTable(parameters, parameters.First(), "csgoInventory", db);


                JsonObject rgInventory = CsgoInventoryJsonObject.GetNamedObject("rgInventory");

                for (int i = 0; i < rgInventory.Count; i++)
                {
                    JsonObject element = rgInventory.GetNamedObject(rgInventory.ElementAt(i).Key);

                    parameters = new List <Object> {
                        element.GetNamedString("id"),
                        element.GetNamedString("classid"),
                        element.GetNamedString("instanceid"),
                        element.GetNamedString("amount"),
                        element.GetNamedNumber("pos"),
                        csgoInventoryId

                        //skin.PriceCol = new ObservableCollection<SteamItem.SteamPrice>();
                        //skin.PriceCol.Add(new SteamItem.SteamPrice());
                        //skin.BuyPrice = new SteamItem.PurchaseData();
                    };

                    InsertIntoTable(parameters, parameters.First(), "rgInventory", db);
                }

                JsonObject rgDescriptions = CsgoInventoryJsonObject.GetNamedObject("rgDescriptions");

                for (int n = 0; n < rgDescriptions.Count; n++)
                {
                    JsonObject rgDescription = rgDescriptions.GetNamedObject(rgDescriptions.ElementAt(n).Key);

                    parameters = new List <Object>
                    {
                        rgDescriptions.ElementAt(n).Key,
                        rgDescription.ContainsKey("appid") ? (Object)rgDescription.GetNamedString("appid") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("instanceid") ? (Object)rgDescription.GetNamedString("instanceid") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("icon_url") ? (Object)rgDescription.GetNamedString("icon_url") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("icon_url_large") ? (Object)rgDescription.GetNamedString("icon_url_large") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("icon_drag_url") ? (Object)rgDescription.GetNamedString("icon_drag_url") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("name") ? (Object)rgDescription.GetNamedString("name") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("market_hash_name") ? (Object)rgDescription.GetNamedString("market_hash_name") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("market_name") ? (Object)rgDescription.GetNamedString("market_name") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("name_color") ? (Object)rgDescription.GetNamedString("name_color") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("background_color") ? (Object)rgDescription.GetNamedString("background_color") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("type") ? (Object)rgDescription.GetNamedString("type") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("tradable") ? (Object)rgDescription.GetNamedNumber("tradable") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("marketable") ? (Object)rgDescription.GetNamedNumber("marketable") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("commodity") ? (Object)rgDescription.GetNamedNumber("commodity") : (Object)DBNull.Value,
                        rgDescription.ContainsKey("market_tradable_restriction") ? (Object)rgDescription.GetNamedString("market_tradable_restriction") : (Object)DBNull.Value,
                        csgoInventoryId
                    };

                    InsertIntoTable(parameters, parameters.First(), "rgDescription", db);


                    if (rgDescription.ContainsKey("descriptions"))
                    {
                        JsonArray descriptions = rgDescription.GetNamedArray("descriptions");

                        for (uint m = 0; m < descriptions.Count; m++)
                        {
                            JsonObject description = descriptions.GetObjectAt(m);

                            string descriptionValuesString = (description.ContainsKey("type") ? description.GetNamedString("type") : "") + (description.ContainsKey("value") ? description.GetNamedString("value") : "") + (description.ContainsKey("color") ? description.GetNamedString("color") : "");

                            parameters = new List <Object>
                            {
                                descriptionValuesString.GetHashCode(),
                                    description.ContainsKey("type") ? (Object)description.GetNamedString("type") : (Object)DBNull.Value,
                                description.ContainsKey("value") ? (Object)description.GetNamedString("value") : (Object)DBNull.Value,
                                description.ContainsKey("color") ? (Object)description.GetNamedString("color") : (Object)DBNull.Value,
                                rgDescriptions.ElementAt(n).Key
                            };

                            InsertIntoTable(parameters, parameters.First(), "descriptions", db);

                            if (description.ContainsKey("app_data"))
                            {
                                JsonObject appData = description.GetNamedObject("app_data");

                                string appDataValuesString = (appData.ContainsKey("def_index") ? appData.GetNamedString("def_index") : "") + (appData.ContainsKey("is_itemset_name") ? appData.GetNamedNumber("is_itemset_name").ToString() : "");

                                parameters = new List <Object>
                                {
                                    appDataValuesString.GetHashCode(),
                                        appData.ContainsKey("def_index") ? (Object)appData.GetNamedString("def_index") : (Object)DBNull.Value,
                                    appData.ContainsKey("is_itemset_name") ? (Object)appData.GetNamedNumber("is_itemset_name") : (Object)DBNull.Value,
                                    description.GetHashCode()
                                };

                                InsertIntoTable(parameters, parameters.First(), "app_data", db);
                            }
                        }
                    }

                    if (rgDescription.ContainsKey("actions"))
                    {
                        JsonArray actions = rgDescription.GetNamedArray("actions");
                        for (uint o = 0; o < actions.Count; o++)
                        {
                            JsonObject action = actions.GetObjectAt(o);

                            using (SqliteCommand actionsInsertCommand = new SqliteCommand("INSERT INTO actions VALUES (@id, @name, @link, @rgDescriptionID);", db))
                            {
                                actionsInsertCommand.Parameters.AddWithValue("@id", DBNull.Value);
                                if (action.ContainsKey("name"))
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@name", action.GetNamedString("name"));
                                }
                                else
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@name", DBNull.Value);
                                }
                                if (action.ContainsKey("link"))
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@link", action.GetNamedString("link"));
                                }
                                else
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@link", DBNull.Value);
                                }
                                actionsInsertCommand.Parameters.AddWithValue("@rgDescriptionID", rgDescriptions.ElementAt(n).Key);
                                actionsInsertCommand.ExecuteReader();
                            }
                        }
                    }

                    if (rgDescription.ContainsKey("market_actions"))
                    {
                        JsonArray marketActions = rgDescription.GetNamedArray("market_actions");
                        for (uint o = 0; o < marketActions.Count; o++)
                        {
                            JsonObject marketAction = marketActions.GetObjectAt(o);

                            using (SqliteCommand actionsInsertCommand = new SqliteCommand("INSERT INTO market_actions VALUES (@id, @name, @link, @rgDescriptionID);", db))
                            {
                                actionsInsertCommand.Parameters.AddWithValue("@id", DBNull.Value);
                                if (marketAction.ContainsKey("name"))
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@name", marketAction.GetNamedString("name"));
                                }
                                else
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@name", DBNull.Value);
                                }
                                if (marketAction.ContainsKey("link"))
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@link", marketAction.GetNamedString("link"));
                                }
                                else
                                {
                                    actionsInsertCommand.Parameters.AddWithValue("@link", DBNull.Value);
                                }
                                actionsInsertCommand.Parameters.AddWithValue("@rgDescriptionID", rgDescriptions.ElementAt(n).Key);
                                actionsInsertCommand.ExecuteReader();
                            }
                        }
                    }

                    if (rgDescription.ContainsKey("tags"))
                    {
                        JsonArray tags = rgDescription.GetNamedArray("tags");
                        for (uint p = 0; p < tags.Count; p++)
                        {
                            JsonObject tag = tags.GetObjectAt(p);

                            using (SqliteCommand tagsInsertCommand = new SqliteCommand("INSERT INTO tags VALUES (@id, @internal_name, @name, @category, @color, @category_name, @rgDescriptionID);", db))
                            {
                                tagsInsertCommand.Parameters.AddWithValue("@id", DBNull.Value);
                                if (tag.ContainsKey("internal_name"))
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@internal_name", tag.GetNamedString("internal_name"));
                                }
                                else
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@internal_name", DBNull.Value);
                                }
                                if (tag.ContainsKey("name"))
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@name", tag.GetNamedString("name"));
                                }
                                else
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@name", DBNull.Value);
                                }
                                if (tag.ContainsKey("category"))
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@category", tag.GetNamedString("category"));
                                }
                                else
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@category", DBNull.Value);
                                }
                                if (tag.ContainsKey("color"))
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@color", tag.GetNamedString("color"));
                                }
                                else
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@color", DBNull.Value);
                                }
                                if (tag.ContainsKey("category_name"))
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@category_name", tag.GetNamedString("category_name"));
                                }
                                else
                                {
                                    tagsInsertCommand.Parameters.AddWithValue("@category_name", DBNull.Value);
                                }
                                tagsInsertCommand.Parameters.AddWithValue("@rgDescriptionID", rgDescriptions.ElementAt(n).Key);
                                tagsInsertCommand.ExecuteReader();
                            }
                        }
                    }
                }
                JsonArray rgCurrency = CsgoInventoryJsonObject.GetNamedArray("rgCurrency");

                db.Close();
            }
        }
Ejemplo n.º 39
0
        private JsonArray SetSchema()
        {
            var fields = new JsonArray();

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "STATUS"),
                                      new KeyValuePair <string, JsonValue>("value", "status"),
                                      new KeyValuePair <string, JsonValue>("type", "Action")));

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "ANALYSIS NAME"),
                                      new KeyValuePair <string, JsonValue>("value", "name"),
                                      new KeyValuePair <string, JsonValue>("type", "Text"),
                                      new KeyValuePair <string, JsonValue>("group", 0),
                                      new KeyValuePair <string, JsonValue>("required", true)));

            var sourceQuery = MariaQueryDefine.GetSourceInformation;
            var sources     = MariaDBConnector.Instance.GetJsonArray("DynamicQueryExecuter", sourceQuery);
            var sourceArray = new JsonArray();

            if (sources != null)
            {
                foreach (var source in sources)
                {
                    var sourceName = source["TABLE_NAME"].ReadAs <string>().Replace("current_", "");
                    sourceArray.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", sourceName),
                                                   new KeyValuePair <string, JsonValue>("value", sourceName)));
                }
            }
            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "TARGET SOURCE"),
                                      new KeyValuePair <string, JsonValue>("value", "target_source"),
                                      new KeyValuePair <string, JsonValue>("type", "Select"),
                                      new KeyValuePair <string, JsonValue>("group", 1),
                                      new KeyValuePair <string, JsonValue>("required", true),
                                      new KeyValuePair <string, JsonValue>("options", sourceArray)));

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "ANALYSIS QUERY"),
                                      new KeyValuePair <string, JsonValue>("value", "analysis_query"),
                                      new KeyValuePair <string, JsonValue>("type", "Editor"),
                                      new KeyValuePair <string, JsonValue>("group", 2),
                                      new KeyValuePair <string, JsonValue>("required", true)));

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "ACTION TYPE"),
                                      new KeyValuePair <string, JsonValue>("value", "action_type"),
                                      new KeyValuePair <string, JsonValue>("type", "Select"),
                                      new KeyValuePair <string, JsonValue>("group", 3),
                                      new KeyValuePair <string, JsonValue>("required", true),
                                      new KeyValuePair <string, JsonValue>("dynamic", true),
                                      new KeyValuePair <string, JsonValue>("options", new JsonArray(
                                                                               new JsonObject(
                                                                                   new KeyValuePair <string, JsonValue>("text", "예약 실행"),
                                                                                   new KeyValuePair <string, JsonValue>("value", "schedule"),
                                                                                   new KeyValuePair <string, JsonValue>("fields", new JsonArray(
                                                                                                                            new JsonObject(new KeyValuePair <string, JsonValue>("text", "WEEKDAYS"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("value", "weekdays"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("type", "MultiSelect"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("group", 4),
                                                                                                                                           new KeyValuePair <string, JsonValue>("required", false),
                                                                                                                                           new KeyValuePair <string, JsonValue>("temp", true),
                                                                                                                                           new KeyValuePair <string, JsonValue>("datakey", "schedule"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("options", new JsonArray(
                                                                                                                                                                                    new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "월요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "MON")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "화요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "TUE")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "수요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "WED")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "목요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "THU")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "금요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "FRI")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "토요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "SAT")
                                                                                                                                                                                        ), new JsonObject(
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("text", "일요일"),
                                                                                                                                                                                        new KeyValuePair <string, JsonValue>("value", "SUN")
                                                                                                                                                                                        )))),
                                                                                                                            new JsonObject(new KeyValuePair <string, JsonValue>("text", "START"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("value", "start"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("type", "TimePicker"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("group", 5),
                                                                                                                                           new KeyValuePair <string, JsonValue>("datakey", "schedule"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("temp", true),
                                                                                                                                           new KeyValuePair <string, JsonValue>("required", false)),
                                                                                                                            new JsonObject(new KeyValuePair <string, JsonValue>("text", "END"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("value", "end"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("type", "TimePicker"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("group", 5),
                                                                                                                                           new KeyValuePair <string, JsonValue>("datakey", "schedule"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("temp", true),
                                                                                                                                           new KeyValuePair <string, JsonValue>("required", false)),
                                                                                                                            new JsonObject(new KeyValuePair <string, JsonValue>("text", "INTERVAL"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("value", "interval"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("type", "Number"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("group", 5),
                                                                                                                                           new KeyValuePair <string, JsonValue>("datakey", "schedule"),
                                                                                                                                           new KeyValuePair <string, JsonValue>("temp", true),
                                                                                                                                           new KeyValuePair <string, JsonValue>("required", false))
                                                                                                                            ))), new JsonObject(
                                                                                   new KeyValuePair <string, JsonValue>("text", "즉시 실행"),
                                                                                   new KeyValuePair <string, JsonValue>("value", "once"))))
                                      ));

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "UPDATED TIME"),
                                      new KeyValuePair <string, JsonValue>("value", "unixtime"),
                                      new KeyValuePair <string, JsonValue>("type", "Data")));

            fields.Add(new JsonObject(new KeyValuePair <string, JsonValue>("text", "OPTIONS"),
                                      new KeyValuePair <string, JsonValue>("value", "options"),
                                      new KeyValuePair <string, JsonValue>("type", "AddFields"),
                                      new KeyValuePair <string, JsonValue>("group", 6),
                                      new KeyValuePair <string, JsonValue>("required", true)));
            return(fields);
        }
Ejemplo n.º 40
0
        public void GetDataList()
        {
            _pageSize = UrlHelper.ReqIntByGetOrPost("pagesize", _pageSize);
            _total = UrlHelper.ReqLongByGetOrPost("total");
            _selectTypeName = UrlHelper.ReqStrByGetOrPost("selecttypename");
            _page = UrlHelper.ReqIntByGetOrPost("page");
            _minid = UrlHelper.ReqStrByGetOrPost("minid");
            _maxid = UrlHelper.ReqStrByGetOrPost("maxid");
            _descOrder = UrlHelper.ReqBoolByGetOrPost("descorder", true);

            bool IsGetTotal = UrlHelper.ReqBoolByGetOrPost("isgettotal", true);


            string[] fieldArr = new string[]{
                "[UserID]",
                "[LoginID]",
                "[RealName]",
                "[DepartmentID]",
                "[Mobile]",
                "[Email]",
                "[QQ]",
                "[IsEnabled]",
                "[IsLocked]",
                "[Remark]"
                };
            int pageSize = UrlHelper.ReqIntByGetOrPost("pageSize");
            int pageNumber = UrlHelper.ReqIntByGetOrPost("pageNumber");


            string condition = MakeConditionString<DBControl.DBInfo.Tables.Users>(HttpContext.Current, "s_");

            try
            {
                JsonObject jsonData = JsonResult(false, enumReturnTitle.GetData, "数据获取失败。");
                IDataReader idr = null;
                if (string.IsNullOrWhiteSpace(_selectTypeName))
                {
                    throw new Exception("请指定加载页面数据的类型,如首页selecttypename=firstpage等");
                }
                enumSelectType selectType = (enumSelectType)Enum.Parse(typeof(enumSelectType), _selectTypeName, true);

                switch (selectType)
                {
                    case enumSelectType.FirstPage:
                        idr = DBControl.Base.DBAccess.GetFirstPageDataIDR<DBControl.DBInfo.Tables.Users>(fieldArr.ToString(","), _descOrder, _pageSize, condition);
                        break;
                    case enumSelectType.LastPage:
                        idr = DBControl.Base.DBAccess.GetLastPageDataIDR<DBControl.DBInfo.Tables.Users>(fieldArr.ToString(","), _descOrder, _pageSize, condition);
                        break;
                    case enumSelectType.PrevPage:
                        idr = DBControl.Base.DBAccess.GetPrevPageDataIDR<DBControl.DBInfo.Tables.Users>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition);
                        break;
                    case enumSelectType.NextPage:
                        idr = DBControl.Base.DBAccess.GetNextPageDataIDR<DBControl.DBInfo.Tables.Users>(fieldArr.ToString(","), _descOrder, _pageSize, _minid, _maxid, condition);
                        break;
                    case enumSelectType.GoToPage:
                        idr = DBControl.Base.DBAccess.GetPageDataIDR<DBControl.DBInfo.Tables.Users>(fieldArr.ToString(","), _descOrder, _pageSize, _page, condition);
                        break;


                }

                JsonArray jArray = DataListToJson(idr, tableInfo.PKey, _descOrder, ref _minid, ref _maxid, fieldArr);

                if (jArray.Count > 0)
                {
                    jsonData = JsonResult(true,enumReturnTitle.GetData, "数据获取成功。");

                    jsonData.Add("rowsccount", jArray.Count);
                    if (IsGetTotal)
                    {
                        _total = DBControl.Base.DBAccess.Count<DBControl.DBInfo.Tables.Users>(condition);
                    }
                    jsonData.Add("total", _total);

                    jsonData.Add("minid", _minid);
                    jsonData.Add("maxid", _maxid);
                    jsonData.Add("rows", jArray);
                }
                else
                {
                    jsonData = JsonResult(false,enumReturnTitle.GetData, "没数据。");
                }

                JsonWriter jWriter = new JsonWriter();
                jsonData.Write(jWriter);
                CurrentContext.Response.Write(jWriter.ToString());
            }
            catch (Exception ex)
            {
                ReturnMsg(false, enumReturnTitle.GetData, string.Format("获取数据失败:{0}", ex.Message));
            }

        }
Ejemplo n.º 41
0
        public static int Main(string[] args)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | (SecurityProtocolType)3072;
            webClient.Headers.Add("User-Agent", "Unity web player");

            if (args.Length < 4)
            {
                Logger.LogError("Bad arguments for generator process; expected arguments: <unityVersion> <gameRoot> <gameData> <regenerate> <force_version_unhollower>");
                return(-1);
            }

            if ((args.Length >= 4) && !string.IsNullOrEmpty(args[3]) && args[3].Equals("true"))
            {
                Force_Regenerate = true;
            }

            if (args.Length >= 5)
            {
                try
                {
                    string Force_Version_Unhollower = args[4];
                    if (!string.IsNullOrEmpty(Force_Version_Unhollower))
                    {
                        if (!Force_Version_Unhollower.Equals("0.2.0.0") && !Force_Version_Unhollower.Equals("0.1.1.0") && !Force_Version_Unhollower.Equals("0.1.0.0"))
                        {
                            JsonArray data = (JsonArray)JsonValue.Parse(webClient.DownloadString("https://api.github.com/repos/knah/Il2CppAssemblyUnhollower/releases")).AsJsonArray;
                            if (data.Count > 0)
                            {
                                bool found_version = false;
                                foreach (var x in data)
                                {
                                    string version = x["tag_name"].AsString;
                                    if (!string.IsNullOrEmpty(version) && version.Equals("v" + Force_Version_Unhollower))
                                    {
                                        found_version = true;
                                        ExternalToolVersions.Il2CppAssemblyUnhollowerVersion = Force_Version_Unhollower;
                                        ExternalToolVersions.Il2CppAssemblyUnhollowerUrl     = "https://github.com/knah/Il2CppAssemblyUnhollower/releases/download/v" + Force_Version_Unhollower + "/Il2CppAssemblyUnhollower." + Force_Version_Unhollower + ".zip";
                                        break;
                                    }
                                }
                                if (!found_version)
                                {
                                    throw new Exception("Invalid Version Specified!");
                                }
                            }
                            else
                            {
                                throw new Exception("Unable to Verify Version!");
                            }
                        }
                        else
                        {
                            throw new Exception("Invalid Version! Only Supports v0.3.0.0 and up!");
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError("Failed to Force Unhollower Version, Defaulting to " + ExternalToolVersions.Il2CppAssemblyUnhollowerVersion + "  |  " + e.Message);
                }
            }

            try
            {
                int returnval = (AssemblyGenerator.Main.Initialize(args[0], args[1], args[2]) ? 0 : -2);
                TempFileCache.ClearCache();
                return(returnval);
            }
            catch (Exception ex)
            {
                TempFileCache.ClearCache();
                Logger.LogError("Failed to generate assemblies;");
                Logger.LogError(ex.ToString());

                return(-3);
            }
        }
Ejemplo n.º 42
0
    public static JsonArray StringToJsonArr(string str)
    {
        JsonArray player_obj = (JsonArray)SimpleJson.SimpleJson.DeserializeObject(str);

        return(player_obj);
    }
Ejemplo n.º 43
0
        public void ReadObject()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();

            const string json =
                @"{""string"":""foo"",""number"":12.12,""bool"":true,""null"":null,""array"":[1,2],""object"":{""id"":1}}";
            JsonObject actualObject = Helper.Read <JsonObject>(json, options);

            Assert.NotNull(actualObject);

            // pairs
            Assert.Equal(6, actualObject.GetPropertyNames().Count);

            // string
            JsonNode value = actualObject.GetPropertyValue("string");

            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.String, value.ValueKind);
            Assert.IsType <JsonString>(value);
            Assert.Equal("foo", ((JsonString)value).Value);

            // number
            value = actualObject.GetPropertyValue("number");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Number, value.ValueKind);
            Assert.IsType <JsonNumber>(value);
            Assert.Equal(12.12, ((JsonNumber)value).GetDouble(), 3);

            // bool
            value = actualObject.GetPropertyValue("bool");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.True, value.ValueKind);
            Assert.IsType <JsonBoolean>(value);
            Assert.True(((JsonBoolean)value).Value);

            // null
            value = actualObject.GetPropertyValue("null");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Null, value.ValueKind);
            Assert.IsType <JsonNull>(value);

            // array
            value = actualObject.GetPropertyValue("array");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Array, value.ValueKind);
            Assert.IsType <JsonArray>(value);
            JsonArray JsonArray = (JsonArray)value;

            Assert.Equal(2, JsonArray.Count);
            Assert.Equal(JsonValueKind.Number, JsonArray[0].ValueKind);
            Assert.Equal(1, ((JsonNumber)JsonArray[0]).GetDouble());
            Assert.Equal(JsonValueKind.Number, JsonArray[1].ValueKind);
            Assert.Equal(2, ((JsonNumber)JsonArray[1]).GetDouble());

            // object
            value = actualObject.GetPropertyValue("object");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Object, value.ValueKind);
            Assert.IsType <JsonObject>(value);
            JsonObject JsonObject = (JsonObject)value;

            value = JsonObject.GetPropertyValue("id");
            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Number, value.ValueKind);
            Assert.IsType <JsonNumber>(value);
            Assert.Equal(1, ((JsonNumber)value).GetInt32());
        }
Ejemplo n.º 44
0
        private void LoadFromJson(JsonObject obj)
        {
            // loop through the keys of this JsonObject to get invoice info, and parse it out
            foreach (string key in obj.Keys)
            {
                switch (key)
                {
                case IDKey:
                    m_id = obj.GetJSONContentAsInt(key);
                    break;

                case SubscriptionIdKey:
                    _subscriptionId = obj.GetJSONContentAsInt(key);
                    break;

                case StatementIdKey:
                    _statementId = obj.GetJSONContentAsInt(key);
                    break;

                case SiteIdKey:
                    _siteId = obj.GetJSONContentAsInt(key);
                    break;

                case StateKey:
                    _state = obj.GetJSONContentAsSubscriptionState(key);
                    break;

                case TotalAmountInCentsKey:
                    _totalAmountInCents = obj.GetJSONContentAsInt(key);
                    break;

                case PaidAtKey:
                    _paidAt = obj.GetJSONContentAsDateTime(key);
                    break;

                case CreatedAtKey:
                    _createdAt = obj.GetJSONContentAsDateTime(key);
                    break;

                case UpdatedAtKey:
                    _updatedAt = obj.GetJSONContentAsDateTime(key);
                    break;

                case AmountDueInCentsKey:
                    _amountDueInCents = obj.GetJSONContentAsInt(key);
                    break;

                case NumberKey:
                    _number = obj.GetJSONContentAsString(key);
                    break;

                case ChargesKey:
                    _charges = new List <ICharge>();
                    JsonArray chargesArray = obj[key] as JsonArray;
                    if (chargesArray != null)
                    {
                        foreach (var jsonValue in chargesArray.Items)
                        {
                            var charge = (JsonObject)jsonValue;
                            _charges.Add(charge.GetJSONContentAsCharge("charge"));
                        }
                    }
                    // Sanity check, should be equal.
                    if (chargesArray != null && chargesArray.Length != _charges.Count)
                    {
                        throw new JsonParseException(string.Format("Unable to parse charges ({0} != {1})", chargesArray.Length, _charges.Count));
                    }
                    break;

                case PaymentsAndCreditsKey:
                    break;
                }
            }
        }
Ejemplo n.º 45
0
        public void ReadArray()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();

            const string json        = @"[""foo"",12.12,true,null,[1,2],{""id"":1}]";
            JsonArray    actualArray = Helper.Read <JsonArray>(json, options);

            Assert.NotNull(actualArray);

            // values
            Assert.Equal(6, actualArray.Count);

            // string
            JsonNode actualString = actualArray[0];

            Assert.NotNull(actualString);
            Assert.Equal(JsonValueKind.String, actualString.ValueKind);
            Assert.IsType <JsonString>(actualString);
            Assert.Equal("foo", ((JsonString)actualString).Value);

            // number
            JsonNode actualNumber = actualArray[1];

            Assert.NotNull(actualNumber);
            Assert.Equal(JsonValueKind.Number, actualNumber.ValueKind);
            Assert.IsType <JsonNumber>(actualNumber);
            Assert.Equal(12.12, ((JsonNumber)actualNumber).GetDouble(), 3);

            // bool
            JsonNode actualBool = actualArray[2];

            Assert.NotNull(actualBool);
            Assert.Equal(JsonValueKind.True, actualBool.ValueKind);
            Assert.IsType <JsonBoolean>(actualBool);

            // null
            JsonNode actualNull = actualArray[3];

            Assert.NotNull(actualNull);
            Assert.Equal(JsonValueKind.Null, actualNull.ValueKind);

            // array
            JsonNode actualArrayValue = actualArray[4];

            Assert.NotNull(actualArrayValue);
            Assert.Equal(JsonValueKind.Array, actualArrayValue.ValueKind);
            Assert.IsType <JsonArray>(actualArrayValue);
            JsonArray JsonArray = (JsonArray)actualArrayValue;

            Assert.Equal(2, JsonArray.Count);
            Assert.Equal(JsonValueKind.Number, JsonArray[0].ValueKind);
            Assert.Equal(1, ((JsonNumber)JsonArray[0]).GetInt32());
            Assert.Equal(JsonValueKind.Number, JsonArray[1].ValueKind);
            Assert.Equal(2, ((JsonNumber)JsonArray[1]).GetInt32());

            // object
            JsonNode actualObject = actualArray[5];

            Assert.NotNull(actualObject);
            Assert.Equal(JsonValueKind.Object, actualObject.ValueKind);
            Assert.IsType <JsonObject>(actualObject);
            JsonObject JsonObject = (JsonObject)actualObject;
            JsonNode   value      = JsonObject.GetPropertyValue("id");

            Assert.NotNull(value);
            Assert.Equal(JsonValueKind.Number, value.ValueKind);
            Assert.IsType <JsonNumber>(value);
            Assert.Equal(1, ((JsonNumber)value).GetInt32());
        }
Ejemplo n.º 46
0
        private IJsonValue CreateJsonValue(JsonReader reader)
        {
            while (reader.TokenType == JsonToken.Comment)
            {
                if (!reader.Read())
                {
                    throw JsonSerializationException.Create(reader, "Unexpected end.");
                }
            }

            switch (reader.TokenType)
            {
            case JsonToken.StartObject:
            {
                return(CreateJsonObject(reader));
            }

            case JsonToken.StartArray:
            {
                JsonArray a = new JsonArray();

                while (reader.Read())
                {
                    switch (reader.TokenType)
                    {
                    case JsonToken.EndArray:
                        return(a);

                    default:
                        IJsonValue value = CreateJsonValue(reader);
                        a.Add(value);
                        break;
                    }
                }
            }
            break;

            case JsonToken.Integer:
            case JsonToken.Float:
                return(JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value)));

            case JsonToken.String:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Boolean:
                return(JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value)));

            case JsonToken.Null:
                // surely there is a better way to create a null value than this?
                return(JsonValue.Parse("null"));

            case JsonToken.Date:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            case JsonToken.Bytes:
                return(JsonValue.CreateStringValue(reader.Value.ToString()));

            default:
                throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            throw JsonSerializationException.Create(reader, "Unexpected end.");
        }
Ejemplo n.º 47
0
        public static JsonDocument Load(JsonReader reader)
        {
            var nodeStack = new Stack <JsonNode>();
            var doc       = new JsonDocument();

            nodeStack.Push(doc);

            var      propertyStack = new Stack <string>();
            JsonNode node          = null;

            while (reader.Read())
            {
                switch (reader.SyntaxKind)
                {
                case SyntaxKind.Comment:
                case SyntaxKind.None:
                    continue;

                case SyntaxKind.ArrayStart:
                    var arr = new JsonArray();
                    arr.Start = reader.Start;
                    nodeStack.Push(arr);
                    continue;

                case SyntaxKind.ObjectStart:
                    var obj = new JsonObject();
                    obj.Start = reader.Start;
                    nodeStack.Push(obj);
                    continue;

                case SyntaxKind.PropertyName:
                    propertyStack.Push(reader.PropertyName);

                    continue;

                case SyntaxKind.ArrayEnd:
                case SyntaxKind.ObjectEnd:
                    node     = nodeStack.Pop();
                    node.End = reader.End;
                    break;

                case SyntaxKind.StringValue:
                    node = new JsonString(reader.StringValue);
                    SetLocation(reader, node);
                    break;

                case SyntaxKind.DoubleValue:
                    node = new JsonNumber(reader.FloatValue);
                    SetLocation(reader, node);
                    break;

                case SyntaxKind.IntegerValue:
                    node = new JsonNumber(reader.IntegerValue);
                    SetLocation(reader, node);
                    break;

                case SyntaxKind.NullValue:
                    node = new JsonNull();
                    SetLocation(reader, node);
                    break;

                case SyntaxKind.TrueValue:
                    node = new JsonBoolean(true);
                    SetLocation(reader, node);
                    break;

                case SyntaxKind.FalseValue:
                    node = new JsonBoolean(false);
                    SetLocation(reader, node);
                    break;
                }

                var parent = nodeStack.Peek();

                if (parent is JsonArray a)
                {
                    a.Add(node);
                }
                else
                if (parent is JsonObject o)
                {
                    var propertyName = propertyStack.Pop();
                    o.Add(propertyName, node);
                }
                else
                if (parent is JsonDocument d)
                {
                    d.RootNode = node;
                    break;
                }
            }
            if (doc.RootNode != null)
            {
                doc.Start = doc.RootNode.Start;
                doc.End   = doc.RootNode.End;
            }

            return(doc);
        }
Ejemplo n.º 48
0
 internal Fee(JsonArray feeJson)
 {
     Volume = ((JsonNumber)feeJson[0]).ToInt32();
     Frais  = ((JsonNumber)feeJson[1]).ToDouble();
 }
Ejemplo n.º 49
0
        public async static Task <string> GetArrivalEstimates(string origin, string dest)
        {
            if (!IsThereInternet())
            {
                return("");
            }

            Tuple <string, string, IEnumerable <string> > idsAndCommonRotes = await GetCommonRoutesAndStopIds(origin, dest);

            string origin_id = idsAndCommonRotes.Item1;
            string dest_id   = idsAndCommonRotes.Item2;
            IEnumerable <string> common_routes = idsAndCommonRotes.Item3;

            // Download stops and get json response
            string url    = "http://api.transloc.com/1.1/arrival-estimates.json?agencies=" + agency + "&stops=" + origin_id;
            var    client = new System.Net.Http.HttpClient();
            HttpResponseMessage response = client.GetAsync(url).Result;
            string responseString        = await response.Content.ReadAsStringAsync();

            JsonObject obj = JsonObject.Parse(responseString);

            string    arrivalStr = "";
            JsonArray dataArr    = obj["data"].GetArray();

            if (dataArr.Count != 0)
            {
                var arrivals = dataArr[0].GetObject()["arrivals"].GetArray();
                foreach (JsonValue arrival in arrivals)
                {
                    var    arrival_obj = arrival.GetObject();
                    string route_id    = arrival_obj["route_id"].GetString();

                    // we have an arrival
                    if (common_routes.Contains(route_id))
                    {
                        arrivalStr = arrival_obj["arrival_at"].GetString().Split('T')[1].Split('-')[0];
                        break;
                    }
                }
            }

            if (arrivalStr != "")
            {
                string[] time       = arrivalStr.Split(':');
                int      departMin  = Convert.ToInt32(time[1]);
                int      departHour = Convert.ToInt32(time[0]);

                int minuteCountdown = departHour * 60 + departMin - (DateTime.Now.TimeOfDay.Hours * 60 + DateTime.Now.TimeOfDay.Minutes);
                if (minuteCountdown < 0)
                {
                    minuteCountdown = (24 * 60) + minuteCountdown;
                }
                arrivalStr = minuteCountdown.ToString();
            }

            // clean up
            obj = null;
            response.Dispose();
            response = null;
            client.Dispose();
            client            = null;
            common_routes     = null;
            idsAndCommonRotes = null;

            return(arrivalStr);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Call Kraken to update info about order execution.
        /// </summary>
        /// <param name="order">Order to update</param>
        /// <returns>RefreshOrderResult containing info about eventual success or failure of the request</returns>
        private RefreshOrderResult RefreshOrder(ref KrakenOrder order)
        {
            RefreshOrderResult refreshOrderResult = new RefreshOrderResult();

            try
            {
                JsonObject res = _kraken.QueryOrders(order.TxId);

                JsonArray error = (JsonArray)res["error"];
                if (error.Count() > 0)
                {
                    refreshOrderResult.ResultType = RefreshOrderResultType.error;
                    List <string> errorList = new List <string>();
                    foreach (var item in error)
                    {
                        errorList.Add(item.ToString());
                    }
                    refreshOrderResult.Errors = errorList;
                    return(refreshOrderResult);
                }
                else
                {
                    JsonObject result       = (JsonObject)res["result"];
                    JsonObject orderDetails = (JsonObject)result[order.TxId];

                    if (orderDetails == null)
                    {
                        refreshOrderResult.ResultType = RefreshOrderResultType.order_not_found;
                        return(refreshOrderResult);
                    }
                    else
                    {
                        string status    = (orderDetails["status"] != null) ? orderDetails["status"].ToString() : null;
                        string reason    = (orderDetails["reason"] != null) ? orderDetails["reason"].ToString() : null;
                        string openTime  = (orderDetails["opentm"] != null) ? orderDetails["opentm"].ToString() : null;
                        string closeTime = (orderDetails["closetm"] != null) ? orderDetails["closetm"].ToString() : null;
                        string vol_exec  = (orderDetails["vol_exec"] != null)
                            ? orderDetails["vol_exec"].ToString()
                            : null;
                        string    cost        = (orderDetails["cost"] != null) ? orderDetails["cost"].ToString() : null;
                        string    fee         = (orderDetails["fee"] != null) ? orderDetails["fee"].ToString() : null;
                        string    price       = (orderDetails["price"] != null) ? orderDetails["price"].ToString() : null;
                        string    misc        = (orderDetails["misc"] != null) ? orderDetails["misc"].ToString() : null;
                        string    oflags      = (orderDetails["oflags"] != null) ? orderDetails["oflags"].ToString() : null;
                        JsonArray tradesArray = (JsonArray)orderDetails["trades"];
                        string    trades      = null;
                        if (tradesArray != null)
                        {
                            foreach (var item in tradesArray)
                            {
                                trades += item.ToString() + ",";
                            }
                            trades = trades.TrimEnd(',');
                        }

                        order.Status         = status;
                        order.Reason         = reason;
                        order.OpenTime       = openTime;
                        order.CloseTime      = closeTime;
                        order.VolumeExecuted = double.Parse(vol_exec.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                        order.Cost           = decimal.Parse(cost.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                        order.Fee            = decimal.Parse(fee.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                        order.AveragePrice   = decimal.Parse(price.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                        order.Info           = misc;
                        order.OFlags         = oflags;
                        order.Trades         = trades;

                        refreshOrderResult.ResultType = RefreshOrderResultType.success;
                        return(refreshOrderResult);
                    }
                }
            }
            catch (Exception ex)
            {
                refreshOrderResult.ResultType = RefreshOrderResultType.exception;
                refreshOrderResult.Exception  = ex;
                return(refreshOrderResult);
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="dest"></param>
        /// <returns>Dictionary that maps route ids to a tuple of the route name, its color, and a list of segment collections</returns>
        public async static Task <Dictionary <string, Tuple <string, string, List <List <Point> > > > > GetRoutes(string origin, string dest)
        {
            bool checkForAllRoutes = (origin == "" && dest == "");

            Tuple <string, string, IEnumerable <string> > idsAndCommonRotes = (checkForAllRoutes) ? null : await GetCommonRoutesAndStopIds(origin, dest);

            IEnumerable <string> common_routes = (checkForAllRoutes) ? new List <string>() : idsAndCommonRotes.Item3;

            if (!IsThereInternet())
            {
                common_routes     = null;
                idsAndCommonRotes = null;
                return(null);
            }

            Dictionary <string, Tuple <string, string, List <List <Point> > > > routeMap = new Dictionary <string, Tuple <string, string, List <List <Point> > > >();
            // Download routes and get json response
            string url    = "http://api.transloc.com/1.1/routes.json?agencies=" + agency;
            var    client = new System.Net.Http.HttpClient();
            HttpResponseMessage response = client.GetAsync(url).Result;
            string responseString        = await response.Content.ReadAsStringAsync();

            JsonObject obj = JsonObject.Parse(responseString);

            // parse object
            JsonArray routeArr = obj["data"].GetObject()["52"].GetArray();

            if (routeArr.Count == 0)
            {
                return(routeMap);
            }

            JsonObject segmentMap = await GetSegments();

            //var routeArr = dataArr[0].GetObject()["52"].GetArray(); // does this fail when empty?
            foreach (JsonValue routeVal in routeArr)
            {
                var    route_obj = routeVal.GetObject();
                string route_id  = route_obj["route_id"].GetString();
                List <List <Point> > locationCollectionList = new List <List <Point> >();

                // we found a route that's common to the origin and the destination
                if (checkForAllRoutes || common_routes.Contains(route_id))
                {
                    string    name       = route_obj["long_name"].GetString();
                    string    color      = route_obj["color"].GetString();
                    JsonArray segmentArr = route_obj["segments"].GetArray();
                    foreach (JsonValue segment_id in segmentArr)
                    {
                        string       segmentID       = segment_id.Stringify().Replace("\"", "");
                        var          derp            = segmentMap[segmentID].Stringify();
                        string       encoded_segment = segmentMap[segmentID].Stringify().Replace("\"", "").Replace("\\\\", "\\");
                        List <Point> locations       = DecodeLatLong(encoded_segment);
                        locationCollectionList.Add(locations);
                    }
                    routeMap[route_id] = Tuple.Create <string, string, List <List <Point> > >(name, color, locationCollectionList);
                }
            }

            // clean up
            segmentMap = null;
            obj        = null;
            response.Dispose();
            response = null;
            client.Dispose();
            client            = null;
            common_routes     = null;
            idsAndCommonRotes = null;

            return(routeMap);
        }
Ejemplo n.º 52
0
 public AllJoynAction(string id, List <string> commands, JsonArray actionsConfig)
 {
     Id           = id;
     Commands     = commands;
     Interactions = actionsConfig.Select(x => new Interaction(x.GetObject())).ToList();
 }
Ejemplo n.º 53
0
        public JsonArray GetOrders(int userId, int orderId, string orderCode, int isSurvey, DateTime dtFrom, DateTime dtTo, int payStatus, int status, string receiver, int page, int pageSize, out int total)
        {
            using (helper = new SqlHelper())
            {
                StringBuilder where = new StringBuilder("1=1");
                if (userId > 0)
                {
                    helper.AddIntParameter("@UserID", userId);
                    where.Append(" and UserID=@UserID");
                }
                if (orderId > 0)
                {
                    helper.AddIntParameter("@OrderId", orderId);
                    where.Append(" and OrderId=@OrderId");
                }
                if (!string.IsNullOrEmpty(orderCode))
                {
                    helper.AddStringParameter("@OrderCode", 50, orderCode);
                    where.Append(" and OrderCode=@OrderCode");
                }
                if (dtFrom != DateTime.MinValue && dtTo != DateTime.MinValue)
                {
                    helper.AddDateTimeParameter("@DtFrom", dtFrom.Date);
                    helper.AddDateTimeParameter("@DtTo", dtTo.Date.AddDays(1).AddMilliseconds(-3));
                    where.Append(" and CreationTime between @DtFrom and @DtTo");
                }
                if (payStatus != -1)
                {
                    helper.AddIntParameter("@PayStatus", payStatus);
                    where.Append(" and PayStatus=@PayStatus");
                }
                if (status != -1)
                {
                    helper.AddIntParameter("@Status", status);
                    where.Append(" and Status=@Status");
                }
                if (!string.IsNullOrEmpty(receiver))
                {
                    helper.AddStringParameter("@Receiver", 20, receiver);
                    where.Append(" and Receiver like '%'+@Receiver+'%'");
                }
                if (isSurvey != -1)
                {
                    if (isSurvey == 0)
                    {
                        where.Append(" and (SurveyID=0 or SurveyID is null)");
                    }
                    else
                    {
                        where.Append(" and (SurveyID<>0 and SurveyID is not null)");
                    }
                }
                JsonArray orders = helper.GetJsonArray("a.OrderID", "a.OrderID,OrderCode,CreationTime,Status,PayType,PayStatus,a.Memo,UserID,Receiver,IP,a.CityID,a.RegionID,a.Address,Zip,a.Mobile,Phone,OriginalAmount,Amount,Freight,EarnestMoney,Measurement,IsDistribute,IsConsigned,Logistics,LogisticsCode,LogisticStatus,SignIn,Score,Comments,CityName,ProvinceName,RegionName,ServiceMemo,PayedTime,BuyerEmail,TransportType,TradeNo,SurveyID,f.ExpressID,ExpressName,ExpressUrl", "Orders a inner join City b on a.CityID=b.CityID inner join Province c on c.ProvinceID=b.ProvinceID left join Region d on d.RegionID=a.RegionID left join Survey e on a.OrderID=e.OrderID left join Express f on f.ExpressID=a.ExpressID", where.ToString(), page, pageSize, out total, "CreationTime");

                if (orders != null)
                {
                    string sql = "select DetailID,a.OrderID,a.ProductID,a.Discount,OrignalPrice,a.Quantity,b.Name,b.Code,Url,Points,b.Freight,b.Freight1,Express from OrderDetails a inner join Products b on a.ProductID=b.ProductID inner join Orders c on a.OrderID=c.OrderID left join (select PictureDesc,Url,a.ProductID as PID from ProductPictures b inner join (select ProductID,min(PictureID) as PictureID from ProductPictures group by ProductID) a on a.PictureID=b.PictureID) d on PID=a.ProductID where a.OrderID=@OrderID";

                    JsonObject orderObj;
                    helper.ClearParameters();
                    helper.AddIntParameter("@OrderID", 0);
                    ProductDAL productDAL = new ProductDAL();
                    int        regionID, productID, qty;
                    for (int i = 0; i < orders.Count; i++)
                    {
                        orderObj = orders[i];
                        helper.SetParameter("@OrderID", (int)orderObj["OrderID"]);
                        regionID = (int)orderObj["RegionID"];

                        var details = helper.GetJsonArray(sql, CommandType.Text);
                        foreach (var detail in details)
                        {
                            productID = (int)detail["ProductID"];
                            qty       = (int)detail["Quantity"];
                            var freight = productDAL.GetProductFreight(productID, regionID);
                            detail["Freight"]  = freight[0];
                            detail["Freight1"] = freight[1];
                        }

                        orderObj["children"] = details;
                    }
                }

                return(orders);
            }
        }
Ejemplo n.º 54
0
 public static VimeoVideo[] Parse(JsonArray array)
 {
     return(array == null ? new VimeoVideo[0] : array.ParseMultiple(Parse));
 }
 internal TwitterTimeline(JsonArray array) : base(array)
 {
     // Hide default constructor
 }
Ejemplo n.º 56
0
        public void Test_1_2_GetResult_ConditionNull()
        {
            // set mock
            MockHttpClientFactory factory = new MockHttpClientFactory();

            KiiAnalytics.AsyncHttpClientFactory = factory;
            MockHttpClient client = factory.Client;

            client.AddResponse(200, "{" +
                               "\"snapshots\" : [ {" +
                               "\"name\" : \"Male\"," +
                               "\"data\" : [ 546.775207 ]," +
                               "\"pointStart\" : 1338044400000," +
                               "\"pointInterval\" : 86400000}, " +
                               "{" +
                               "\"name\" : \"Female\"," +
                               "\"data\" : [ 325.216381 ]," +
                               "\"pointStart\" : 1338044400000," +
                               "\"pointInterval\" : 86400000}" +
                               "]}");

            GroupedResult   result    = null;
            string          ruleId    = null;
            ResultCondition condition = null;
            Exception       exp       = null;
            CountDownLatch  cd        = new CountDownLatch(1);

            KiiAnalytics.GetResult("a", null, (string id, ResultCondition c, GroupedResult r, Exception e) => {
                Interlocked.Exchange(ref result, r);
                Interlocked.Exchange(ref ruleId, id);
                Interlocked.Exchange(ref condition, c);
                Interlocked.Exchange(ref exp, e);
                cd.Signal();
            });

            if (!cd.Wait(new TimeSpan(0, 0, 0, 3)))
            {
                Assert.Fail("Callback not fired.");
            }
            Assert.AreEqual(ruleId, "a");
            Assert.IsNull(condition);
            Assert.IsNotNull(result);
            Assert.IsNull(exp);

            Assert.IsNotNull(result.SnapShots);
            IList <GroupedSnapShot> snapshots = result.SnapShots;

            Assert.AreEqual(2, snapshots.Count);

            GroupedSnapShot snapShot1 = snapshots[0];

            Assert.AreEqual("Male", snapShot1.Name);
            Assert.AreEqual(1338044400000, snapShot1.PointStart);
            Assert.AreEqual(86400000, snapShot1.PointInterval);
            JsonArray data = snapShot1.Data;

            Assert.AreEqual(1, data.Length());

            GroupedSnapShot snapShot2 = snapshots[1];

            Assert.AreEqual("Female", snapShot2.Name);
            Assert.AreEqual(1338044400000, snapShot2.PointStart);
            Assert.AreEqual(86400000, snapShot2.PointInterval);
            data = snapShot2.Data;
            Assert.AreEqual(1, data.Length());
        }
Ejemplo n.º 57
0
        private async Task GetSampleDataAsync()
        {
            if (this._groups.Count != 0)
            {
                return;
            }

            var client   = new HttpClient(); // Add: using System.Net.Http;
            var response = await client.GetAsync(new Uri("http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?apikey=uqaavp6g9u9fdytpacga2psv"));

            var jsonText = await response.Content.ReadAsStringAsync();

            JsonObject      jsonObject = JsonObject.Parse(jsonText);
            JsonArray       jsonArray  = jsonObject["movies"].GetArray();
            SampleDataGroup group      = new SampleDataGroup();

            foreach (JsonValue itemValue in jsonArray)
            {
                JsonObject itemObject = itemValue.GetObject();
                JsonObject poster     = itemObject["posters"].GetObject();
                JsonObject rating     = itemObject["ratings"].GetObject();
                JsonArray  all_cast   = itemObject["abridged_cast"].GetArray();
                String     cast       = "";
                String     charac     = "";

                for (int i = 0; i < 3; i++)
                {
                    if (i < all_cast.Count)
                    {
                        JsonObject castObject = all_cast[i].GetObject();
                        cast += castObject["name"].GetString() + "\n";
                        if (castObject.ContainsKey("characters"))
                        {
                            charac += castObject["characters"].GetArray()[0].GetString() + "\n";
                        }
                        else
                        {
                            charac += "\n";
                        };
                    }
                }
                JsonObject date_released = itemObject["release_dates"].GetObject();
                group.Items.Add(new SampleDataItem(itemObject["id"].GetString(),
                                                   poster["thumbnail"].GetString(),
                                                   itemObject["title"].GetString(),
                                                   itemObject["year"].GetNumber().ToString(),
                                                   itemObject["mpaa_rating"].GetString(),
                                                   rating["audience_score"].GetNumber().ToString(),
                                                   itemObject["synopsis"].GetString(),
                                                   cast,
                                                   itemObject["runtime"].GetNumber(),
                                                   date_released["theater"].GetString(),
                                                   rating["critics_score"].GetNumber().ToString(),
                                                   charac
                                                   ));
            }
            this.Groups.Add(group);


            var response_u = await client.GetAsync(new Uri("http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=uqaavp6g9u9fdytpacga2psv"));

            var jsonText_u = await response_u.Content.ReadAsStringAsync();

            JsonObject      jsonObject_u = JsonObject.Parse(jsonText_u);
            JsonArray       jsonArray_u  = jsonObject_u["movies"].GetArray();
            SampleDataGroup group_u      = new SampleDataGroup();

            foreach (JsonValue itemValue in jsonArray_u)
            {
                JsonObject itemObject = itemValue.GetObject();
                JsonObject poster     = itemObject["posters"].GetObject();
                JsonObject rating     = itemObject["ratings"].GetObject();
                JsonArray  all_cast   = itemObject["abridged_cast"].GetArray();
                String     cast       = "";
                String     charac     = "";
                for (int i = 0; i < 3; i++)
                {
                    if (i < all_cast.Count)
                    {
                        JsonObject castObject = all_cast[i].GetObject();
                        cast += castObject["name"].GetString() + "\n";
                        if (castObject.ContainsKey("characters"))
                        {
                            charac += castObject["characters"].GetArray()[0].GetString() + "\n";
                        }
                        else
                        {
                            charac += "\n";
                        }
                    }
                }
                JsonObject date_released = itemObject["release_dates"].GetObject();
                group_u.Items.Add(new SampleDataItem(itemObject["id"].GetString(),
                                                     poster["thumbnail"].GetString(),
                                                     itemObject["title"].GetString(),
                                                     itemObject["year"].GetNumber().ToString(),
                                                     itemObject["mpaa_rating"].GetString(),
                                                     rating["audience_score"].GetNumber().ToString(),
                                                     itemObject["synopsis"].GetString(),
                                                     cast,
                                                     itemObject["runtime"].GetNumber(),
                                                     date_released["theater"].GetString(),
                                                     rating["critics_score"].GetNumber().ToString(),
                                                     charac
                                                     ));
            }


            this.Groups.Add(group_u);
        }
Ejemplo n.º 58
0
            /// <summary>
            /// Attempt to parse a string into a JSONObject.
            /// </summary>
            /// <param name="jsonString"></param>
            /// <returns>A new JSONObject or null if parsing fails.</returns>
            public static JsonObject Parse(string jsonString)
            {
                if (string.IsNullOrEmpty(jsonString))
                {
                    return(null);
                }

                JsonValue currentValue = null;

                var keyList = new List <string>();

                var state = JsonParsingState.Object;

                for (var startPosition = 0; startPosition < jsonString.Length; ++startPosition)
                {
                    startPosition = SkipWhitespace(jsonString, startPosition);

                    switch (state)
                    {
                    case JsonParsingState.Object:
                        if (jsonString[startPosition] != '{')
                        {
                            return(Fail('{', startPosition));
                        }

                        JsonValue newObj = new JsonObject();
                        if (currentValue != null)
                        {
                            newObj.Parent = currentValue;
                        }
                        currentValue = newObj;

                        state = JsonParsingState.Key;
                        break;

                    case JsonParsingState.EndObject:
                        if (jsonString[startPosition] != '}')
                        {
                            return(Fail('}', startPosition));
                        }

                        if (currentValue.Parent == null)
                        {
                            return(currentValue.Obj);
                        }

                        switch (currentValue.Parent.Type)
                        {
                        case JsonValueType.Object:
                            currentValue.Parent.Obj.values[keyList.Pop()] = new JsonValue(currentValue.Obj);
                            break;

                        case JsonValueType.Array:
                            currentValue.Parent.Array.Add(new JsonValue(currentValue.Obj));
                            break;

                        default:
                            return(Fail("valid object", startPosition));
                        }
                        currentValue = currentValue.Parent;

                        state = JsonParsingState.ValueSeparator;
                        break;

                    case JsonParsingState.Key:
                        if (jsonString[startPosition] == '}')
                        {
                            --startPosition;
                            state = JsonParsingState.EndObject;
                            break;
                        }

                        var key = ParseString(jsonString, ref startPosition);
                        if (key == null)
                        {
                            return(Fail("key string", startPosition));
                        }
                        keyList.Add(key);
                        state = JsonParsingState.KeyValueSeparator;
                        break;

                    case JsonParsingState.KeyValueSeparator:
                        if (jsonString[startPosition] != ':')
                        {
                            return(Fail(':', startPosition));
                        }
                        state = JsonParsingState.Value;
                        break;

                    case JsonParsingState.ValueSeparator:
                        switch (jsonString[startPosition])
                        {
                        case ',':
                            state = currentValue.Type == JsonValueType.Object ? JsonParsingState.Key : JsonParsingState.Value;
                            break;

                        case '}':
                            state = JsonParsingState.EndObject;
                            --startPosition;
                            break;

                        case ']':
                            state = JsonParsingState.EndArray;
                            --startPosition;
                            break;

                        default:
                            return(Fail(", } ]", startPosition));
                        }
                        break;

                    case JsonParsingState.Value:
                    {
                        var c = jsonString[startPosition];
                        if (c == '"')
                        {
                            state = JsonParsingState.String;
                        }
                        else if (char.IsDigit(c) || c == '-')
                        {
                            state = JsonParsingState.Number;
                        }
                        else
                        {
                            switch (c)
                            {
                            case '{':
                                state = JsonParsingState.Object;
                                break;

                            case '[':
                                state = JsonParsingState.Array;
                                break;

                            case ']':
                                if (currentValue.Type == JsonValueType.Array)
                                {
                                    state = JsonParsingState.EndArray;
                                }
                                else
                                {
                                    return(Fail("valid array", startPosition));
                                }
                                break;

                            case 'f':
                            case 't':
                                state = JsonParsingState.Boolean;
                                break;


                            case 'n':
                                state = JsonParsingState.Null;
                                break;

                            default:
                                return(Fail("beginning of value", startPosition));
                            }
                        }

                        --startPosition;                                         //To re-evaluate this char in the newly selected state
                        break;
                    }

                    case JsonParsingState.String:
                        var str = ParseString(jsonString, ref startPosition);
                        if (str == null)
                        {
                            return(Fail("string value", startPosition));
                        }

                        switch (currentValue.Type)
                        {
                        case JsonValueType.Object:
                            currentValue.Obj.values[keyList.Pop()] = new JsonValue(str);
                            break;

                        case JsonValueType.Array:
                            currentValue.Array.Add(str);
                            break;

                        default:
                            JsonLogger.Error("Fatal error, current JSON value not valid");
                            return(null);
                        }

                        state = JsonParsingState.ValueSeparator;
                        break;

                    case JsonParsingState.Number:
                        var number = ParseNumber(jsonString, ref startPosition);
                        if (double.IsNaN(number))
                        {
                            return(Fail("valid number", startPosition));
                        }

                        switch (currentValue.Type)
                        {
                        case JsonValueType.Object:
                            currentValue.Obj.values[keyList.Pop()] = new JsonValue(number);
                            break;

                        case JsonValueType.Array:
                            currentValue.Array.Add(number);
                            break;

                        default:
                            JsonLogger.Error("Fatal error, current JSON value not valid");
                            return(null);
                        }

                        state = JsonParsingState.ValueSeparator;

                        break;

                    case JsonParsingState.Boolean:
                        if (jsonString[startPosition] == 't')
                        {
                            if (jsonString.Length < startPosition + 4 ||
                                jsonString[startPosition + 1] != 'r' ||
                                jsonString[startPosition + 2] != 'u' ||
                                jsonString[startPosition + 3] != 'e')
                            {
                                return(Fail("true", startPosition));
                            }

                            switch (currentValue.Type)
                            {
                            case JsonValueType.Object:
                                currentValue.Obj.values[keyList.Pop()] = new JsonValue(true);
                                break;

                            case JsonValueType.Array:
                                currentValue.Array.Add(new JsonValue(true));
                                break;

                            default:
                                JsonLogger.Error("Fatal error, current JSON value not valid");
                                return(null);
                            }

                            startPosition += 3;
                        }
                        else
                        {
                            if (jsonString.Length < startPosition + 5 ||
                                jsonString[startPosition + 1] != 'a' ||
                                jsonString[startPosition + 2] != 'l' ||
                                jsonString[startPosition + 3] != 's' ||
                                jsonString[startPosition + 4] != 'e')
                            {
                                return(Fail("false", startPosition));
                            }

                            switch (currentValue.Type)
                            {
                            case JsonValueType.Object:
                                currentValue.Obj.values[keyList.Pop()] = new JsonValue(false);
                                break;

                            case JsonValueType.Array:
                                currentValue.Array.Add(new JsonValue(false));
                                break;

                            default:
                                JsonLogger.Error("Fatal error, current JSON value not valid");
                                return(null);
                            }

                            startPosition += 4;
                        }

                        state = JsonParsingState.ValueSeparator;
                        break;

                    case JsonParsingState.Array:
                        if (jsonString[startPosition] != '[')
                        {
                            return(Fail('[', startPosition));
                        }

                        JsonValue newArray = new JsonArray();
                        if (currentValue != null)
                        {
                            newArray.Parent = currentValue;
                        }
                        currentValue = newArray;

                        state = JsonParsingState.Value;
                        break;

                    case JsonParsingState.EndArray:
                        if (jsonString[startPosition] != ']')
                        {
                            return(Fail(']', startPosition));
                        }

                        if (currentValue.Parent == null)
                        {
                            return(currentValue.Obj);
                        }

                        switch (currentValue.Parent.Type)
                        {
                        case JsonValueType.Object:
                            currentValue.Parent.Obj.values[keyList.Pop()] = new JsonValue(currentValue.Array);
                            break;

                        case JsonValueType.Array:
                            currentValue.Parent.Array.Add(new JsonValue(currentValue.Array));
                            break;

                        default:
                            return(Fail("valid object", startPosition));
                        }
                        currentValue = currentValue.Parent;

                        state = JsonParsingState.ValueSeparator;
                        break;

                    case JsonParsingState.Null:
                        if (jsonString[startPosition] == 'n')
                        {
                            if (jsonString.Length < startPosition + 4 ||
                                jsonString[startPosition + 1] != 'u' ||
                                jsonString[startPosition + 2] != 'l' ||
                                jsonString[startPosition + 3] != 'l')
                            {
                                return(Fail("null", startPosition));
                            }

                            switch (currentValue.Type)
                            {
                            case JsonValueType.Object:
                                currentValue.Obj.values[keyList.Pop()] = new JsonValue(JsonValueType.Null);
                                break;

                            case JsonValueType.Array:
                                currentValue.Array.Add(new JsonValue(JsonValueType.Null));
                                break;

                            default:
                                JsonLogger.Error("Fatal error, current JSON value not valid");
                                return(null);
                            }

                            startPosition += 3;
                        }
                        state = JsonParsingState.ValueSeparator;
                        break;
                    }
                }
                JsonLogger.Error("Unexpected end of string");
                return(null);
            }
Ejemplo n.º 59
0
 get => FromJToken(JsonArray[index]);
Ejemplo n.º 60
-1
        public void Store()
        {
            var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var sessionJson = new JsonObject();

            if (Folder != null)
            {
                sessionJson.Add("Folder", JsonValue.CreateStringValue(Folder.Path));
            }

            if (Photo != null)
            {
                var photoJson = new JsonObject();
                photoJson.Add("Path", JsonValue.CreateStringValue(Photo.File.Path));
                var filterIdsJson = new JsonArray();
                
                foreach (var filter in Photo.Filters)
                {
                    filterIdsJson.Add(JsonValue.CreateStringValue(filter.Id));
                }

                photoJson.Add("FilterIds", filterIdsJson);

                sessionJson.Add("Photo", photoJson);
            }

            settings.Values["Session"] = sessionJson.Stringify();
        }