Beispiel #1
0
 private static void maybeSetField(IJEnumerable <JToken> fieldsMeta, Dictionary <string, object> fields, string fieldName, object value)
 {
     if (fieldsMeta[fieldName]["operations"].Values().Any(o => "set".Equals(o.Value <string>())))
     {
         fields[fieldName] = value;
     }
 }
Beispiel #2
0
        public IJEnumerable <JToken> ExtractFromParentNode(string input, string parentNodeName)
        {
            IJEnumerable <JToken> result = null;

            result = JToken.Parse(input)[parentNodeName];
            return(result);
        }
Beispiel #3
0
        public IJEnumerable <JToken> ExtractFromChildNode(string input, string childNodeName)
        {
            IJEnumerable <JToken> result = null;

            result = JToken.Parse(input).Children()[childNodeName];
            return(result);
        }
        async Task GetMovies()
        {
            try
            {
                string response = await SendRequest(currentCinema.MoviesUrl);

                JToken jsonResponse = JsonConvert.DeserializeObject <JToken>(response);
                IJEnumerable <JToken> listJsonMovies  = jsonResponse.Values();
                IEnumerator <JToken>  movieEnumerator = listJsonMovies.GetEnumerator();

                Device.BeginInvokeOnMainThread(() =>
                {
                    LoadingPage.GetProgressBar().ProgressTo(0.6, 100, Easing.Linear);
                });

                while (movieEnumerator.MoveNext())
                {
                    Movie movie = new Movie(movieEnumerator.Current);
                    App.MovieTable.Save(movie);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Beispiel #5
0
        public static void GenerateHtml(IJEnumerable <JToken> videos, string filePath)
        {
            var pocos = videos.Select(x => new
            {
                Title = x["title"],
                Link  = x["media:group"]["media:content"]["@url"]
            });

            var html = new Collection <string>();

            var start = "<html><body><div>";
            var end   = "</div></body></html>";

            html.Add(start);
            foreach (var poco in pocos)
            {
                var line = $"<iframe src=\"{poco.Link}\"></iframe><hr/>";
                html.Add(line);
            }
            ;

            html.Add(end);

            File.WriteAllLines(filePath, html);
        }
Beispiel #6
0
        private static void CheckVideo(IJEnumerable <JToken> expected, VideoInfo actual)
        {
            Assert.AreEqual(expected["id"].Value <string>(), actual.Id);
            Assert.AreEqual(expected["title"].Value <string>(), actual.Title);
            Assert.AreEqual(expected["open_time"].Value <string>().ToDateTimeOffsetFromIso8601(), actual.OpenedAt);
            Assert.AreEqual(expected["start_time"].Value <string>().ToDateTimeOffsetFromIso8601(), actual.StartedAt);
            Assert.AreEqual(expected["schedule_end_time"] != null ? expected["schedule_end_time"].Value <string>().ToDateTimeOffsetFromIso8601() : DateTimeOffset.MinValue, actual.EndedAtInPlan);
            Assert.AreEqual(expected["end_time"].Value <string>().ToDateTimeOffsetFromIso8601(), actual.EndedAt);

            var comType = expected["provider_type"].Value <string>().ToCommunityType();

            Assert.AreEqual(comType == CommunityType.Official, actual.IsOfficial);
            Assert.AreEqual(comType == CommunityType.Channel, actual.IsChannel);
            Assert.AreEqual(comType == CommunityType.Community, actual.IsCommunity);
            Assert.AreEqual(comType, actual.CommunityType);

            Assert.AreEqual(expected["related_channel_id"].Value <string>(), actual.RelatedChannelId);
            Assert.AreEqual(expected["_picture_url"] != null ? expected["_picture_url"].Value <string>().ToUri() : null, actual.ThumbnailUrl);
            Assert.AreEqual(expected["_thumbnail_url"] != null ? expected["_thumbnail_url"].Value <string>().ToUri() : null, actual.SmallThumbnailUrl);
            Assert.AreEqual(expected["hidescore_online"].Value <ushort>(), actual.HidescoreOnline);
            Assert.AreEqual(expected["hidescore_comment"].Value <ushort>(), actual.HidescoreComment);
            Assert.AreEqual(expected["community_only"].Value <string>().ToBooleanFrom1() || expected["channel_only"].Value <string>().ToBooleanFrom1(), actual.IsMemberOnly);
            Assert.AreEqual(expected["view_counter"].Value <uint>(), actual.ViewCount);
            Assert.AreEqual(expected["comment_count"].Value <uint>(), actual.CommentCount);
            Assert.AreEqual(expected["_ts_reserved_count"].Value <uint>(), actual.TimeshiftReservedCount);

            Assert.AreEqual(expected["timeshift_enabled"].Value <ushort>(), actual.TimeshiftEnabled);
            Assert.AreEqual(expected["is_hq"].Value <string>().ToBooleanFrom1(), actual.IsHighQuality);
        }
Beispiel #7
0
 private IEnumerable <ClientParameter> ParseParams(IJEnumerable <JProperty> props)
 {
     foreach (var prop in props)
     {
         yield return(new ClientParameter(prop.Name, prop));
     }
 }
Beispiel #8
0
        public static List <string> GetAllUsersInTenant()
        {
            Console.WriteLine(" Getting all users in tenant");
            List <string> userPrincipalList = new List <string>();
            string        userSuffix        = "users?$select=userPrincipalName";
            string        userEndPoint      = AppState.GraphEndPoint + userSuffix;

            HttpClient         client  = new HttpClient();
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, userEndPoint);

            message.Headers.Add("Authorization", "Bearer " + AppState.Token);


            HttpResponseMessage response = client.SendAsync(message).Result;
            string userPayload           = response.Content.ReadAsStringAsync().Result;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                JObject resp = JObject.Parse(userPayload);
                IJEnumerable <JToken> users = resp.GetValue("value").AsJEnumerable();

                foreach (JToken user in users)
                {
                    userPrincipalList.Add(user.Value <string>("userPrincipalName"));
                }
            }
            Console.WriteLine($"Found {userPrincipalList.Count()} users");
            return(userPrincipalList);
        }
Beispiel #9
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jqGridData = (JqGridData)value;

            writer.WriteStartObject();
            WriteProperty(jqGridData.Configuration.Total, jqGridData.Total, writer);
            WriteProperty(jqGridData.Configuration.Page, jqGridData.Page, writer);
            WriteProperty(jqGridData.Configuration.Records, jqGridData.Records, writer);
            writer.WritePropertyName(jqGridData.Configuration.Root);
            var    hasId     = HasId(jqGridData);
            JArray jArray    = JArray.FromObject(jqGridData.Rows);
            JArray newjArray = new JArray();

            foreach (JToken jToken in jArray)
            {
                JObject jObject    = (JObject)jToken;
                JObject newjObject = new JObject();
                if (hasId && jqGridData.Configuration.IncludeId)
                {
                    JToken id = GetId(jObject);
                    newjObject.Add(jqGridData.Configuration.Id, id);
                    if (jqGridData.Configuration.ExcludeIdFromCell)
                    {
                        jObject.Remove("Id");
                    }
                }
                IJEnumerable <JToken> values = jObject.Values();
                newjObject.Add(new JProperty(jqGridData.Configuration.Cell, new JArray(values)));
                newjArray.Add(newjObject);
            }
            newjArray.WriteTo(writer);
            writer.WriteEndObject();
        }
Beispiel #10
0
        private async Task <List <WirelessSite> > ParseData(CancellationToken stoppingToken, string loadedData)
        {
            List <WirelessSite> sites = new List <WirelessSite>();

            try
            {
                var jObj = JObject.Parse(loadedData).Children().Children();
                IJEnumerable <JToken> jTok = default;
                if (jObj != null)
                {
                    jTok = jObj;
                }
                foreach (var site in jTok)
                {
                    try
                    {
                        sites.Add(site.ToObject <WirelessSite>());
                    }
                    catch (Exception) // if general structure was ok but in propertyes is for instance forbiden character this exception will ocure and only part of whole data will be skipped.
                    {
                        logger.LogWarning($"Cannot deserialize part, skiping:\n{site.ToString()}");
                    }
                }
            }
            catch (Exception e) // error in general structure, data are not usable
            {
                logger.LogError("Source data are not seriazible");
                appLifetime.StopApplication();
                return(null);
            }

            return(sites);
        }
Beispiel #11
0
 public IJEnumerable <JToken> FilterData(IJEnumerable <JToken> data)
 {
     if (Criteria == null)
     {
         return(data);
     }
     return(data.Where(d => d is JObject j && Criteria.All(c => c.SatisfiedBy(j))).AsJEnumerable());
 }
Beispiel #12
0
 public static void CheckDetailCommunity(IJEnumerable <JToken> expected, CommunityInfo actual)
 {
     if (CheckCommunity(expected, actual))
     {
         Assert.AreEqual(expected["user_count"].Value <uint>(), actual.UserCount);
         Assert.AreEqual(expected["level"].Value <ushort>(), actual.Level);
     }
 }
Beispiel #13
0
 public static void CheckSimpleCommunity(IJEnumerable <JToken> expected, CommunityInfo actual)
 {
     if (CheckCommunity(expected, actual))
     {
         Assert.AreEqual(0u, actual.UserCount);
         Assert.AreEqual(( ushort )0u, actual.Level);
     }
 }
Beispiel #14
0
        public IJEnumerable <JToken> ExtractFromParentChildren(string input, string childNodeName)
        {
            IJEnumerable <JToken> result = null;

            try{
                result = JToken.Parse(input).Children()[childNodeName];
            }catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); }
            return(result);
        }
Beispiel #15
0
        public static void PrintVideoTitles(IJEnumerable <JToken> videos)
        {
            foreach (var video in videos)
            {
                var title = video["title"];

                Console.WriteLine(title);
                Console.WriteLine();
            }
        }
Beispiel #16
0
        private static List <JToken> CompareChildKeyValues(IJEnumerable <JToken> check, IJEnumerable <JToken> childValues)
        {
            var result = new List <JToken>();

            foreach (JToken item in childValues)
            {
                result = check.Where(x => !x.SequenceEqual(item)).ToList();
            }

            return(result);
        }
Beispiel #17
0
 private void DownloadFinishedCallback()
 {
     imageCount    = -1;
     curCount      = 0;
     panel.Enabled = true;
     toolStripProgressBar.Style = ProgressBarStyle.Continuous;
     toolStripProgressBar.Value = 0;
     toolStripStatusLabel.Text  = "Finished downloading pool " + textBoxPID.Text + " (" + poolName + ")";
     json  = null;
     posts = null;
 }
Beispiel #18
0
    void OnMessage(int from, JToken data)
    {
        if ((string)data["action"] == "SHOOT")
        {
            float dx = (float)data["dx"];
            float dy = (float)data["dy"];
            Debug.Log("dx:" + dx + " dy:" + dy);
            var player_id = AirConsole.instance.ConvertDeviceIdToPlayerNumber(from);
            if (player_id == 0)
            {
                redCannonShoot.Shoot(dx, dy, 9);
            }
            else if (player_id == 1)
            {
                blueCannonShoot.Shoot(dx, dy, 8);
            }
        }
        if ((string)data["action"] == "BUILD")
        {
            IJEnumerable <JToken> components = data["components"].Children();
            List <Block>          blocks     = new List <Block>();
            var player_id = AirConsole.instance.ConvertDeviceIdToPlayerNumber(from);
            foreach (JToken comp in components)
            {
                float x = (int)comp["x"];
                float y = (int)comp["y"];
                x -= 141f;
                y -= 309f;
                x /= 40f;
                y /= 40f;
                y  = -y;

                string type = (string)comp["type"];
                Debug.Log(x + ", " + y + ": " + type);
                blocks.Add(new Block(x, y, type));
            }
            if (player_id == 0)
            {
                redBuilder.BuildBase(blocks, 8);
                redHasBuilt = true;
            }
            else if (player_id == 1)
            {
                blueBuilder.BuildBase(blocks, 9);
                blueHasBuilt = true;
            }
            if (redHasBuilt && blueHasBuilt)
            {
                var gm = new GameMode();
                gm.mode = "SHOOTING";
                AirConsole.instance.Broadcast(gm);
            }
        }
    }
Beispiel #19
0
        private static void UpdateComponentIds(IJEnumerable <JToken> inputs, IArmPropertyValueResolver armPropertyValueResolver)
        {
            var componentIdInput = inputs.GetObjectByName("ComponentId")?.GetObject("value");

            if (componentIdInput != null)
            {
                componentIdInput.ReplacePropertyValueWith(ArmTemplateDynamicProperty.SubscriptionId, armPropertyValueResolver);
                componentIdInput.ReplacePropertyValueWith(ArmTemplateDynamicProperty.ResourceGroupName, armPropertyValueResolver);
                componentIdInput.ReplacePropertyValueWith(ArmTemplateDynamicProperty.AppInsightsName, armPropertyValueResolver);
            }
        }
Beispiel #20
0
        public string parseJSON(JObject item)
        {
            string wikiText = "";

            IJEnumerable <JToken> list = item["query"]["pages"].Children();

            foreach (var row in list)
            {
                wikiText = (string)row.Last.Last;
            }
            return(wikiText);
        }
Beispiel #21
0
        public void CovariantIJEnumerable()
        {
            IEnumerable <JObject> o = new[]
            {
                JObject.FromObject(new { First = 1, Second = 2 }),
                JObject.FromObject(new { First = 1, Second = 2 })
            };

            IJEnumerable <JToken> values = o.Properties();

            Assert.AreEqual(4, values.Count());
        }
Beispiel #22
0
        public string parseJSONImage(JObject item)
        {
            string wikiImageURL = "";

            IJEnumerable <JToken> list = item["query"]["pages"].Children();

            foreach (var row in list)
            {
                wikiImageURL = (string)row.Last["thumbnail"].First;
            }
            return(wikiImageURL);
        }
Beispiel #23
0
        /// <summary>
        ///   Takes a string, representing either a ListAssetsResponse or ListUserAssetsResponse proto, and
        ///   fills polyListResult with relevant fields from the response and returns a success status
        ///   if the response is of the expected format, or a failure status if it's not.
        /// </summary>
        public static PolyStatus ParseReturnedAssets(string response, out PolyListAssetsResult polyListAssetsResult)
        {
            // Try and actually parse the string.
            JObject results = JObject.Parse(response);
            IJEnumerable <JToken> assets = results["assets"].AsJEnumerable();

            // If assets is null, check for a userAssets object, which would be present if the response was
            // a ListUserAssets response.
            if (assets == null)
            {
                assets = results["userAssets"].AsJEnumerable();
            }
            if (assets == null)
            {
                // Empty response means there were no assets that matched the request parameters.
                polyListAssetsResult = new PolyListAssetsResult(PolyStatus.Success(), /*totalSize*/ 0);
                return(PolyStatus.Success());
            }
            List <PolyAsset> polyAssets = new List <PolyAsset>();

            foreach (JToken asset in assets)
            {
                PolyAsset polyAsset;
                if (!(asset is JObject))
                {
                    Debug.LogWarningFormat("Ignoring asset since it's not a JSON object: " + asset);
                    continue;
                }
                JObject jObjectAsset = (JObject)asset;
                if (asset["asset"] != null)
                {
                    // If this isn't null, means we are parsing a ListUserAssets response, which has an added
                    // layer of nesting.
                    jObjectAsset = (JObject)asset["asset"];
                }
                PolyStatus parseStatus = ParseAsset(jObjectAsset, out polyAsset);
                if (parseStatus.ok)
                {
                    polyAssets.Add(polyAsset);
                }
                else
                {
                    Debug.LogWarningFormat("Failed to parse a returned asset: {0}", parseStatus);
                }
            }
            var totalSize = results["totalSize"] != null?int.Parse(results["totalSize"].ToString()) : 0;

            var nextPageToken = results["nextPageToken"] != null ? results["nextPageToken"].ToString() : null;

            polyListAssetsResult = new PolyListAssetsResult(PolyStatus.Success(), totalSize, polyAssets, nextPageToken);
            return(PolyStatus.Success());
        }
 private void _bgGetUpdateDetails_RunWorkerCompleted(
     object sender,
     RunWorkerCompletedEventArgs e)
 {
     try
     {
         if (!(e.Result is JToken result))
         {
             return;
         }
         this.OemUpdateList = new ObservableCollection <AppPlayerUpdateModel>();
         IJEnumerable <JToken> source = result.First <JToken>().Children().Children <JToken>();
         if (source != null && source.Any <JToken>())
         {
             foreach (object obj in (IEnumerable <JToken>)source)
             {
                 this.OemUpdateList.Add(JsonConvert.DeserializeObject <AppPlayerUpdateModel>(obj.ToString(), Utils.GetSerializerSettings()));
             }
         }
         foreach (AppPlayerModel coexistingOem in (Collection <AppPlayerModel>)InstalledOem.CoexistingOemList)
         {
             AppPlayerModel       item = coexistingOem;
             AppPlayerUpdateModel playerUpdateModel = this.OemUpdateList.Where <AppPlayerUpdateModel>((Func <AppPlayerUpdateModel, bool>)(u => u.RequestedOem == item.AppPlayerOem)).FirstOrDefault <AppPlayerUpdateModel>();
             if (playerUpdateModel != null)
             {
                 playerUpdateModel.OemDisplayName = item.AppPlayerOemDisplayName;
             }
         }
         foreach (AppPlayerUpdateModel oemUpdate in (Collection <AppPlayerUpdateModel>) this.OemUpdateList)
         {
             AppPlayerUpdateModel item = oemUpdate;
             if (item.OemDisplayName != null && InstalledOem.InstalledCoexistingOemList.Contains(item.RequestedOem))
             {
                 SimpleIoc.Default.Unregister <EngineUpdateViewModel>(item.OemDisplayName);
                 SimpleIoc.Default.Register <EngineUpdateViewModel>((Func <EngineUpdateViewModel>)(() => new EngineUpdateViewModel(item)), item.OemDisplayName);
                 EngineUpdateViewModel instance = SimpleIoc.Default.GetInstance <EngineUpdateViewModel>(item.OemDisplayName);
                 if (!this.EngineUpdateViewModelList.Contains(instance))
                 {
                     this.EngineUpdateViewModelList.Add(instance);
                 }
             }
         }
         this.RaisePropertyChanged("EngineUpdateViewModelList");
         this.CheckUpdateGridVisibility = false;
         this.HyperLinkTextVisibility   = true;
     }
     catch (Exception ex)
     {
         Logger.Error("Failed to get update details err: {0}", (object)ex.Message);
     }
 }
Beispiel #25
0
        public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            string jsonUrl = "https://mangadex.org/api/chapter/" + chapter.GetID();
            string jsonString;

            using (var wc = new WebClient())
            {
                jsonString = wc.DownloadString(jsonUrl);
            }

            JObject jobj = JObject.Parse(jsonString);

            string server = (string)jobj["server"];
            string hash   = (string)jobj["hash"];

            // string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
            List <string>         page_array = new List <string>();
            IJEnumerable <JToken> jtokens    = jobj["page_array"].Values();

            foreach (JToken t in jtokens)
            {
                page_array.Add((string)t);
            }

            foreach (string file in page_array)
            {
                if (server == "/data/")
                {
                    server = "https://mangadex.org/data/";
                }

                string imgUrl = server + hash + "/" + file;

                FileInfo imgFile = new FileInfo(
                    Path.Combine(
                        chapter.GetChapterRoot().FullName,
                        ConvertToNumericFileName(file)
                        ));

                if (File.Exists(imgFile.FullName))
                {
                    if (imgFile.Length <= 0)
                    {
                        File.Delete(imgFile.FullName);
                    }
                }

                DownloadAsync(new Uri(imgUrl), imgFile.FullName);
            }
        }
Beispiel #26
0
        // Token: 0x06001203 RID: 4611 RVA: 0x000636E0 File Offset: 0x000618E0
        public static IJEnumerable <T> AsJEnumerable <[Nullable(0)] T>(this IEnumerable <T> source) where T : JToken
        {
            if (source == null)
            {
                return(null);
            }
            IJEnumerable <T> ijenumerable = source as IJEnumerable <T>;

            if (ijenumerable != null)
            {
                return(ijenumerable);
            }
            return(new JEnumerable <T>(source));
        }
        public static Dictionary <string, object> Bagify(this JToken obj, string name = null)
        {
            name = name ?? "obj";
            JObject jobojectAux = obj as JObject;

            if (jobojectAux != null)
            {
                IEnumerable <KeyValuePair <string, object> > asBag = from prop in jobojectAux.Properties()
                                                                     let propName = prop.Name
                                                                                    let propValue =
                    prop.Value is JValue
                                                                          ? new Dictionary <string, object>()
                {
                    {
                        prop.Name,
                        prop.Value
                    }
                }
                                                                          : prop.Value.Bagify(prop.Name)
                select
                new KeyValuePair <string, object>(
                    propName,
                    propValue);
                return(asBag.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
            }

            if (obj is JArray)
            {
                IJEnumerable <JToken> vals = (obj as JArray).Values();
                object[] alldicts          = vals.SelectMany(val => val.Bagify(name)).Select(x => x.Value).ToArray();
                return(new Dictionary <string, object>()
                {
                    { name, (object)alldicts }
                });
            }

            if (obj is JValue)
            {
                return(new Dictionary <string, object>()
                {
                    { name, (obj as JValue) }
                });
            }

            return(new Dictionary <string, object>()
            {
                { name, null }
            });
        }
Beispiel #28
0
        public string GetTitle(string title, string year = "")
        {
            var url = string.Format("{0}/?page=1&r=json&s={1}", urlBase, title.Replace(" ", "%20"));

            if (year != "")
            {
                url += string.Format("&y={0}", year);
            }

            var client  = new RestClient(url);
            var request = new RestRequest(Method.GET);

            request.AddHeader("x-rapidapi-host", "movie-database-imdb-alternative.p.rapidapi.com");
            request.AddHeader("x-rapidapi-key", "f439435b7dmshd45ea6ae205714ap14de2bjsnfe4d88c18881");
            IRestResponse response = client.Execute(request);

            if (response != null && response.StatusCode == HttpStatusCode.OK)
            {
                var json = JObject.Parse(response.Content);

                if (json != null)
                {
                    if (json["Search"] is JArray search)
                    {
                        IJEnumerable <JProperty> properties = null;
                        JProperty selectedTitle             = null;

                        foreach (var item in search.Children())
                        {
                            properties    = item.Children <JProperty>();
                            selectedTitle = properties.FirstOrDefault(x => x.Name == "Title");

                            if (selectedTitle != null)
                            {
                                if (selectedTitle.Value.ToString().ToUpper() == title.ToUpper())
                                {
                                    break;
                                }
                            }
                        }
                        if (selectedTitle != null)
                        {
                            return(properties?.FirstOrDefault(x => x.Name == "imdbID").Value.ToString() ?? HttpStatusCode.NotFound.ToString());
                        }
                    }
                }
            }
            return(HttpStatusCode.NotFound.ToString());
        }
        public void JSONmanagerParseJSONParentChildColectiontoStringReturnsString()
        {
            //extract from JSON parent node
            IJEnumerable <JToken> jte = jm.ExtractFromParentChildNode(str1, "news", "Title");
            //convert to collection of strings
            IEnumerable <string> res = jm.DeserializeFromParentChildNode <string>(str1, "news", "Title");
            //to string  Selectable -> ignore nulls, no intending
            string resp = jm.CollectionToStringFormat <string>(res
                                                               , new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Include, Formatting = Formatting.None
            });

            Assert.Equal(resp, act1);
        }
        public void JSONmngParsefromChildCollectionreturnsString()
        {
            //extract from child nodes
            IJEnumerable <JToken> jte = jm.ExtractFromChildNode(str4, "Name");
            //to collection
            IEnumerable <string> res = jm.DeserializeFromChildNode <string>(str4, "Name");
            //to string  Selectable -> ignore nulls, no intending
            string resp = jm.CollectionToStringFormat <string>(res
                                                               , new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Include, Formatting = Formatting.None
            });

            Assert.Equal(resp, act1);
        }