Example #1
0
        /// <summary>
        /// SenderId 会話を生成する。
        /// </summary>
        private async Task <Conversation> CreateOrUpdateConversationAsync(string senderId, string path, JObject data)
        {
            var conversation = await _db.Conversation.Where(x => x.SenderId == senderId).FirstOrDefaultAsync();

            if (conversation == null)
            {
                conversation = new Conversation
                {
                    SenderId = senderId,
                    Path     = path,
                    Data     = data?.ToString() ?? "{}",
                };

                _db.Add(conversation);
                await _db.SaveChangesAsync();
            }
            else
            {
                conversation.Path = path;
                conversation.Data = data?.ToString() ?? "{}";
                await _db.SaveChangesAsync();
            }

            return(conversation);
        }
        public void Example()
        {
            #region Usage
            JObject o = new JObject
            {
                { "name1", "value1" },
                { "name2", "value2" }
            };

            JsonWriter writer = o.CreateWriter();
            writer.WritePropertyName("name3");
            writer.WriteStartArray();
            writer.WriteValue(1);
            writer.WriteValue(2);
            writer.WriteEndArray();

            Console.WriteLine(o.ToString());
            // {
            //   "name1": "value1",
            //   "name2": "value2",
            //   "name3": [
            //     1,
            //     2
            //   ]
            // }
            #endregion
        }
Example #3
0
        public async Task CreateAssociation(int from, int to, string type, JObject attributes)
        {
            using (var db = await _data.Connect())
            {
                var count = await db.ExecuteScalarAsync <int>(
                    @"select count(*) from association
                  where type = @ty and `from` = @f and `to` = @t",
                    new { ty = type, f = from, t = to });

                if (count == 0)
                {
                    await db.ExecuteAsync(
                        @"insert into association (type, created, `from`, `to`, `attributes`)
                      values (@ty, @c, @f, @t, @a)",
                        new
                    {
                        ty = type,
                        c  = DateTime.UtcNow,
                        f  = from,
                        t  = to,
                        a  = attributes?.ToString(Formatting.None)
                    });
                }
            }
        }
        static void Main011(string[] args)
        {
            var info = new
            {
                pageIndex     = 1,
                pageSize      = 10,
                projectCode   = "ff8080817682f02601768933e2540009",
                buildCorpCode = "91420100177738297E"
            };

            JObject result = null;

            try
            {
                HjApi api = new HjApi()
                {
                    Endpoint = "open/api/get", Method = "Project.Query", Version = "1.0"
                };
                result = HjApiCaller.CallOpenApi(api, info);
            }
            catch (Exception e)
            {
                throw;
            }

            Console.WriteLine(result?.ToString());
        }
        /// <summary>
        /// Given a structured lg result, create an activity.
        /// </summary>
        /// This method will create an MessageActivity from JToken
        /// <param name="lgJObj">lg output.</param>
        /// <returns>Activity for it.</returns>
        private static Activity BuildActivityFromLGStructuredResult(JObject lgJObj)
        {
            var activity = new Activity();
            var type     = GetStructureType(lgJObj);

            if (GenericCardTypeMapping.ContainsKey(type) ||
                type == nameof(Attachment).ToLowerInvariant())
            {
                activity = MessageFactory.Attachment(GetAttachment(lgJObj)) as Activity;
            }
            else if (type == nameof(Activity).ToLowerInvariant())
            {
                activity = BuildActivity(lgJObj);

                // InvokeResponse requires value to be a InvokeResponse typed object.
                if (activity.Type == ActivityTypesEx.InvokeResponse && activity.Value != null)
                {
                    activity.Value = JObject.FromObject(activity.Value).ToObject <InvokeResponse>();
                }
            }
            else
            {
                activity = BuildActivityFromText(lgJObj?.ToString()?.Trim());
            }

            return(activity);
        }
Example #6
0
		internal async Task<JObject> SendCommandAndCheck (JObject args, string method, string script_loc, int line, int column, string function_name,
								Func<JObject, Task> wait_for_event_fn = null, Action<JToken> locals_fn = null, string waitForEvent = Inspector.PAUSE)
		{
			var res = await ctx.cli.SendCommand (method, args, ctx.token);
			if (!res.IsOk) {
				Console.WriteLine ($"Failed to run command {method} with args: {args?.ToString ()}\nresult: {res.Error.ToString ()}");
				Assert.True (false, $"SendCommand for {method} failed with {res.Error.ToString ()}");
			}

			var wait_res = await ctx.insp.WaitFor(waitForEvent);

			if (function_name != null)
				Assert.Equal (function_name, wait_res ["callFrames"]?[0]?["functionName"]?.Value<string> ());

			if (script_loc != null)
				CheckLocation (script_loc, line, column, ctx.scripts, wait_res ["callFrames"][0]["location"]);

			if (wait_for_event_fn != null)
				await wait_for_event_fn (wait_res);

			if (locals_fn != null) {
				var locals = await GetProperties (wait_res ["callFrames"][0]["callFrameId"].Value<string> ());
				locals_fn (locals);
			}

			return wait_res;
		}
Example #7
0
        public async Task <IActionResult> PostAsync([FromBody] JObject data)
        {
            using (_logger.BeginScope(new ExceptionlessState().SetHttpContext(HttpContext).Property("event", data))) {
                string json = data?.ToString();
                if (String.IsNullOrEmpty(json))
                {
                    _logger.LogWarning("Unable to get json of incoming event.");
                    return(BadRequest());
                }

                if (!Request.Headers.TryGetValue("Stripe-Signature", out var signature) || String.IsNullOrEmpty(signature))
                {
                    _logger.LogWarning("No Stripe-Signature header was sent with incoming event.");
                    return(BadRequest());
                }

                StripeEvent stripeEvent;
                try {
                    stripeEvent = StripeEventUtility.ConstructEvent(json, signature, Settings.Current.StripeWebHookSigningSecret);
                } catch (Exception ex) {
                    _logger.LogError(ex, "Unable to parse incoming event: {Message}", ex.Message);
                    return(BadRequest());
                }

                if (stripeEvent == null)
                {
                    _logger.LogWarning("Null stripe event.");
                    return(BadRequest());
                }

                await _stripeEventHandler.HandleEventAsync(stripeEvent);

                return(Ok());
            }
        }
        public void Example()
        {
            #region Usage
            JObject o = new JObject
            {
                { "Cpu", "Intel" },
                { "Memory", 32 },
                {
                    "Drives", new JArray
                    {
                        "DVD",
                        "SSD"
                    }
                }
            };

            Console.WriteLine(o.ToString());
            // {
            //   "Cpu": "Intel",
            //   "Memory": 32,
            //   "Drives": [
            //     "DVD",
            //     "SSD"
            //   ]
            // }
            #endregion
        }
Example #9
0
 private void PrintContext()
 {
     _output.WriteLine("");
     _output.WriteLine("Context:");
     _output.WriteLine(_context?.ToString());
     _output.WriteLine("");
 }
Example #10
0
        public NuGetProject AddBuildIntegratedProject(string projectName = null, NuGetFramework projectTargetFramework = null, JObject json = null)
        {
            var existingProject = Task.Run(async() => await GetNuGetProjectAsync(projectName));

            existingProject.Wait();
            if (existingProject.IsCompleted && existingProject.Result != null)
            {
                throw new ArgumentException("Project with " + projectName + " already exists");
            }

            projectName = string.IsNullOrEmpty(projectName) ? Guid.NewGuid().ToString() : projectName;
            var projectFullPath = Path.Combine(SolutionDirectory, projectName);

            Directory.CreateDirectory(projectFullPath);

            var projectJsonPath = Path.Combine(projectFullPath, "project.json");

            CreateConfigJson(projectJsonPath, json?.ToString() ?? BasicConfig.ToString());

            projectTargetFramework = projectTargetFramework ?? NuGetFramework.Parse("net46");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext(),
                                                                              projectFullPath, projectName);

            var          projectFilePath = Path.Combine(projectFullPath, $"{msBuildNuGetProjectSystem.ProjectName}.csproj");
            NuGetProject nuGetProject    = new ProjectJsonNuGetProject(projectJsonPath, projectFilePath);

            NuGetProjects.Add(nuGetProject);

            return(nuGetProject);
        }
        public ActionResult ExecuteCommand(string commandName, [FromBody] JObject requestJson)
        {
            var request  = requestJson?.ToString();
            var response = RequestRunner.Execute(commandName, request);

            return(Json(response));
        }
Example #12
0
        async Task <JObject> SendCommandAndCheck(JObject args, string method, DebugTestContext ctx, Func <JObject, Task> wait_for_event_fn = null,
                                                 Action <JToken> locals_fn = null, string waitForEvent = Inspector.PAUSE)
        {
            var res = await ctx.cli.SendCommand(method, args, ctx.token);

            if (!res.IsOk)
            {
                Console.WriteLine($"Failed to run command {method} with args: {args?.ToString ()}\nresult: {res.Error.ToString ()}");
                Assert.True(false, $"SendCommand for {method} failed with {res.Error.ToString ()}");
            }

            var wait_res = await ctx.insp.WaitFor(waitForEvent);

            if (wait_for_event_fn != null)
            {
                await wait_for_event_fn(wait_res);
            }

            if (locals_fn != null)
            {
                await CheckLocalsOnFrame(wait_res ["callFrames"][0], ctx, locals_fn);
            }

            return(wait_res);
        }
Example #13
0
        static void Main(string[] args)
        {
            dynamic jObject = new JObject();

            jObject.Property1 = (float)5.6;
            jObject.Property2 = "test";
            //jObject = null;

            string jsonString = jObject?.ToString(Formatting.None);

            Console.WriteLine(jsonString);

            if (!string.IsNullOrEmpty(jsonString))
            {
                dynamic json = JValue.Parse(jsonString);
                if (json != null)
                {
                    Console.WriteLine(json.Property1);
                }
                else
                {
                    Console.WriteLine("json null");
                }
            }
            else
            {
                Console.WriteLine("json string null");
            }
        }
        /// <summary>
        /// This will rebuild an entire index alias behind the scenes with no downtime. It creates a new index
        /// and populates it then uses Elasticsearch's hot-swapping technique to bring it online.
        /// </summary>
        public async static Task RebuildIndexWithHotSwapAsync(
            this IElasticLowLevelClient client,
            string alias,
            JObject indexMapping,
            Func <Task <IEnumerable <BulkIndexingDoc> > > reader,
            CancellationToken ctx = default(CancellationToken))
        {
            var deletableIndices = JArray.Parse((await client.CatAliasesAsync <StringResponse>(alias, new CatAliasesRequestParameters {
                Format = "json"
            }, ctx)).Body)
                                   .Select(x => new
            {
                alias = x.Value <string>("alias"),
                index = x.Value <string>("index")
            })
                                   .ToList();

            var index = GenerateUniqueIndexNameForAlias(alias);

            await client.IndicesCreateAsync <StringResponse>(index, PostData.String(indexMapping?.ToString()), ctx : ctx);

            while (!ctx.IsCancellationRequested)
            {
                // TODO: If an exception is thrown, delete the half-created index
                var docs = await reader();

                if (ctx.IsCancellationRequested || !docs.Any())
                {
                    break;
                }

                var body         = docs.SelectMany(doc => doc.ToLines().Select(x => x.ToString(Formatting.None)));
                var bulkResponse = await client.BulkAsync <StringResponse>(index, PostData.MultiJson(body));

                ThrowOnPartialBulkSuccess(bulkResponse);
            }

            if (ctx.IsCancellationRequested)
            {
                return;
            }

            var actions = deletableIndices.Select(idx => (object)new
            {
                remove = new { idx.index, idx.alias }
            }).ToList();

            actions.Add(new { add = new { index, alias } });

            // This is the hot-swap. The actions in the list are performed atomically
            await client.IndicesUpdateAliasesForAllAsync <StringResponse>(PostData.String(JObject.FromObject(new
            {
                actions
            }).ToString()), ctx : ctx);

            if (deletableIndices.Any())
            {
                await client.IndicesDeleteAsync <StringResponse>(string.Join(",", deletableIndices.Select(x => x.index)), ctx : ctx);
            }
        }
Example #15
0
        private static void OutputTrimEqual(JObject expectedJObject, JObject actualJObject, bool output = true)
        {
            if (expectedJObject == null || actualJObject == null)
            {
                if (output)
                {
                    Console.WriteLine(expectedJObject?.ToString());
                    Console.WriteLine(actualJObject?.ToString());
                }

                return;
            }

            foreach (var prop in actualJObject.Properties().ToArray())
            {
                if (JToken.DeepEquals(actualJObject[prop.Name], expectedJObject[prop.Name]))
                {
                    actualJObject.Remove(prop.Name);
                    expectedJObject.Remove(prop.Name);
                }
            }

            foreach (var prop in actualJObject.Properties().Where(p => p.Value is JObject).Select(p => new { name = p.Name, value = p.Value as JObject }).ToArray())
            {
                OutputTrimEqual(prop.value, expectedJObject[prop.name]?.Value <JObject>(), false);
            }

            if (output)
            {
                Console.WriteLine(expectedJObject.ToString());
                Console.WriteLine(actualJObject.ToString());
            }
        }
Example #16
0
 public override string ToString()
 {
     if (Document?.Property("magicArray") != null)
     {
         return(Document.Property("magicArray").Value?.ToString() ?? String.Empty);
     }
     return(Document?.ToString() ?? String.Empty);
 }
Example #17
0
		internal async Task<Result> SendCommand (string method, JObject args) {
			var res = await ctx.cli.SendCommand (method, args, ctx.token);
			if (!res.IsOk) {
				Console.WriteLine ($"Failed to run command {method} with args: {args?.ToString ()}\nresult: {res.Error.ToString ()}");
				Assert.True (false, $"SendCommand for {method} failed with {res.Error.ToString ()}");
			}
			return res;
		}
Example #18
0
        public void WritePropertyWithNoValue()
        {
            var o = new JObject();
            o.Add(new JProperty("novalue"));

            StringAssert.Equal(@"{
  ""novalue"": null
}", o.ToString());
        }
        public void Example()
        {
            #region Usage
            List<Post> posts = GetPosts();

            JObject rss =
                new JObject(
                    new JProperty("channel",
                        new JObject(
                            new JProperty("title", "James Newton-King"),
                            new JProperty("link", "http://james.newtonking.com"),
                            new JProperty("description", "James Newton-King's blog."),
                            new JProperty("item",
                                new JArray(
                                    from p in posts
                                    orderby p.Title
                                    select new JObject(
                                        new JProperty("title", p.Title),
                                        new JProperty("description", p.Description),
                                        new JProperty("link", p.Link),
                                        new JProperty("category",
                                            new JArray(
                                                from c in p.Categories
                                                select new JValue(c)))))))));

            Console.WriteLine(rss.ToString());

            // {
            //   "channel": {
            //     "title": "James Newton-King",
            //     "link": "http://james.newtonking.com",
            //     "description": "James Newton-King's blog.",
            //     "item": [
            //       {
            //         "title": "Json.NET 1.3 + New license + Now on CodePlex",
            //         "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex",
            //         "link": "http://james.newtonking.com/projects/json-net.aspx",
            //         "category": [
            //           "Json.NET",
            //           "CodePlex"
            //         ]
            //       },
            //       {
            //         "title": "LINQ to JSON beta",
            //         "description": "Annoucing LINQ to JSON",
            //         "link": "http://james.newtonking.com/projects/json-net.aspx",
            //         "category": [
            //           "Json.NET",
            //           "LINQ"
            //         ]
            //       }
            //     ]
            //   }
            // }
            #endregion
        }
Example #20
0
 public static Task QueueStateTransition(this IMessageBroker messageBroker, string processInstanceId, string flowNodeInstanceId, string state, JObject jObj, CancellationToken token)
 {
     return(messageBroker.Queue(BPMNConstants.QueueNames.StateTransitions, new StateTransitionNotification(Guid.NewGuid().ToString())
     {
         Content = jObj?.ToString(),
         State = state,
         ProcessInstanceId = processInstanceId,
         FlowNodeInstanceId = flowNodeInstanceId
     }, token));
 }
Example #21
0
        public async Task <string> Request(HttpMethod method, string url, JObject parameters = null, bool skipRefreshToken = false)
        {
            if (!skipRefreshToken)
            {
                await RefreshAccessToken();
            }

            StringContent content = new StringContent(parameters?.ToString(Formatting.None));

            NameValueCollection query = HttpUtility.ParseQueryString(string.Empty);

            query.Add("query", parameters.ToString(Formatting.None));

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();

            httpRequestMessage.Headers.Add("Authorization", string.Format("Bearer {0}", TokenManager.singleton.accessToken));
            httpRequestMessage.Headers.Add("Content-Type", "application/json");
            httpRequestMessage.Method = method;

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                httpRequestMessage.Content    = content;
                httpRequestMessage.RequestUri = new Uri(url);
            }
            else
            {
                httpRequestMessage.RequestUri = new Uri(url + query.ToString());
            }

            HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage);

            string body = await response.Content.ReadAsStringAsync();

            int statusCode = (int)response.StatusCode;

            switch (statusCode)
            {
            case 200:
                return(body);

            case 401:
                TokenManager.singleton.Clear();
                throw new HttpException(401, "Unauthorized.");

            case 403:
                throw new HttpException(403, "Forbidden.");

            default:
                HttpException.HttpErrors errors = JsonUtility.FromJson <HttpException.HttpErrors>(body);
                throw new HttpException(statusCode, errors.errors);
            }
        }
Example #22
0
        private static HttpRequestMessage GetRequestMessage(HttpMethod method, JObject requestOptions)
        {
            var request = new HttpRequestMessage();

            var data = requestOptions?.ToString();

            if (data != null)
            {
                request.Content = new StringContent(data, Encoding.UTF8, "application/json");
            }

            return(request);
        }
        public ActionResult ExecuteQuery(string queryName)
        {
            JObject requestJson = new JObject();

            foreach (var q in HttpContext.Request.Query)
            {
                requestJson.Add(q.Key, q.Value.FirstOrDefault());
            }
            var request  = requestJson?.ToString();
            var response = RequestRunner.Execute(queryName, request);

            return(Json(response));
        }
Example #24
0
    internal override async Task <JObject> SendCommandAndCheck(JObject args, string method, string script_loc, int line, int column, string function_name,
                                                               Func <JObject, Task> wait_for_event_fn = null, Func <JToken, Task> locals_fn = null, string waitForEvent = Inspector.PAUSE)
    {
        switch (method)
        {
        case "Debugger.resume":
            return(await StepAndCheck(StepKind.Resume, script_loc, line, column, function_name, wait_for_event_fn, locals_fn));

        case "Debugger.stepInto":
            return(await StepAndCheck(StepKind.Into, script_loc, line, column, function_name, wait_for_event_fn, locals_fn));
        }
        var res = await cli.SendCommand(method, args, token);

        if (!res.IsOk)
        {
            _testOutput.WriteLine($"Failed to run command {method} with args: {args?.ToString()}\nresult: {res.Error.ToString()}");
            Assert.True(false, $"SendCommand for {method} failed with {res.Error.ToString()}");
        }
        var wait_res = await WaitFor(waitForEvent);

        if (function_name != null)
        {
            AssertEqual(function_name, wait_res["callFrames"]?[0]?["functionName"]?.Value <string>(), wait_res["callFrames"]?[0]?["functionName"]?.ToString());
        }

        if (script_loc != null && line >= 0)
        {
            CheckLocation(script_loc, line, column, scripts, wait_res["callFrames"]?[0]?["location"]);
        }

        if (wait_for_event_fn != null)
        {
            await wait_for_event_fn(wait_res);
        }

        if (locals_fn != null)
        {
            var locals = await GetProperties(wait_res["callFrames"][0]["callFrameId"].Value <string>());

            try
            {
                await locals_fn(locals);
            }
            catch (System.AggregateException ex)
            {
                throw new AggregateException(ex.Message + " \n" + locals.ToString(), ex);
            }
        }

        return(wait_res);
    }
Example #25
0
 public async Task <int> CreateEntity(string type, JObject attributes)
 {
     using (var db = await _data.Connect())
     {
         return(await db.ExecuteScalarAsync <int>(
                    @"insert into entity (`type`, `created`, `attributes`)
           values (@t, @c, @a);
           select LAST_INSERT_ID();",
                    new
         {
             t = type,
             c = DateTime.UtcNow,
             a = attributes?.ToString(Formatting.None)
         }));
     }
 }
Example #26
0
        /// <summary>
        /// The patch method that posts data to URL
        /// </summary>
        /// <typeparam name="T">the generic type parameter</typeparam>
        /// <param name="url">The url <see cref="string"/></param>
        /// <param name="jsonObject">The json content object<see cref="JObject"/></param>
        /// <param name="memberName">The member name<see cref="string"/></param>
        /// <param name="lineNumber">The line number<see cref="int"/></param>
        /// <param name="filePath">The filePath<see cref="string"/></param>
        /// <returns>The <see cref="T"/> object</returns>
        public T Patch <T>(string url, JObject jsonObject, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0, [CallerFilePath] string filePath = null) where T : class
        {
            var request = this.AddHttpRequestMessage(new HttpMethod("PATCH"),
                                                     jsonObject?.ToString(Formatting.Indented), url);

            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var response = this.Client.SendAsync(request).GetAwaiter().GetResult();

            stopwatch.Stop();

            return(this.DeserializeResponse <T>(url, request, response, stopwatch.ElapsedMilliseconds, memberName, lineNumber, filePath).GetAwaiter().GetResult());
        }
        public void Example()
        {
            #region Usage
            JObject videogameRatings = new JObject(
                new JProperty("Halo", 9),
                new JProperty("Starcraft", 9),
                new JProperty("Call of Duty", 7.5));

            File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());

            // write JSON directly to a file
            using (StreamWriter file = File.CreateText(@"c:\videogames.json"))
            using (JsonTextWriter writer = new JsonTextWriter(file))
            {
                videogameRatings.WriteTo(writer);
            }
            #endregion
        }
        public void Example()
        {
            #region Usage
            JArray array = new JArray();
            array.Add("Manual text");
            array.Add(new DateTime(2000, 5, 23));

            JObject o = new JObject();
            o["MyArray"] = array;

            string json = o.ToString();
            // {
            //   "MyArray": [
            //     "Manual text",
            //     "2000-05-23T00:00:00"
            //   ]
            // }
            #endregion
        }
Example #29
0
        public void AddModelTests()
        {
            string  json = ReflectionUtilities.GetResourceAsString("UnitTests.Core.ApsimFile.JsonUtilitiesTests.AddModelTests.json");
            JObject node = JObject.Parse(json);

            // Clock1 has an empty Children array, whereas clock2 does not have
            // a Children array. This test ensures that this does not matter.
            JObject clock1 = JsonUtilities.ChildWithName(node, "Clock1");
            JObject clock2 = JsonUtilities.ChildWithName(node, "Clock2");

            AddChildren(clock1);
            AddChildren(clock2);

            string clock2Name = clock2["Name"]?.ToString();

            clock2["Name"] = clock1["Name"]; // For comparison purposes.

            Assert.AreEqual(clock1, clock2, "Clock1:" + Environment.NewLine + clock1?.ToString() + Environment.NewLine + "Clock2:" + Environment.NewLine + clock2?.ToString());

            JObject nullJObject = null;
            IModel  nullModel   = null;
            Type    nullType    = null;
            string  nullString  = null;

            // JsonUtilities.AddModel(JObject, IModel)
            Assert.That(() => JsonUtilities.AddModel(nullJObject, new Clock()), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(clock1, nullModel), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, nullModel), Throws.InstanceOf <Exception>());

            // JsonUtilities.AddModel(JObject, Type)
            Assert.That(() => JsonUtilities.AddModel(nullJObject, typeof(Clock)), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(clock1, nullType), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, nullType), Throws.InstanceOf <Exception>());

            // JsonUtilities.AddModel(JObject, Type, string)
            Assert.That(() => JsonUtilities.AddModel(clock1, typeof(Clock), nullString), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(clock1, nullType, ""), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(clock1, nullType, nullString), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, typeof(Clock), ""), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, typeof(Clock), nullString), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, nullType, nullString), Throws.InstanceOf <Exception>());
            Assert.That(() => JsonUtilities.AddModel(nullJObject, nullType, ""), Throws.InstanceOf <Exception>());
        }
        private Post ParsePostItem(JObject _jPostItem, Func <VideoInfo, string> _loadVideoItem)
        {
            try
            {
                var post = new Post();

                post.SourceId    = _jPostItem[PSourceId].Value <int>();
                post.Date        = EpochTimeConverter.ConvertToDateTime(_jPostItem[PItemDate].Value <long>());
                post.PostId      = _jPostItem[PItemId].Value <int>();
                post.Text        = _jPostItem[PItemText].Value <string>();
                post.SignerId    = _jPostItem[PItemSignerId]?.Value <int>() ?? null;
                post.MarkedAsAds = _jPostItem[PItemMarkedAsAds].Value <int>() != 0;
                post.PostSource  = ParsePostSource((JObject)_jPostItem[PPostSource]);

                var attachmentsRaw = _jPostItem[PAttachments];
                if (attachmentsRaw != null)
                {
                    post.Attachments = ParseAttachments(attachmentsRaw, _loadVideoItem).ToArray();
                }

                post.Comments = ParseComments((JObject)_jPostItem[PComments]);
                post.Likes    = ParseLikes((JObject)_jPostItem[PLikes]);
                post.Reposts  = ParseReposts((JObject)_jPostItem[PReposts]);

                if (_jPostItem.ContainsKey(PViews))
                {
                    post.Views = ParseViews((JObject)_jPostItem[PViews]);
                }

                var rawHistoryElem = _jPostItem[PCopyHistrory];

                if (rawHistoryElem != null)
                {
                    post.CopyHistory = ParseHistory(rawHistoryElem, _loadVideoItem).ToArray();
                }

                return(post);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to parse post item \n {_jPostItem?.ToString()}", ex);
            }
        }
Example #31
0
        private HttpStatusCode PostData(Uri url, Config config)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = url;
                client.DefaultRequestHeaders.Add("User-Agent", config.UserAgent);

                var response = client.PostAsync(config.IngestionKey,
                                                new StringContent(JsonConvert.SerializeObject(config), Encoding.UTF8, "application/json")).Result;

                _result = response.IsSuccessStatusCode
                    ? JObject.Parse(response.Content.ReadAsStringAsync().Result)
                    : null;

                InternalLogger(_result?.ToString());

                return(response.StatusCode);
            }
        }
Example #32
0
 public IHttpActionResult FindClient([FromBody] JObject criteria)
 {
     try
     {
         var search = criteria["criteria"];
         if (search != null)
         {
             var searchCriteria = JsonConvert.DeserializeObject <ClientDto>(search.ToString());
             var results        = _clientService.Find(searchCriteria);
             return(Ok(results));
         }
         _log.Info($"Info : client search criteia is not in valid format  : {criteria?.ToString()}");
         return(BadRequest("Request body is not in correct format"));
     }
     catch (Exception e)
     {
         _log.Error($"Error : {e}");
         return(InternalServerError());
     }
 }
Example #33
0
        /// <summary>
        /// Given a structured lg result, create an activity.
        /// </summary>
        /// This method will create an MessageActivity from JToken
        /// <param name="lgJObj">lg output.</param>
        /// <returns>Activity for it.</returns>
        private static Activity BuildActivityFromLGStructuredResult(JObject lgJObj)
        {
            var activity = new Activity();
            var type     = GetStructureType(lgJObj);

            if (GenericCardTypeMapping.ContainsKey(type) ||
                type == nameof(Attachment).ToLowerInvariant())
            {
                activity = MessageFactory.Attachment(GetAttachment(lgJObj)) as Activity;
            }
            else if (type == nameof(Activity).ToLowerInvariant())
            {
                activity = BuildActivity(lgJObj);
            }
            else
            {
                activity = BuildActivityFromText(lgJObj?.ToString()?.Trim());
            }

            return(activity);
        }
Example #34
0
        public T Get(out bool remote_retreival)
        {
            JObject obj = this.RetrieveRemote();

            if (obj == null)
            {
                obj = this.RetrieveLocal();
                remote_retreival = false;
            }
            else
            {
                remote_retreival = true;
            }
            string result = string.IsNullOrWhiteSpace(this.Token) ? obj?.ToString() : obj?.SelectToken(this.Token).ToString();
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ObjectCreationHandling = ObjectCreationHandling.Reuse,
                MissingMemberHandling  = MissingMemberHandling.Ignore
            };

            return(JsonConvert.DeserializeObject <T>(result, settings));
        }
        public void CreatingJson()
        {
#if NETFX_CORE
            #region CreatingJSON
            // Windows.Data.Json
            // -----------------
            JsonObject jsonObject = new JsonObject
              {
                {"CPU", JsonValue.CreateStringValue("Intel")},
                {
                  "Drives", new JsonArray
                              {
                                JsonValue.CreateStringValue("DVD read/writer"),
                                JsonValue.CreateStringValue("500 gigabyte hard drive")
                              }
                }
              };
            string json1 = jsonObject.Stringify();

            // LINQ to JSON
            // ------------
            JObject jObject = new JObject
              {
                {"CPU", "Intel"},
                {
                  "Drives", new JArray
                              {
                                "DVD read/writer",
                                "500 gigabyte hard drive"
                              }
                }
              };
            string json2 = jObject.ToString();
            #endregion
#endif
        }
Example #36
0
        public void Example()
        {
            #region Usage
            JObject o1 = new JObject
            {
                { "String", "A string!" },
                { "Items", new JArray(1, 2) }
            };

            Console.WriteLine(o1.ToString());
            // {
            //   "String": "A string!",
            //   "Items": [
            //     1,
            //     2
            //   ]
            // }

            JObject o2 = (JObject)o1.DeepClone();

            Console.WriteLine(o2.ToString());
            // {
            //   "String": "A string!",
            //   "Items": [
            //     1,
            //     2
            //   ]
            // }

            Console.WriteLine(JToken.DeepEquals(o1, o2));
            // true

            Console.WriteLine(Object.ReferenceEquals(o1, o2));
            // false
            #endregion
        }
Example #37
0
        public void ReadOnlyConverterTest()
        {
            JObject o = new JObject(new JProperty("name", "Hello World"));

            string json = o.ToString(Formatting.Indented, new ReadOnlyStringConverter());

            StringAssert.Equal(@"{
  ""name"": ""Hello World""
}", json);
        }
Example #38
0
        /**
         * This is the lowest level request method. Use higher level if possible.
         */
        public JObject Request(string uri, string method, ClientType client, JObject parameters, JObject headerOverrides, RequestHandler handler, object state)
        {
            JObject request = new JObject();
            request.Add("parameters", parameters);
            JObject header = new JObject();
            if (m_token != null)
            {
                string t = GenerateToken(method);
                header.Add("token", t);
            }
            header.Add("session", m_sid);

            if (client == ClientType.HTML)
                header.Add("client", "htmlshark");
            else if (client == ClientType.JSQueue)
                header.Add("client", "jsqueue");
            else
                throw new Exception("ClientType not supported.");

            header.Add("clientRevision", "20101012.37");
            header.Add("privacy", 0);
            // Somehow this uuid is important, and I don't really know what it is, the UUID of the JSQueue flash object ?
            header.Add("uuid", "6BFBFCDE-B44F-4EC5-AF69-76CCC4A2DAD0");
            header.Add("country", m_countryObj);
            request.Add("header", header);
            request.Add("method", method);

            if (headerOverrides != null)
            {
                IDictionaryEnumerator e = headerOverrides.GetEnumerator();
                while (e.MoveNext())
                {
                    if (header.ContainsKey(e.Key))
                        header[e.Key] = e.Value;
                    else
                        header.Add(e.Key, e.Value);
                }
            }
            string requestStr = request.ToString().Replace("\n", "").Replace(" ", "").Replace("\r", "");
            CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
            wc.UploadStringCompleted += new UploadStringCompletedEventHandler(GSRequestHandler);
            wc.UploadStringAsync(new Uri(uri + "?" + method), "POST", requestStr, new object[]{ handler, state });
            if(RequestSent != null)
                RequestSent(this, requestStr);
            return request;
        }
Example #39
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     json["hex"] = Signable.ToUnsignedArray().ToHexString();
     JArray multisignatures = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             multisignatures.Add(null);
         }
         else
         {
             multisignatures.Add(new JObject());
             multisignatures[i]["redeem_script"] = signatures[i].redeemScript.ToHexString();
             JArray sigs = new JArray();
             for (int j = 0; j < signatures[i].signatures.Length; j++)
             {
                 if (signatures[i].signatures[j] == null)
                 {
                     sigs.Add(null);
                 }
                 else
                 {
                     sigs.Add(signatures[i].signatures[j].ToHexString());
                 }
             }
             multisignatures[i]["signatures"] = sigs;
         }
     }
     json["multi_signatures"] = multisignatures;
     return json.ToString();
 }
Example #40
0
        /// <summary>
        /// Converts the value received from the editor into the value can be stored in the database.
        /// </summary>
        /// <param name="editorValue">The value received from the editor.</param>
        /// <param name="currentValue">The current value of the property</param>
        /// <returns>The converted value.</returns>
        /// <remarks>
        /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
        /// <para>editorValue.Value is used to figure out editorFile and, if it has been cleared, remove the old file - but
        /// it is editorValue.AdditionalData["files"] that is used to determine the actual file that has been uploaded.</para>
        /// </remarks>
        public override object FromEditor(ContentPropertyData editorValue, object currentValue)
        {
            // get the current path
            var currentPath = string.Empty;

            try
            {
                var svalue      = currentValue as string;
                var currentJson = string.IsNullOrWhiteSpace(svalue) ? null : JObject.Parse(svalue);
                if (currentJson != null && currentJson["src"] != null)
                {
                    currentPath = currentJson["src"].Value <string>();
                }
            }
            catch (Exception ex)
            {
                // for some reason the value is invalid so continue as if there was no value there
                _logger.Warn <ImageCropperPropertyValueEditor>(ex, "Could not parse current db value to a JObject.");
            }
            if (string.IsNullOrWhiteSpace(currentPath) == false)
            {
                currentPath = _mediaFileSystem.GetRelativePath(currentPath);
            }

            // get the new json and path
            JObject editorJson = null;
            var     editorFile = string.Empty;

            if (editorValue.Value != null)
            {
                editorJson = editorValue.Value as JObject;
                if (editorJson != null && editorJson["src"] != null)
                {
                    editorFile = editorJson["src"].Value <string>();
                }
            }

            // ensure we have the required guids
            var cuid = editorValue.ContentKey;

            if (cuid == Guid.Empty)
            {
                throw new Exception("Invalid content key.");
            }
            var puid = editorValue.PropertyTypeKey;

            if (puid == Guid.Empty)
            {
                throw new Exception("Invalid property type key.");
            }

            // editorFile is empty whenever a new file is being uploaded
            // or when the file is cleared (in which case editorJson is null)
            // else editorFile contains the unchanged value

            var uploads = editorValue.Files;

            if (uploads == null)
            {
                throw new Exception("Invalid files.");
            }
            var file = uploads.Length > 0 ? uploads[0] : null;

            if (file == null) // not uploading a file
            {
                // if editorFile is empty then either there was nothing to begin with,
                // or it has been cleared and we need to remove the file - else the
                // value is unchanged.
                if (string.IsNullOrWhiteSpace(editorFile) && string.IsNullOrWhiteSpace(currentPath) == false)
                {
                    _mediaFileSystem.DeleteFile(currentPath);
                    return(null); // clear
                }

                return(editorJson?.ToString()); // unchanged
            }

            // process the file
            var filepath = editorJson == null ? null : ProcessFile(editorValue, file, currentPath, cuid, puid);

            // remove all temp files
            foreach (var f in uploads)
            {
                File.Delete(f.TempFilePath);
            }

            // remove current file if replaced
            if (currentPath != filepath && string.IsNullOrWhiteSpace(currentPath) == false)
            {
                _mediaFileSystem.DeleteFile(currentPath);
            }

            // update json and return
            if (editorJson == null)
            {
                return(null);
            }
            editorJson["src"] = filepath == null ? string.Empty : _mediaFileSystem.GetUrl(filepath);
            return(editorJson.ToString());
        }
Example #41
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     using (MemoryStream ms = new MemoryStream())
     using (BinaryWriter writer = new BinaryWriter(ms, Encoding.UTF8))
     {
         Signable.SerializeUnsigned(writer);
         writer.Flush();
         json["hex"] = ms.ToArray().ToHexString();
     }
     JArray scripts = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             scripts.Add(null);
         }
         else
         {
             scripts.Add(new JObject());
             scripts[i]["redeem_script"] = redeemScripts[i].ToHexString();
             JArray sigs = new JArray();
             foreach (var pair in signatures[i])
             {
                 JObject signature = new JObject();
                 signature["pubkey"] = pair.Key.EncodePoint(true).ToHexString();
                 signature["signature"] = pair.Value.ToHexString();
                 sigs.Add(signature);
             }
             scripts[i]["signatures"] = sigs;
             scripts[i]["completed"] = completed[i];
         }
     }
     json["scripts"] = scripts;
     return json.ToString();
 }
Example #42
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     using (MemoryStream ms = new MemoryStream())
     using (BinaryWriter writer = new BinaryWriter(ms, Encoding.UTF8))
     {
         Signable.SerializeUnsigned(writer);
         writer.Flush();
         json["hex"] = ms.ToArray().ToHexString();
     }
     JArray multisignatures = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             multisignatures.Add(null);
         }
         else
         {
             multisignatures.Add(new JObject());
             multisignatures[i]["redeem_script"] = signatures[i].redeemScript.ToHexString();
             JArray sigs = new JArray();
             for (int j = 0; j < signatures[i].signatures.Length; j++)
             {
                 if (signatures[i].signatures[j] == null)
                 {
                     sigs.Add(null);
                 }
                 else
                 {
                     sigs.Add(signatures[i].signatures[j].ToHexString());
                 }
             }
             multisignatures[i]["signatures"] = sigs;
         }
     }
     json["multi_signatures"] = multisignatures;
     return json.ToString();
 }
Example #43
0
    public void CreateJTokenTreeNested()
    {
      List<Post> posts = GetPosts();

      JObject rss =
        new JObject(
          new JProperty("channel",
            new JObject(
              new JProperty("title", "James Newton-King"),
              new JProperty("link", "http://james.newtonking.com"),
              new JProperty("description", "James Newton-King's blog."),
              new JProperty("item",
                new JArray(
                  from p in posts
                  orderby p.Title
                  select new JObject(
                    new JProperty("title", p.Title),
                    new JProperty("description", p.Description),
                    new JProperty("link", p.Link),
                    new JProperty("category",
                      new JArray(
                        from c in p.Categories
                        select new JValue(c)))))))));

      Console.WriteLine(rss.ToString());

      //{
      //  "channel": {
      //    "title": "James Newton-King",
      //    "link": "http://james.newtonking.com",
      //    "description": "James Newton-King's blog.",
      //    "item": [
      //      {
      //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
      //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
      //        "category": [
      //          "Json.NET",
      //          "CodePlex"
      //        ]
      //      },
      //      {
      //        "title": "LINQ to JSON beta",
      //        "description": "Annoucing LINQ to JSON",
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
      //        "category": [
      //          "Json.NET",
      //          "LINQ"
      //        ]
      //      }
      //    ]
      //  }
      //}

      var postTitles =
        from p in rss["channel"]["item"]
        select p.Value<string>("title");

      foreach (var item in postTitles)
      {
        Console.WriteLine(item);
      }

      //LINQ to JSON beta
      //Json.NET 1.3 + New license + Now on CodePlex

      var categories =
        from c in rss["channel"]["item"].Children()["category"].Values<string>()
        group c by c into g
        orderby g.Count() descending
        select new { Category = g.Key, Count = g.Count() };

      foreach (var c in categories)
      {
        Console.WriteLine(c.Category + " - Count: " + c.Count);
      }

      //Json.NET - Count: 2
      //LINQ - Count: 1
      //CodePlex - Count: 1
    }
Example #44
0
    public void ArrayOrder()
    {
      string itemZeroText = "Zero text";

      IEnumerable<ListItemFields> t = new List<ListItemFields>
        {
          new ListItemFields {ListItemText = "First", ListItemValue = 1},
          new ListItemFields {ListItemText = "Second", ListItemValue = 2},
          new ListItemFields {ListItemText = "Third", ListItemValue = 3}
        };

      JObject optionValues =
        new JObject(
          new JProperty("options",
                        new JArray(
                          new JObject(
                            new JProperty("text", itemZeroText),
                            new JProperty("value", "0")),
                          from r in t
                          orderby r.ListItemValue
                          select new JObject(
                            new JProperty("text", r.ListItemText),
                            new JProperty("value", r.ListItemValue.ToString())))));

      string result = "myOptions = " + optionValues.ToString();

      Assert.AreEqual(@"myOptions = {
  ""options"": [
    {
      ""text"": ""Zero text"",
      ""value"": ""0""
    },
    {
      ""text"": ""First"",
      ""value"": ""1""
    },
    {
      ""text"": ""Second"",
      ""value"": ""2""
    },
    {
      ""text"": ""Third"",
      ""value"": ""3""
    }
  ]
}", result);
    }
Example #45
0
        public void RawChildValues()
        {
            var o = new JObject();
            o["val1"] = new JRaw("1");
            o["val2"] = new JRaw("1");

            string json = o.ToString();

            StringAssert.Equal(@"{
  ""val1"": 1,
  ""val2"": 1
}", json);
        }
Example #46
0
        public void CreateJTokenTreeNested()
        {
            List<Post> posts = GetPosts();

            JObject rss =
                new JObject(
                    new JProperty("channel",
                        new JObject(
                            new JProperty("title", "James Newton-King"),
                            new JProperty("link", "http://james.newtonking.com"),
                            new JProperty("description", "James Newton-King's blog."),
                            new JProperty("item",
                                new JArray(
                                    from p in posts
                                    orderby p.Title
                                    select new JObject(
                                        new JProperty("title", p.Title),
                                        new JProperty("description", p.Description),
                                        new JProperty("link", p.Link),
                                        new JProperty("category",
                                            new JArray(
                                                from c in p.Categories
                                                select new JValue(c)))))))));

            StringAssert.AreEqual(@"{
  ""channel"": {
    ""title"": ""James Newton-King"",
    ""link"": ""http://james.newtonking.com"",
    ""description"": ""James Newton-King's blog."",
    ""item"": [
      {
        ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
        ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex"",
        ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
        ""category"": [
          ""Json.NET"",
          ""CodePlex""
        ]
      },
      {
        ""title"": ""LINQ to JSON beta"",
        ""description"": ""Annoucing LINQ to JSON"",
        ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
        ""category"": [
          ""Json.NET"",
          ""LINQ""
        ]
      }
    ]
  }
}", rss.ToString());

            var postTitles =
                from p in rss["channel"]["item"]
                select p.Value<string>("title");

            Assert.AreEqual("Json.NET 1.3 + New license + Now on CodePlex", postTitles.ElementAt(0));
            Assert.AreEqual("LINQ to JSON beta", postTitles.ElementAt(1));

            var categories =
                from c in rss["channel"]["item"].Children()["category"].Values<string>()
                group c by c
                into g
                orderby g.Count() descending
                select new { Category = g.Key, Count = g.Count() };

            Assert.AreEqual("Json.NET", categories.ElementAt(0).Category);
            Assert.AreEqual(2, categories.ElementAt(0).Count);
            Assert.AreEqual("CodePlex", categories.ElementAt(1).Category);
            Assert.AreEqual(1, categories.ElementAt(1).Count);
            Assert.AreEqual("LINQ", categories.ElementAt(2).Category);
            Assert.AreEqual(1, categories.ElementAt(2).Count);
        }
Example #47
0
        public void WriteObjectNullStringValue()
        {
            string s = null;
            JValue v = new JValue(s);
            Assert.Equal(null, v.Value);
            Assert.Equal(JTokenType.String, v.Type);

            var o = new JObject();
            o["title"] = v;

            string output = o.ToString();

            StringAssert.Equal(@"{
  ""title"": null
}", output);
        }
Example #48
0
        public void JObjectContainingHtml()
        {
            var o = new JObject();
            o["rc"] = new JValue(200);
            o["m"] = new JValue("");
            o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>");

            StringAssert.Equal(@"{
  ""rc"": 200,
  ""m"": """",
  ""o"": ""<div class='s1'>\r\n</div>""
}", o.ToString());
        }
Example #49
0
        public void ImplicitValueConversions()
        {
            JObject moss = new JObject();
            moss["FirstName"] = new JValue("Maurice");
            moss["LastName"] = new JValue("Moss");
            moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
            moss["Department"] = new JValue("IT");
            moss["JobTitle"] = new JValue("Support");

            Console.WriteLine(moss.ToString());
            //{
            //  "FirstName": "Maurice",
            //  "LastName": "Moss",
            //  "BirthDate": "\/Date(252241200000+1300)\/",
            //  "Department": "IT",
            //  "JobTitle": "Support"
            //}


            JObject jen = new JObject();
            jen["FirstName"] = "Jen";
            jen["LastName"] = "Barber";
            jen["BirthDate"] = new DateTime(1978, 3, 15);
            jen["Department"] = "IT";
            jen["JobTitle"] = "Manager";

            Console.WriteLine(jen.ToString());
            //{
            //  "FirstName": "Jen",
            //  "LastName": "Barber",
            //  "BirthDate": "\/Date(258721200000+1300)\/",
            //  "Department": "IT",
            //  "JobTitle": "Manager"
            //}
        }
Example #50
0
        void m_gs_LoggedIn(object sender, JObject user)
        {
            log("Logged in as: " + user.ToString());

            if ((double)user["userID"] == 0.0)
            {
                MessageBox.Show(this, "Check your username and password.", "O-oh! Can't log in", MessageBoxButtons.OK, MessageBoxIcon.Error);

                connectB.Enabled = true;
                connectB.Text = "log-in";
                return;
            }

            connectB.Text = "getting playlists";
            m_gs.GetPlaylists();
        }
    public void JObjectContainingHtml()
    {
      JObject o = new JObject();
      o["rc"] = new JValue(200);
      o["m"] = new JValue("");
      o["o"] = new JValue(@"<div class='s1'>
    <div class='avatar'>                    
        <a href='asdf'>asdf</a><br />
        <strong>0</strong>
    </div>
    <div class='sl'>
        <p>
            444444444
        </p>
    </div>
    <div class='clear'>
    </div>                        
</div>");

      Assert.AreEqual(@"{
  ""rc"": 200,
  ""m"": """",
  ""o"": ""<div class='s1'>\r\n    <div class='avatar'>                    \r\n        <a href='asdf'>asdf</a><br />\r\n        <strong>0</strong>\r\n    </div>\r\n    <div class='sl'>\r\n        <p>\r\n            444444444\r\n        </p>\r\n    </div>\r\n    <div class='clear'>\r\n    </div>                        \r\n</div>""
}", o.ToString());
    }
Example #52
0
    public void CreateJTokenTree()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", "Test1Value"),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(4, o.Properties().Count());

      Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

      JArray a =
        new JArray(
          o,
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
          55,
          new JArray(
            "1",
            2,
            3.0,
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
          ),
          new JConstructor(
            "ConstructorName",
            "param1",
            2,
            3.0
          )
        );

      Assert.AreEqual(5, a.Count());
      Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""2000-10-10T00:00:00Z"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""0004-05-06T07:08:09Z""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
    }
Example #53
0
        public static object Invoke(MethodInfo methodInfo, JObject json)
        {
            ParameterInfo[] paramterInfos = methodInfo.GetParameters();
            var type = methodInfo.DeclaringType;

            object[] paramters = new object[paramterInfos.Length];
            try
            {
                for (int i = 0; i < paramterInfos.Length; i++)
                {
                    Type parameterType = paramterInfos[i].ParameterType;
                    string parameterName = paramterInfos[i].Name;
                    object value = null;
                    JToken jvalue = null;

                    if (json.TryGetValue(parameterName, StringComparison.OrdinalIgnoreCase, out jvalue))
                    {
                        if (parameterType == typeof(string))
                            value = jvalue.ToString();
                        else
                            value = jvalue.ToObject(parameterType);

                    }
                    else
                    {
                        if (parameterType == typeof(string))
                            value = json.ToString();
                        else
                            value = json.ToObject(parameterType);

                    }
                    paramters[i] = value;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("解析方法'" + type.FullName + "." + methodInfo.Name + "'参数出错,请检查传入参数!\n出错信息:" + ex.Message, ex);
            }
            try
            {
                object instance = null;
                if (!methodInfo.IsStatic)
                    instance = Activator.CreateInstance(type, new object[] { });
                return methodInfo.Invoke(instance, paramters);
            }
            catch (Exception ex)
            {
                throw new Exception("调用方法'" + type.FullName + "." + methodInfo.Name + "'失败\n出错信息:" + ex.Message, ex);
            }
        }
Example #54
0
        // 好像坏掉了


        /// <summary>
        /// Search
        /// </summary>
        /// <param name="image">Base64 Encoded Image</param>
        /// <param name="filter">Limit search in specific year / season</param>
        /// <returns></returns>
        internal static async Task <JObject> SearchAsync(string image, string filter = "")
        {
            JObject result = null;

            try
            {
                if (!Cooldown.CanSearch)
                {
                    throw new ApplicationException($"全局冷却中: 剩余 {Cooldown.RemainingSeconds} 秒");
                }
                result = JObject.Parse(await RequestStringAsync($"/api/search?token={ApiToken}", $"image={image}" + (filter == "" ? "" : "&filter=" + filter)));
                Cooldown.SetCooldown(result["quota"].ToObject <int>(), result["expire"].ToObject <int>());
                return(result);
            }
            catch (WebException we)
            {
                switch ((int)(we.Response as HttpWebResponse).StatusCode)
                {
                case 429:
                    Cooldown.TriggeredHTTP429();
                    break;
                }
                CoolQApi.AddLog(CoolQApi.LogLevel.Debug, "ErrorDebug", "Search Result: " + result?.ToString(Newtonsoft.Json.Formatting.None) ?? "[NULL]");
                throw;
            }
        }
Example #55
0
        public void WriteObjectNullDBNullValue()
        {
            DBNull dbNull = DBNull.Value;
            JValue v = new JValue(dbNull);
            Assert.Equal(DBNull.Value, v.Value);
            Assert.Equal(JTokenType.Null, v.Type);

            var o = new JObject();
            o["title"] = v;

            string output = o.ToString();

            StringAssert.Equal(@"{
  ""title"": null
}", output);
        }