public PlainScript(IAsset asset, Bundle bundle, IAmdConfiguration modules) : base(asset, bundle) { this.modules = modules; jsonSerializer = new SimpleJsonSerializer(); asset.AddAssetTransformer(this); }
public PlainScript(IAsset asset, Bundle bundle, IModuleInitializer modules,string baseUrl = null) : base(asset, bundle, baseUrl) { this.modules = modules; jsonSerializer = new SimpleJsonSerializer(); asset.AddAssetTransformer(this); }
public async Task<List<Showcase>> GetShowcases() { var url = string.Format(ShowcaseUrl, string.Empty); var data = await BlobCache.LocalMachine.DownloadUrl(url, absoluteExpiration: DateTimeOffset.Now.AddDays(1)); var serializer = new SimpleJsonSerializer(); return serializer.Deserialize<List<Showcase>>(Encoding.UTF8.GetString(data)); }
public void CanSerialize() { var expected = "{\"name\":\"Hello-World\"," + "\"description\":\"This is your first repository\"," + "\"homepage\":\"https://github.com\"," + "\"private\":true," + "\"has_issues\":true," + "\"has_wiki\":true," + "\"has_downloads\":true}"; var update = new RepositoryUpdate { Name = "Hello-World", Description = "This is your first repository", Homepage = "https://github.com", Private = true, HasIssues = true, HasWiki = true, HasDownloads = true }; var json = new SimpleJsonSerializer().Serialize(update); Assert.Equal(expected, json); }
public void HandleUnicodeCharacters() { const string backspace = "\b"; const string tab = "\t"; var sb = new StringBuilder(); sb.Append("My name has Unicode characters"); Enumerable.Range(0, 19).Select(e => System.Convert.ToChar(e)) .Aggregate(sb, (a, b) => a.Append(b)); sb.Append(backspace).Append(tab); var data = sb.ToString(); var json = new SimpleJsonSerializer().Serialize(data); var lastTabCharacter = json .Reverse() .Skip(1) .Take(2) .Reverse() .Aggregate(new StringBuilder(), (a, b) => a.Append(b)); var deserializeData = new SimpleJsonSerializer().Deserialize<string>(json); Assert.True(lastTabCharacter.ToString().Equals("\\t")); Assert.Equal(data, deserializeData); }
public void UsesRubyCasing() { var item = new Sample { Id = 42, FirstName = "Phil", IsSomething = true, Private = true }; var json = new SimpleJsonSerializer().Serialize(item); Assert.Equal("{\"id\":42,\"first_name\":\"Phil\",\"is_something\":true,\"private\":true}", json); }
public async Task<List<Octokit.Repository>> GetTrendingRepositories(string since, string language = null) { var query = "?since=" + since; if (!string.IsNullOrEmpty(language)) query += string.Format("&language={0}", language); var data = await BlobCache.LocalMachine.DownloadUrl(TrendingUrl + query, absoluteExpiration: DateTimeOffset.Now.AddHours(1)); var serializer = new SimpleJsonSerializer(); return serializer.Deserialize<List<Octokit.Repository>>(Encoding.UTF8.GetString(data)); }
public void UnderstandsRubyCasing() { const string json = "{\"id\":42,\"first_name\":\"Phil\",\"is_something\":true,\"private\":true}"; var sample = new SimpleJsonSerializer().Deserialize<Sample>(json); Assert.Equal(42, sample.Id); Assert.Equal("Phil", sample.FirstName); Assert.True(sample.IsSomething); Assert.True(sample.Private); }
public void CanBeDeserialized() { var serializer = new SimpleJsonSerializer(); var apiError = serializer.Deserialize<ApiError>(json); Assert.Equal("Validation Failed", apiError.Message); Assert.Equal(1, apiError.Errors.Count); Assert.Equal("Issue", apiError.Errors[0].Resource); Assert.Equal("title", apiError.Errors[0].Field); Assert.Equal("missing_field", apiError.Errors[0].Code); }
public async Task<IList<GitHubSharp.Models.RepositoryModel>> GetTrendingRepositories(string since, string language = null) { var query = "?since=" + since; if (!string.IsNullOrEmpty(language)) query += string.Format("&language={0}", language); var client = new HttpClient(); var serializer = new SimpleJsonSerializer(); var msg = await client.GetAsync(TrendingUrl + query).ConfigureAwait(false); var content = await msg.Content.ReadAsStringAsync().ConfigureAwait(false); return serializer.Deserialize<List<GitHubSharp.Models.RepositoryModel>>(content); }
public void DoesNotOmitsNullablePropertiesWithAValue() { var item = new { Object = new { Id = 42 }, NullableInt = (int?)1066, NullableBool = (bool?)true }; var json = new SimpleJsonSerializer().Serialize(item); Assert.Equal("{\"object\":{\"id\":42},\"nullable_int\":1066,\"nullable_bool\":true}", json); }
public void HandlesBase64EncodedStrings() { var item = new SomeObject { Name = "Ferris Bueller", Content = "Day off", Description = "stuff" }; var json = new SimpleJsonSerializer().Serialize(item); Assert.Equal("{\"name\":\"RmVycmlzIEJ1ZWxsZXI=\",\"description\":\"stuff\",\"content\":\"RGF5IG9mZg==\"}", json); }
public void OmitsPropertiesWithNullValue() { var item = new { Object = (object)null, NullableInt = (int?)null, NullableBool = (bool?)null }; var json = new SimpleJsonSerializer().Serialize(item); Assert.Equal("{}", json); }
public void HandlesMixingNullAndNotNullData() { var item = new { Int = 42, Bool = true, NullableInt = (int?)null, NullableBool = (bool?)null }; var json = new SimpleJsonSerializer().Serialize(item); Assert.Equal("{\"int\":42,\"bool\":true}", json); }
public void CanBeDeserializedWithNullPrivateGistsDiskUsageAndCollaborators() { const string json = @"{ ""login"": ""octocat"", ""id"": 1234, ""url"": ""https://api.github.com/orgs/octocat"", ""repos_url"": ""https://api.github.com/orgs/octocat/repos"", ""events_url"": ""https://api.github.com/orgs/octocat/events"", ""hooks_url"": ""https://api.github.com/orgs/octocat/hooks"", ""issues_url"": ""https://api.github.com/orgs/octocat/issues"", ""members_url"": ""https://api.github.com/orgs/octocat/members{/member}"", ""public_members_url"": ""https://api.github.com/orgs/octocat/public_members{/member}"", ""avatar_url"": ""https://avatars.githubusercontent.com/u/1234?v=3"", ""description"": ""Test org."", ""name"": ""Octocat"", ""company"": null, ""blog"": ""http://octocat.abc"", ""location"": """", ""email"": """", ""public_repos"": 13, ""public_gists"": 0, ""followers"": 0, ""following"": 0, ""html_url"": ""https://github.com/octocat"", ""created_at"": ""2012-09-11T21:54:25Z"", ""updated_at"": ""2016-08-02T05:44:12Z"", ""type"": ""Organization"", ""total_private_repos"": 1, ""owned_private_repos"": 1, ""private_gists"": null, ""disk_usage"": null, ""collaborators"": null, ""billing_email"": null, ""plan"": { ""name"": ""organization"", ""space"": 976562499, ""private_repos"": 9999, ""filled_seats"": 45, ""seats"": 45 } }"; var serializer = new SimpleJsonSerializer(); var org = serializer.Deserialize<Organization>(json); Assert.Equal("octocat", org.Login); Assert.Equal(1234, org.Id); }
public void CanBeDeserialized() { const string json = @"{ ""total_count"": 40, ""incomplete_results"": false, ""items"": [ { ""id"": 3081286, ""name"": ""Tetris"", ""full_name"": ""dtrupenn/Tetris"", ""owner"": { ""login"": ""dtrupenn"", ""id"": 872147, ""avatar_url"": ""https://secure.gravatar.com/avatar/e7956084e75f239de85d3a31bc172ace?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/dtrupenn"", ""received_events_url"": ""https://api.github.com/users/dtrupenn/received_events"", ""type"": ""User"" }, ""private"": false, ""html_url"": ""https://github.com/dtrupenn/Tetris"", ""description"": ""A C implementation of Tetris using Pennsim through LC4"", ""fork"": false, ""url"": ""https://api.github.com/repos/dtrupenn/Tetris"", ""created_at"": ""2012-01-01T00:31:50Z"", ""updated_at"": ""2013-01-05T17:58:47Z"", ""pushed_at"": ""2012-01-01T00:37:02Z"", ""homepage"": """", ""size"": 524, ""stargazers_count"": 1, ""watchers_count"": 1, ""language"": ""Assembly"", ""forks_count"": 0, ""open_issues_count"": 0, ""master_branch"": ""master"", ""default_branch"": ""master"", ""score"": 10.309712 } ] }"; var serializer = new SimpleJsonSerializer(); var results = serializer.Deserialize<SearchRepositoryResult>(json); Assert.Equal(40, results.TotalCount); Assert.False(results.IncompleteResults); }
public void CanDeserialize() { const string json = @"{ ""id"": 1, ""url"": ""https://api.github.com/repos/octocat/example/deployments/1/statuses/42"", ""state"": ""success"", ""creator"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": ""somehexcode"", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""payload"": { ""environment"":""production""}, ""target_url"": ""https://gist.github.com/628b2736d379f"", ""created_at"": ""2012-07-20T01:19:13Z"", ""updated_at"": ""2012-07-20T01:19:13Z"", ""description"": ""Deploy request from hubot"" }"; var actual = new SimpleJsonSerializer().Deserialize<DeploymentStatus>(json); Assert.Equal(1, actual.Id); Assert.Equal("https://api.github.com/repos/octocat/example/deployments/1/statuses/42", actual.Url); Assert.Equal(DeploymentState.Success, actual.State); Assert.Equal(1, actual.Payload.Count); Assert.Equal("production", actual.Payload["environment"]); Assert.Equal("https://gist.github.com/628b2736d379f", actual.TargetUrl); Assert.Equal(DateTimeOffset.Parse("2012-07-20T01:19:13Z"), actual.CreatedAt); Assert.Equal(DateTimeOffset.Parse("2012-07-20T01:19:13Z"), actual.UpdatedAt); Assert.Equal("Deploy request from hubot", actual.Description); }
public void CanBeDeserializedFromLicenseJson() { const string json = @"{ ""key"": ""mit"", ""name"": ""MIT License"", ""spdx_id"": ""MIT"", ""url"": ""https://api.github.com/licenses/mit"", ""featured"": true }"; var serializer = new SimpleJsonSerializer(); var license = serializer.Deserialize <LicenseMetadata>(json); Assert.Equal("mit", license.Key); Assert.Equal("MIT License", license.Name); Assert.Equal("MIT", license.SpdxId); Assert.Equal("https://api.github.com/licenses/mit", license.Url); Assert.True(license.Featured); }
public void CanDeserialize() { const string json = @"{ ""id"": 1, ""sha"": ""topic-branch"", ""url"": ""https://api.github.com/repos/octocat/example/deployments/1"", ""creator"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": ""somehexcode"", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""payload"": { ""environment"":""production""}, ""created_at"": ""2012-07-20T01:19:13Z"", ""updated_at"": ""2012-07-20T01:19:13Z"", ""description"": ""Deploy request from hubot"", ""statuses_url"": ""https://api.github.com/repos/octocat/example/deployments/1/statuses"" }"; var actual = new SimpleJsonSerializer().Deserialize<Deployment>(json); Assert.Equal(1, actual.Id); Assert.Equal("topic-branch", actual.Sha); Assert.Equal("https://api.github.com/repos/octocat/example/deployments/1", actual.Url); Assert.Equal(new ReadOnlyDictionary<string, string>(new Dictionary<string, string> { { "environment", "production" } }), actual.Payload); Assert.Equal(DateTimeOffset.Parse("2012-07-20T01:19:13Z"), actual.CreatedAt); Assert.Equal(DateTimeOffset.Parse("2012-07-20T01:19:13Z"), actual.UpdatedAt); Assert.Equal("Deploy request from hubot", actual.Description); Assert.Equal("https://api.github.com/repos/octocat/example/deployments/1/statuses", actual.StatusesUrl); }
public void ShouldDeserializeParentTeamWithNullPermission() { var teamJson = @"{ ""id"": 1, ""node_id"": ""MDQ6VGVhbTE="", ""url"": ""https://api.github.com/teams/1"", ""html_url"": ""https://api.github.com/teams/justice-league"", ""name"": ""Justice League"", ""slug"": ""justice-league"", ""description"": ""A great team."", ""privacy"": ""closed"", ""permission"": ""admin"", ""members_url"": ""https://api.github.com/teams/1/members{/member}"", ""repositories_url"": ""https://api.github.com/teams/1/repos"", ""parent"": { ""id"": 1, ""node_id"": ""MDQ6LFJSbTE="", ""url"": ""https://api.github.com/teams/2"", ""html_url"": ""https://api.github.com/teams/super-friends"", ""name"": ""Super Friends"", ""slug"": ""super-friends"", ""description"": ""Also a great team."", ""privacy"": ""closed"", ""permission"": null, ""members_url"": ""https://api.github.com/teams/2/members{/member}"", ""repositories_url"": ""https://api.github.com/teams/2/repos"", } } }"; var result = new SimpleJsonSerializer().Deserialize <Team>(teamJson); // original value works as expected Assert.Equal(PermissionLevel.Admin, result.Permission.Value); Assert.Equal("admin", result.Permission.StringValue); // parent permission is marked as null and cannot be parsed Assert.Equal("null", result.Parent.Permission.StringValue); PermissionLevel value; Assert.False(result.Parent.Permission.TryParse(out value)); }
public void ParseWebhookEvent(string action, string data) { try { switch (action) { case "pull_request": var pullRequest = new SimpleJsonSerializer().Deserialize <PullRequestEventPayload>(data); UpdatePullRequest(pullRequest?.PullRequest); break; case "pull_request_review": var pullRequestReview = new SimpleJsonSerializer().Deserialize <PullRequestReviewEventPayload>(data); UpdatePullRequestReview(pullRequestReview?.PullRequest, pullRequestReview?.Review); break; case "create": var branchCreate = new SimpleJsonSerializer().Deserialize <BranchEventPayload>(data); UpdateBranch(branchCreate?.Ref, branchCreate?.Repository.FullName); break; case "delete": var branchDelete = new SimpleJsonSerializer().Deserialize <BranchEventPayload>(data); DeleteBranch(branchDelete?.Ref, branchDelete?.Repository.FullName); break; default: Log?.Invoke(this, new GithubLogEventArgs { Data = new { action, data } }); break; } } catch (Exception e) { Log?.Invoke(this, new GithubLogEventArgs { Data = e }); } }
public void CanDeserializeOrganization() { const string json = "{" + "\"login\": \"mono\"," + "\"id\": 53395," + "\"avatar_url\": \"https://avatars.githubusercontent.com/u/53395?\"," + "\"gravatar_id\": \"f275a99c0b4e6044d3e81daf445f8174\"," + "\"url\": \"https://api.github.com/users/mono\"," + "\"html_url\": \"https://github.com/mono\"," + "\"followers_url\": \"https://api.github.com/users/mono/followers\"," + "\"following_url\": \"https://api.github.com/users/mono/following{/other_user}\"," + "\"gists_url\": \"https://api.github.com/users/mono/gists{/gist_id}\"," + "\"starred_url\": \"https://api.github.com/users/mono/starred{/owner}{/repo}\"," + "\"subscriptions_url\": \"https://api.github.com/users/mono/subscriptions\"," + "\"organizations_url\": \"https://api.github.com/users/mono/orgs\"," + "\"repos_url\": \"https://api.github.com/users/mono/repos\"," + "\"events_url\": \"https://api.github.com/users/mono/events{/privacy}\"," + "\"received_events_url\": \"https://api.github.com/users/mono/received_events\"," + "\"type\": \"Organization\"," + "\"site_admin\": false," + "\"name\": \"Mono Project\"," + "\"company\": null," + "\"blog\": \"http://mono-project.com\"," + "\"location\": \"Boston, MA\"," + "\"email\": \"[email protected]\"," + "\"hireable\": null," + "\"bio\": null," + "\"public_repos\": 161," + "\"public_gists\": 0," + "\"followers\": 0," + "\"following\": 0," + "\"created_at\": \"2009-02-10T17:53:17Z\"," + "\"updated_at\": 1404691976" + "}"; var result = new SimpleJsonSerializer().Deserialize <User>(json); Assert.Equal("Mono Project", result.Name); Assert.Null(result.Hireable); Assert.Equal(new DateTimeOffset(2009, 02, 10, 17, 53, 17, TimeSpan.Zero), result.CreatedAt); Assert.Equal(new DateTimeOffset(2014, 07, 07, 00, 12, 56, TimeSpan.Zero), result.UpdatedAt); }
public void DeserializesEnumWithParameterAttribute() { const string json1 = @"{""some_enum"":""+1""}"; const string json2 = @"{""some_enum"":""utf-8""}"; const string json3 = @"{""some_enum"":""something else""}"; const string json4 = @"{""some_enum"":""another_example""}"; const string json5 = @"{""some_enum"":""unicode""}"; var sample1 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json1); var sample2 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json2); var sample3 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json3); var sample4 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json4); var sample5 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json5); Assert.Equal(SomeEnum.PlusOne, sample1.SomeEnum); Assert.Equal(SomeEnum.Utf8, sample2.SomeEnum); Assert.Equal(SomeEnum.SomethingElse, sample3.SomeEnum); Assert.Equal(SomeEnum.AnotherExample, sample4.SomeEnum); Assert.Equal(SomeEnum.Unicode, sample5.SomeEnum); }
/// <inheritdoc /> public Task ProcessPayload(PullRequestEventPayload payload, CancellationToken cancellationToken) { if (payload == null) { throw new ArgumentNullException(nameof(payload)); } switch (payload.Action) { case "opened": case "closed": case "reopened": //reserialize it //.htmlSpecialChars($payload['sender']['login']).': <a href="'.$payload['pull_request']['html_url'].'">'.htmlSpecialChars('#'.$payload['pull_request']['number'].' '.$payload['pull_request']['user']['login'].' - '.$payload['pull_request']['title']).'</a>'; var json = new SimpleJsonSerializer().Serialize(payload); json = byondTopicSender.SanitizeString(json); const string innerAnnouncementFormatter = "#{0} {1} - {2}"; var innerAnnouncement = String.Format(CultureInfo.CurrentCulture, innerAnnouncementFormatter, payload.PullRequest.Number, payload.PullRequest.User.Login, payload.PullRequest.Title); var announcement = HttpUtility.HtmlEncode(innerAnnouncement); var actionString = payload.PullRequest.Merged ? "merged" : payload.Action; announcement = stringLocalizer["AnnouncementFormatterGame", payload.Repository.FullName, actionString, payload.Sender.Login, payload.PullRequest.HtmlUrl, announcement]; // "[{0}] Pull Request {1} by {2}: <a href='{3}'>{4}</a>"; announcement = byondTopicSender.SanitizeString(announcement); var startingQuery = String.Format(CultureInfo.InvariantCulture, "?announce={0}&payload={1}&key=", json, announcement); var chatAnnouncement = stringLocalizer["AnnouncementFormatterChat", payload.Repository.FullName, actionString, payload.Sender.Login, payload.PullRequest.HtmlUrl, innerAnnouncement]; var tasks = new List <Task> { //send it to the chats chatMessenger.SendMessage(chatAnnouncement, cancellationToken) }; foreach (var I in serverConfiguration.Entries) { var final = startingQuery + byondTopicSender.SanitizeString(I.CommsKey); tasks.Add(byondTopicSender.SendTopic(I.Address, I.Port, final, cancellationToken)); } return(Task.WhenAll(tasks)); } throw new NotSupportedException(); }
public ActionResult Edit(FormCollection form) { int id = Convert.ToInt32(form["Id"]); string name = form["Text"]; DateTime start = Convert.ToDateTime(form["Start"]); DateTime end = Convert.ToDateTime(form["End"]); int resource = Convert.ToInt32(form["Resource"]); int paid = Convert.ToInt32(form["Paid"]); int status = Convert.ToInt32(form["Status"]); DataRow dr = DbHelper.GetReservation(id); if (dr == null) { throw new Exception("The task was not found"); } DbHelper.UpdateReservation(id, name, start, end, resource, status, paid); return(JavaScript(SimpleJsonSerializer.Serialize("OK"))); }
public string GetCallbackResult() { if (this.callbackException == null) { string result; try { Hashtable hashtable = new Hashtable(); hashtable["Items"] = this.Items; hashtable["Cells"] = this.GetCells(); if (this.EnableViewState) { using (StringWriter stringWriter = new StringWriter()) { LosFormatter losFormatter = new LosFormatter(); losFormatter.Serialize(stringWriter, ViewStateHelper.ToHashtable(this.ViewState)); hashtable["VsUpdate"] = stringWriter.ToString(); } } result = SimpleJsonSerializer.Serialize(hashtable); } catch (Exception ex) { if (HttpContext.Current.IsDebuggingEnabled) { result = "$$$" + ex; } else { result = "$$$" + ex.Message; } } return(result); } if (HttpContext.Current.IsDebuggingEnabled) { return("$$$" + this.callbackException); } return("$$$" + this.callbackException.Message); }
public ActionResult Edit(FormCollection form) { string id = form["Id"]; string masterId = Request.QueryString["master"]; string recurrence = form["Recurrence"]; DateTime start = Convert.ToDateTime(form["Start"]); DateTime end = Convert.ToDateTime(form["End"]); string text = form["Text"]; string resource = form["Resource"]; var row = new EventManager().Get(id) ?? new EventManager.Event(); var master = new EventManager().Get(masterId) ?? new EventManager.Event(); switch (Mode(id)) { case EventMode.Master: RecurrenceRule rule = RecurrenceRule.FromJson(masterId, master.Start, recurrence); new EventManager().EventEdit(masterId, text, start, end, resource, rule.Encode()); break; case EventMode.NewException: new EventManager().EventCreateException(start, end, text, resource, RecurrenceRule.EncodeExceptionModified(masterId, Occurrence)); break; case EventMode.Exception: new EventManager().EventEdit(id, text, start, end, resource); break; case EventMode.Regular: new EventManager().EventEdit(id, text, start, end, resource, RecurrenceRule.FromJson(id, row.Start, recurrence).Encode()); break; default: throw new ArgumentOutOfRangeException(); } return(JavaScript(SimpleJsonSerializer.Serialize("OK"))); }
public void CanBeDeserialized() { const string json = @"{ ""message"": ""Validation Failed"", ""errors"": [ { ""resource"": ""Issue"", ""field"": ""title"", ""code"": ""missing_field"" } ] }"; var serializer = new SimpleJsonSerializer(); var apiError = serializer.Deserialize <ApiError>(json); Assert.Equal("Validation Failed", apiError.Message); Assert.Equal(1, apiError.Errors.Count); Assert.Equal("Issue", apiError.Errors[0].Resource); Assert.Equal("title", apiError.Errors[0].Field); Assert.Equal("missing_field", apiError.Errors[0].Code); }
public void CanBeDeserialized() { const string json = @"{ ""message"": ""Validation Failed"", ""errors"": [ { ""resource"": ""Issue"", ""field"": ""title"", ""code"": ""missing_field"" } ] }"; var serializer = new SimpleJsonSerializer(); var apiError = serializer.Deserialize<ApiError>(json); Assert.Equal("Validation Failed", apiError.Message); Assert.Equal(1, apiError.Errors.Count); Assert.Equal("Issue", apiError.Errors[0].Resource); Assert.Equal("title", apiError.Errors[0].Field); Assert.Equal("missing_field", apiError.Errors[0].Code); }
public void CanBeDeserializedFromRepositoryContentLicenseJson() { const string json = @"{ ""name"": ""LICENSE"", ""path"": ""LICENSE"", ""sha"": ""401c59dcc4570b954dd6d345e76199e1f4e76266"", ""size"": 1077, ""url"": ""https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master"", ""html_url"": ""https://github.com/benbalter/gman/blob/master/LICENSE"", ""git_url"": ""https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266"", ""download_url"": ""https://raw.githubusercontent.com/benbalter/gman/master/LICENSE?lab=true"", ""type"": ""file"", ""content"": ""VGhlIE1JVCBMaWNlbnNlIChNSVQpCgpDb3B5cmlnaHQgKGMpIDIwMTMgQmVu\nIEJhbHRlcgoKUGVybWlzc2lvbiBpcyBoZXJlYnkgZ3JhbnRlZCwgZnJlZSBv\nZiBjaGFyZ2UsIHRvIGFueSBwZXJzb24gb2J0YWluaW5nIGEgY29weSBvZgp0\naGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmls\nZXMgKHRoZSAiU29mdHdhcmUiKSwgdG8gZGVhbCBpbgp0aGUgU29mdHdhcmUg\nd2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRh\ndGlvbiB0aGUgcmlnaHRzIHRvCnVzZSwgY29weSwgbW9kaWZ5LCBtZXJnZSwg\ncHVibGlzaCwgZGlzdHJpYnV0ZSwgc3VibGljZW5zZSwgYW5kL29yIHNlbGwg\nY29waWVzIG9mCnRoZSBTb2Z0d2FyZSwgYW5kIHRvIHBlcm1pdCBwZXJzb25z\nIHRvIHdob20gdGhlIFNvZnR3YXJlIGlzIGZ1cm5pc2hlZCB0byBkbyBzbywK\nc3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6CgpUaGUgYWJv\ndmUgY29weXJpZ2h0IG5vdGljZSBhbmQgdGhpcyBwZXJtaXNzaW9uIG5vdGlj\nZSBzaGFsbCBiZSBpbmNsdWRlZCBpbiBhbGwKY29waWVzIG9yIHN1YnN0YW50\naWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS4KClRIRSBTT0ZUV0FSRSBJ\nUyBQUk9WSURFRCAiQVMgSVMiLCBXSVRIT1VUIFdBUlJBTlRZIE9GIEFOWSBL\nSU5ELCBFWFBSRVNTIE9SCklNUExJRUQsIElOQ0xVRElORyBCVVQgTk9UIExJ\nTUlURUQgVE8gVEhFIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZLCBG\nSVRORVNTCkZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBTkQgTk9OSU5GUklO\nR0VNRU5ULiBJTiBOTyBFVkVOVCBTSEFMTCBUSEUgQVVUSE9SUyBPUgpDT1BZ\nUklHSFQgSE9MREVSUyBCRSBMSUFCTEUgRk9SIEFOWSBDTEFJTSwgREFNQUdF\nUyBPUiBPVEhFUiBMSUFCSUxJVFksIFdIRVRIRVIKSU4gQU4gQUNUSU9OIE9G\nIENPTlRSQUNULCBUT1JUIE9SIE9USEVSV0lTRSwgQVJJU0lORyBGUk9NLCBP\nVVQgT0YgT1IgSU4KQ09OTkVDVElPTiBXSVRIIFRIRSBTT0ZUV0FSRSBPUiBU\nSEUgVVNFIE9SIE9USEVSIERFQUxJTkdTIElOIFRIRSBTT0ZUV0FSRS4K\n"", ""encoding"": ""base64"", ""_links"": { ""self"": ""https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master"", ""git"": ""https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266"", ""html"": ""https://github.com/benbalter/gman/blob/master/LICENSE"" }, ""license"": { ""key"": ""mit"", ""name"": ""MIT License"", ""spdx_id"": ""MIT"", ""url"": ""https://api.github.com/licenses/mit"", ""featured"": true } }"; var serializer = new SimpleJsonSerializer(); var license = serializer.Deserialize <RepositoryContentLicense>(json); var licenseMetadata = license.License; Assert.Equal("LICENSE", license.Name); Assert.Equal("LICENSE", license.Path); Assert.Equal("401c59dcc4570b954dd6d345e76199e1f4e76266", license.Sha); Assert.NotNull(license.License); Assert.Equal("mit", licenseMetadata.Key); }
protected bool tryParsePayload(string requestBody, out TPayload payload, out EventHandlerResult errorResult) { payload = null; if (string.IsNullOrEmpty(requestBody)) { errorResult = EventHandlerResult.PayloadError("request body was empty"); Logger.LogError("request body was empty"); return(false); } try { payload = new SimpleJsonSerializer().Deserialize <TPayload>(requestBody); } catch (Exception ex) { errorResult = EventHandlerResult.PayloadError($"request body deserialization failed: {ex.Message}"); Logger.LogError(ex, "request body deserialization failed"); return(false); } if (payload == null) { errorResult = EventHandlerResult.PayloadError("parsed payload was null or empty"); Logger.LogError("parsed payload was null or empty"); return(false); } if (payload.Repository == null) { errorResult = EventHandlerResult.PayloadError("no repository information in webhook payload"); Logger.LogError("no repository information in webhook payload"); return(false); } errorResult = null; return(true); }
public void DeserializesNullableStringEnums() { const string json1 = @"{""string_enum_nullable"":""+1""}"; const string json2 = @"{""string_enum_nullable"":""utf-8""}"; const string json3 = @"{""string_enum_nullable"":""something else""}"; const string json4 = @"{""string_enum_nullable"":""another_example""}"; const string json5 = @"{""string_enum_nullable"":""unicode""}"; const string json6 = @"{""string_enum_nullable"":null}"; var sample1 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json1); var sample2 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json2); var sample3 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json3); var sample4 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json4); var sample5 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json5); var sample6 = new SimpleJsonSerializer().Deserialize <ObjectWithEnumProperty>(json6); Assert.Equal(SomeEnum.PlusOne, sample1.StringEnumNullable); Assert.Equal(SomeEnum.Utf8, sample2.StringEnumNullable); Assert.Equal(SomeEnum.SomethingElse, sample3.StringEnumNullable); Assert.Equal(SomeEnum.AnotherExample, sample4.StringEnumNullable); Assert.Equal(SomeEnum.Unicode, sample5.StringEnumNullable); Assert.False(sample6.StringEnumNullable.HasValue); }
public async Task <IActionResult> InstallationHandler(JObject data) { var ser = new SimpleJsonSerializer(); var payload = ser.Deserialize <InstallationEvent>(data.ToString()); switch (payload.Action) { case "deleted": await RemoveInstallationRepositoriesAsync(payload.Installation.Id); break; case "created": await SynchronizeInstallationRepositoriesAsync(payload.Installation.Id); break; default: Logger.LogError("Received Unknown action '{action}' for installation event. Payload: {payload}", payload.Action, data.ToString()); break; } return(Ok()); }
public bool TryParse(out TEnum value) { if (_parsedValue.HasValue) { // the value has been parsed already. value = _parsedValue.Value; return(true); } try { // Use the SimpleJsonSerializer to parse the string to Enum according to the GitHub Api strategy value = (TEnum)SimpleJsonSerializer.DeserializeEnum(StringValue, typeof(TEnum)); // cache the parsed value for subsequent calls. _parsedValue = value; return(true); } catch (ArgumentException) { value = default(TEnum); return(false); } }
public void CanSerialize() { var expected = "{\"name\":\"Hello-World\"," + "\"description\":\"This is your first repository\"," + "\"homepage\":\"https://github.com\"," + "\"private\":true," + "\"has_issues\":true," + "\"has_wiki\":true," + "\"has_downloads\":true}"; var update = new RepositoryUpdate("Hello-World") { Description = "This is your first repository", Homepage = "https://github.com", Private = true, HasIssues = true, HasWiki = true, HasDownloads = true }; var json = new SimpleJsonSerializer().Serialize(update); Assert.Equal(expected, json); }
public static object DeserializeObject(string json) { IJsonSerializer current = new SimpleJsonSerializer(); return(current.DeserializeObject(json)); }
public HttpPartsPostTest(ITestOutputHelper testOutputHelper) { LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper); SimpleJsonSerializer.RegisterGlobally(); }
internal string GetHash() { byte[] bytes = Encoding.ASCII.GetBytes(SimpleJsonSerializer.Serialize(this.GetList())); return(Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(bytes))); }
public void CanBeDeserialized() { const string json = @"{ ""id"": 1, ""url"": ""https://api.github.com/repos/octocat/Hello-World/issues/1347"", ""html_url"": ""https://github.com/octocat/Hello-World/issues/1347"", ""number"": 1347, ""state"": ""open"", ""title"": ""Found a bug"", ""body"": ""I'm having a problem with this."", ""user"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""labels"": [ { ""url"": ""https://api.github.com/repos/octocat/Hello-World/labels/bug"", ""name"": ""bug"", ""color"": ""f29513"" } ], ""assignee"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""milestone"": { ""url"": ""https://api.github.com/repos/octocat/Hello-World/milestones/1"", ""number"": 1, ""state"": ""open"", ""title"": ""v1.0"", ""description"": """", ""creator"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""open_issues"": 4, ""closed_issues"": 8, ""created_at"": ""2011-04-10T20:09:31Z"", ""updated_at"": ""2014-03-03T18:58:10Z"", ""closed_at"": ""2013-02-12T13:22:01Z"", ""due_on"": null }, ""comments"": 0, ""pull_request"": { ""url"": ""https://api.github.com/repos/octocat/Hello-World/pulls/1347"", ""html_url"": ""https://github.com/octocat/Hello-World/pull/1347"", ""diff_url"": ""https://github.com/octocat/Hello-World/pull/1347.diff"", ""patch_url"": ""https://github.com/octocat/Hello-World/pull/1347.patch"" }, ""closed_at"": null, ""created_at"": ""2011-04-22T13:33:48Z"", ""updated_at"": ""2011-04-22T13:33:48Z"", ""closed_by"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false } }"; var serializer = new SimpleJsonSerializer(); var issue = serializer.Deserialize <Issue>(json); Assert.Equal(1347, issue.Number); Assert.Equal("octocat", issue.User.Login); Assert.Equal("bug", issue.Labels.First().Name); }
public async Task <IActionResult> Receive() { logger.LogTrace("Recieved POST."); if (!Request.Headers.TryGetValue("X-GitHub-Event", out StringValues eventName) || !Request.Headers.TryGetValue("X-Hub-Signature", out StringValues signature) || !Request.Headers.TryGetValue("X-GitHub-Delivery", out StringValues delivery)) { logger.LogDebug("Missing GitHub headers for payload! Found headers: {0}", Request.Headers.Keys); return(BadRequest()); } string json; using (var reader = new StreamReader(Request.Body)) json = await reader.ReadToEndAsync().ConfigureAwait(false); logger.LogTrace("Recieved payload: {0}", json); if (!CheckPayloadSignature(json, signature)) { logger.LogDebug("Payload rejected due to bad signature!"); return(Unauthorized()); } IActionResult StartJob <TPayload>() where TPayload : ActivityPayload { TPayload payload; logger.LogTrace("Deserializing payload."); try { payload = new SimpleJsonSerializer().Deserialize <TPayload>(json); } catch (Exception e) { logger.LogDebug(e, "Failed to deserialize payload JSON!"); return(BadRequest(e)); } //ensure the payload is from the configured sender logger.LogTrace("Checking payload repository."); if (payload.Repository.Owner.Login != gitHubConfiguration.RepoOwner || payload.Repository.Name != gitHubConfiguration.RepoName) { logger.LogDebug("Payload received from incorrectly configured repository!"); return(Forbid()); } logger.LogTrace("Queuing payload processing job."); //we pass in json because of the limitations of background job var jobName = backgroundJobClient.Enqueue(() => InvokeHandlers <TPayload>(json, JobCancellationToken.Null)); logger.LogTrace("Started background job for payload: {0}", jobName); return(Ok()); }; switch (eventName) { case "pull_request": return(StartJob <PullRequestEventPayload>()); case "pull_request_review": return(StartJob <PullRequestReviewEventPayload>()); default: return(Ok()); } }
public static string SerializeObject(object obj) { IJsonSerializer current = new SimpleJsonSerializer(); return(current.SerializeObject(obj)); }
internal string GetCode() { this.sb = new StringBuilder(); this.sb.AppendLine("<script type='text/javascript'>"); this.sb.AppendLine(string.Format("/* HMSPro: {0} */", Assembly.GetExecutingAssembly().FullName)); this.sb.AppendLine("function " + this._calendar.ClientObjectName + "_Init() {"); this.sb.AppendLine("var v = new HMS.Navigator('" + this._calendar.ClientID + "');"); this.appendProp("api", 1); if (this._calendar.boundClientName != null) { this.appendProp("bound", this._calendar.boundClientName, true); } this.appendProp("cellHeight", this._calendar.CellHeight); this.appendProp("cellWidth", this._calendar.CellWidth); this.appendProp("clientName", this._calendar.ClientObjectName, true); this.appendProp("command", this._calendar.BindCommand, true); this.appendProp("cssOnly", this._calendar.CssOnly); this.appendProp("theme", this._calendar.Theme, true); this.appendProp("dayHeaderHeight", this._calendar.DayHeaderHeight); this.appendProp("items", SimpleJsonSerializer.Serialize(this._calendar.Items)); this.appendProp("cells", SimpleJsonSerializer.Serialize(this._calendar.GetCells())); this.appendProp("locale", Thread.CurrentThread.CurrentCulture.Name.ToLower(), true); this.appendProp("month", this._calendar.StartDate.Month); this.appendProp("orientation", this._calendar.Orientation, true); this.appendProp("rowsPerMonth", this._calendar.RowsPerMonth, true); this.appendProp("selectMode", this._calendar.SelectMode.ToString().ToLower(), true); this.appendProp("selectionStart", "new HMS.Date('" + this._calendar.SelectionStart.ToString("s") + "')"); this.appendProp("selectionEnd", "new HMS.Date('" + this._calendar.SelectionEnd.ToString("s") + "')"); this.appendProp("showMonths", this._calendar.ShowMonths); this.appendProp("showWeekNumbers", this._calendar.ShowWeekNumbers); this.appendProp("skipMonths", this._calendar.SkipMonths); this.appendProp("titleHeight", this._calendar.TitleHeight); this.appendProp("uniqueID", this._calendar.UniqueID, true); this.appendProp("visible", this._calendar.Visible); this.appendProp("weekStarts", this.weekStarts()); this.appendProp("weekNumberAlgorithm", this._calendar.WeekNumberAlgorithm, true); this.appendProp("year", this._calendar.StartDate.Year); if (!string.IsNullOrEmpty(this._calendar.CallBackErrorJavaScript)) { this.appendProp("callbackError", "function(result, context) { " + this._calendar.CallBackErrorJavaScript + " }", false); } this.appendProp("timeRangeSelectedHandling", this._calendar.TimeRangeSelectedHandling, true); this.appendProp("onTimeRangeSelected", "function(start, end, day) {" + this._calendar.TimeRangeSelectedJavaScript + "}", false); this.appendProp("visibleRangeChangedHandling", this._calendar.VisibleRangeChangedHandling, true); this.appendProp("onVisibleRangeChanged", "function(start, end) {" + this._calendar.VisibleRangeChangedJavaScript + "}", false); this.sb.AppendLine("v.init();"); this.sb.AppendLine("return v.internal.initialized() ? v : null;"); this.sb.AppendLine("}"); this.sb.AppendLine(Locale.RegistrationString(Thread.CurrentThread.CurrentCulture.Name.ToLower())); this.sb.AppendLine(string.Concat(new string[] { "var ", this._calendar.ClientObjectName, " = ", this._calendar.ClientObjectName, "_Init() || ", this._calendar.ClientObjectName, ";" })); this.sb.AppendLine("</script>"); return(this.sb.ToString()); }
static async Task <int> Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); ParserResult <CommandlineArgs> argsResult = Parser.Default.ParseArguments <CommandlineArgs>(args); if (argsResult is NotParsed <CommandlineArgs> ) { Log.Logger.Error("Unable to parse arguments, be sure to include the path to the 'repos.json' file"); return(1); } CommandlineArgs parsedArgs = ((Parsed <CommandlineArgs>)argsResult).Value; if (!File.Exists(parsedArgs.RepositoryJson)) { Log.Logger.Error($"Unable to locate {parsedArgs.RepositoryJson}"); return(2); } RepositoryRoot configRoot = JsonConvert.DeserializeObject <RepositoryRoot>(await File.ReadAllTextAsync(parsedArgs.RepositoryJson)); IHost host = new HostBuilder() .ConfigureLogging(loggingBuilder => { loggingBuilder.AddSerilog(Log.Logger); }) .ConfigureServices(services => { if (!string.IsNullOrEmpty(parsedArgs.ProxyUrl)) { services.AddSingleton <IWebProxy>(_ => new WebProxy(parsedArgs.ProxyUrl)); } services.AddSingleton <IGitHubClient>(provider => { IWebProxy proxy = provider.GetService <IWebProxy>(); SimpleJsonSerializer jsonSerializer = new SimpleJsonSerializer(); return(new GitHubClient(new Connection(new ProductHeaderValue(ClientName), new Uri(parsedArgs.GithubApi), new InMemoryCredentialStore(new Credentials(parsedArgs.GithubToken)), new HttpClientAdapter( () => new HttpClientHandler { Proxy = proxy }), jsonSerializer))); }); services .AddSingleton(parsedArgs) .AddSingleton(configRoot) .AddSingleton(x => new GhStandardFileSetFactory(x.GetRequiredService <RepositoryRoot>(), parsedArgs.RepositoryJson)) .AddSingleton <GhStandardContentApplier>(); }) .Build(); GhStandardFileSetFactory fileSetFactory = host.Services.GetRequiredService <GhStandardFileSetFactory>(); GhStandardContentApplier applier = host.Services.GetRequiredService <GhStandardContentApplier>(); IEnumerable <KeyValuePair <string, JObject> > repos; if (!string.IsNullOrEmpty(parsedArgs.Repository) && configRoot.Repositories.TryGetValue(parsedArgs.Repository, out var singleRepo)) { repos = new[] { KeyValuePair.Create(parsedArgs.Repository, singleRepo) }; } else if (!string.IsNullOrEmpty(parsedArgs.Repository)) { // Try looking for a partial match var match = configRoot.Repositories.Keys.FirstOrDefault(s => s.Split('/').Last().Equals(parsedArgs.Repository, StringComparison.OrdinalIgnoreCase)); if (match == null) { Log.Error("Unable to run for {Repository} alone", parsedArgs.Repository); return(3); } repos = new[] { KeyValuePair.Create(match, configRoot.Repositories[match]) }; } else { repos = configRoot.Repositories; } foreach ((string repository, JObject config) in repos) { GhStandardFileSet fileSet = fileSetFactory.GetFileSet(config); if (fileSet.Count == 0) { Log.Debug("Skipping {Repository}, no files to manage", repository); continue; } string[] repoParts = repository.Split('/'); string repoOrg = repoParts[0]; string repoName = repoParts[1]; Log.Information("Applying {Count} files to {Organization} / {Repository}", fileSet.Count, repoOrg, repoName); await applier.Apply(repoOrg, repoName, fileSet); } return(0); }
public void CanBeDeserialized() { const string json = @"{ ""id"": 1, ""url"": ""https://api.github.com/repos/octocat/Hello-World/issues/1347"", ""html_url"": ""https://github.com/octocat/Hello-World/issues/1347"", ""number"": 1347, ""state"": ""open"", ""title"": ""Found a bug"", ""body"": ""I'm having a problem with this."", ""user"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""labels"": [ { ""url"": ""https://api.github.com/repos/octocat/Hello-World/labels/bug"", ""name"": ""bug"", ""color"": ""f29513"" } ], ""assignee"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""milestone"": { ""url"": ""https://api.github.com/repos/octocat/Hello-World/milestones/1"", ""number"": 1, ""state"": ""open"", ""title"": ""v1.0"", ""description"": """", ""creator"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""open_issues"": 4, ""closed_issues"": 8, ""created_at"": ""2011-04-10T20:09:31Z"", ""updated_at"": ""2014-03-03T18:58:10Z"", ""closed_at"": ""2013-02-12T13:22:01Z"", ""due_on"": null }, ""comments"": 0, ""pull_request"": { ""url"": ""https://api.github.com/repos/octocat/Hello-World/pulls/1347"", ""html_url"": ""https://github.com/octocat/Hello-World/pull/1347"", ""diff_url"": ""https://github.com/octocat/Hello-World/pull/1347.diff"", ""patch_url"": ""https://github.com/octocat/Hello-World/pull/1347.patch"" }, ""closed_at"": null, ""created_at"": ""2011-04-22T13:33:48Z"", ""updated_at"": ""2011-04-22T13:33:48Z"", ""closed_by"": { ""login"": ""octocat"", ""id"": 1, ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""https://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false } }"; var serializer = new SimpleJsonSerializer(); var issue = serializer.Deserialize<Issue>(json); Assert.Equal(1347, issue.Number); Assert.Equal("octocat", issue.User.Login); Assert.Equal("bug", issue.Labels.First().Name); }
public void DeserializesInheritedProperties() { const string json = "{\"sha\":\"commit-sha\",\"url\":\"commit-url\",\"message\":\"commit-message\"}"; var result = new SimpleJsonSerializer().Deserialize<Commit>(json); Assert.Equal("commit-sha", result.Sha); Assert.Equal("commit-url", result.Url); Assert.Equal("commit-message", result.Message); }
public ActionResult Edit(FormCollection form) { new EventManager(this).EventEdit(form["Id"], form["Text"]); return(JavaScript(SimpleJsonSerializer.Serialize("OK"))); }
internal void AppendSerialized(string property, object value) { AppendProp(property, SimpleJsonSerializer.Serialize(value), false); }
static string CreateRequireCallJavaScript(string[] initialModulePaths) { var jsonSerializer = new SimpleJsonSerializer(); var modulePathsArray = jsonSerializer.Serialize(initialModulePaths); return "<script>require(" + modulePathsArray + ")</script>"; }
public void PerformsCommitSerialization() { var tree = new GitReference { Sha = "tree-reference", Url = "tree-url" }; var parent1 = new GitReference { Sha = "parent1-reference", Url = "parent1-url" }; var parent2 = new GitReference { Sha = "parent2-reference", Url = "parent2-url" }; var author = new Signature { Name = "author-name", Email = "author-email", Date = new DateTime(2013, 10, 15, 13, 40, 14, DateTimeKind.Utc) }; var committer = new Signature { Name = "committer-name", Email = "committer-email", Date = new DateTime(2013, 06, 29, 10, 12, 50, DateTimeKind.Utc) }; var commit = new Commit { Sha = "commit-reference", Url = "commit-url", Message = "commit-message", Parents = new[]{ parent1, parent2 }, Tree = tree, Author = author, Committer = committer, }; var json = new SimpleJsonSerializer().Serialize(commit); const string expectedResult = "{\"message\":\"commit-message\"," + "\"author\":{" + "\"name\":\"author-name\"," + "\"email\":\"author-email\"," + "\"date\":\"2013-10-15T13:40:14Z\"" + "}," + "\"committer\":{" + "\"name\":\"committer-name\"," + "\"email\":\"committer-email\"," + "\"date\":\"2013-06-29T10:12:50Z\"" + "}," + "\"tree\":{" + "\"url\":\"tree-url\"," + "\"sha\":\"tree-reference\"" + "}," + "\"parents\":[{" + "\"url\":\"parent1-url\"," + "\"sha\":\"parent1-reference\"" + "}," + "{" + "\"url\":\"parent2-url\"," + "\"sha\":\"parent2-reference\"" + "}]," + "\"comment_count\":0," + "\"url\":\"commit-url\"," + "\"sha\":\"commit-reference\"" + "}"; Assert.Equal(expectedResult, json); }
public void CanBeDeserialized() { const string json = @"{ ""action"": ""rerequested"", ""check_run"": { ""id"": 4, ""head_sha"": ""d6fde92930d4715a2b49857d24b940956b26d2d3"", ""external_id"": """", ""url"": ""https://api.github.com/repos/github/hello-world/check-runs/4"", ""html_url"": ""http://github.com/github/hello-world/runs/4"", ""status"": ""completed"", ""conclusion"": ""neutral"", ""started_at"": ""2018-05-04T01:14:52Z"", ""completed_at"": ""2018-05-04T01:14:52Z"", ""output"": { ""title"": ""Report"", ""summary"": ""It's all good."", ""text"": ""Minus odio facilis repudiandae. Soluta odit aut amet magni nobis. Et voluptatibus ex dolorem et eum."", ""annotations_count"": 2, ""annotations_url"": ""https://api.github.com/repos/github/hello-world/check-runs/4/annotations"" }, ""name"": ""randscape"", ""check_suite"": { ""id"": 5, ""head_branch"": ""master"", ""head_sha"": ""d6fde92930d4715a2b49857d24b940956b26d2d3"", ""status"": ""completed"", ""conclusion"": ""neutral"", ""url"": ""https://api.github.com/repos/github/hello-world/check-suites/5"", ""before"": ""146e867f55c26428e5f9fade55a9bbf5e95a7912"", ""after"": ""d6fde92930d4715a2b49857d24b940956b26d2d3"", ""pull_requests"": [ ], ""app"": { ""id"": 2, ""node_id"": ""MDExOkludGVncmF0aW9uMQ=="", ""owner"": { ""login"": ""github"", ""id"": 340, ""node_id"": ""MDEyOk9yZ2FuaXphdGlvbjE="", ""avatar_url"": ""http://alambic.github.com/avatars/u/340?"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/github"", ""html_url"": ""http://github.com/github"", ""followers_url"": ""https://api.github.com/users/github/followers"", ""following_url"": ""https://api.github.com/users/github/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/github/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/github/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/github/subscriptions"", ""organizations_url"": ""https://api.github.com/users/github/orgs"", ""repos_url"": ""https://api.github.com/users/github/repos"", ""events_url"": ""https://api.github.com/users/github/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/github/received_events"", ""type"": ""Organization"", ""site_admin"": false }, ""name"": ""Super Duper"", ""description"": null, ""external_url"": ""http://super-duper.example.com"", ""html_url"": ""http://github.com/apps/super-duper"", ""created_at"": ""2018-04-25T20:42:10Z"", ""updated_at"": ""2018-04-25T20:42:10Z"" }, ""created_at"": ""2018-05-04T01:14:52Z"", ""updated_at"": ""2018-05-04T01:14:52Z"" }, ""app"": { ""id"": 2, ""node_id"": ""MDExOkludGVncmF0aW9uMQ=="", ""owner"": { ""login"": ""github"", ""id"": 340, ""node_id"": ""MDEyOk9yZ2FuaXphdGlvbjE="", ""avatar_url"": ""http://alambic.github.com/avatars/u/340?"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/github"", ""html_url"": ""http://github.com/github"", ""followers_url"": ""https://api.github.com/users/github/followers"", ""following_url"": ""https://api.github.com/users/github/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/github/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/github/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/github/subscriptions"", ""organizations_url"": ""https://api.github.com/users/github/orgs"", ""repos_url"": ""https://api.github.com/users/github/repos"", ""events_url"": ""https://api.github.com/users/github/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/github/received_events"", ""type"": ""Organization"", ""site_admin"": false }, ""name"": ""Super Duper"", ""description"": null, ""external_url"": ""http://super-duper.example.com"", ""html_url"": ""http://github.com/apps/super-duper"", ""created_at"": ""2018-04-25T20:42:10Z"", ""updated_at"": ""2018-04-25T20:42:10Z"" }, ""pull_requests"": [ ] }, ""requested_action"": { ""identifier"": ""dosomeaction"" }, ""repository"": { ""id"": 526, ""node_id"": ""MDEwOlJlcG9zaXRvcnkxMzU0OTMyMzM="", ""name"": ""hello-world"", ""full_name"": ""github/hello-world"", ""owner"": { ""login"": ""github"", ""id"": 340, ""node_id"": ""MDQ6VXNlcjIxMDMxMDY3"", ""avatar_url"": ""http://alambic.github.com/avatars/u/340?"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/github"", ""html_url"": ""http://github.com/github"", ""followers_url"": ""https://api.github.com/users/github/followers"", ""following_url"": ""https://api.github.com/users/github/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/github/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/github/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/github/subscriptions"", ""organizations_url"": ""https://api.github.com/users/github/orgs"", ""repos_url"": ""https://api.github.com/users/github/repos"", ""events_url"": ""https://api.github.com/users/github/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/github/received_events"", ""type"": ""Organization"", ""site_admin"": false }, ""private"": false, ""html_url"": ""http://github.com/github/hello-world"", ""description"": null, ""fork"": false, ""url"": ""https://api.github.com/repos/github/hello-world"", ""forks_url"": ""https://api.github.com/repos/github/hello-world/forks"", ""keys_url"": ""https://api.github.com/repos/github/hello-world/keys{/key_id}"", ""collaborators_url"": ""https://api.github.com/repos/github/hello-world/collaborators{/collaborator}"", ""teams_url"": ""https://api.github.com/repos/github/hello-world/teams"", ""hooks_url"": ""https://api.github.com/repos/github/hello-world/hooks"", ""issue_events_url"": ""https://api.github.com/repos/github/hello-world/issues/events{/number}"", ""events_url"": ""https://api.github.com/repos/github/hello-world/events"", ""assignees_url"": ""https://api.github.com/repos/github/hello-world/assignees{/user}"", ""branches_url"": ""https://api.github.com/repos/github/hello-world/branches{/branch}"", ""tags_url"": ""https://api.github.com/repos/github/hello-world/tags"", ""blobs_url"": ""https://api.github.com/repos/github/hello-world/git/blobs{/sha}"", ""git_tags_url"": ""https://api.github.com/repos/github/hello-world/git/tags{/sha}"", ""git_refs_url"": ""https://api.github.com/repos/github/hello-world/git/refs{/sha}"", ""trees_url"": ""https://api.github.com/repos/github/hello-world/git/trees{/sha}"", ""statuses_url"": ""https://api.github.com/repos/github/hello-world/statuses/{sha}"", ""languages_url"": ""https://api.github.com/repos/github/hello-world/languages"", ""stargazers_url"": ""https://api.github.com/repos/github/hello-world/stargazers"", ""contributors_url"": ""https://api.github.com/repos/github/hello-world/contributors"", ""subscribers_url"": ""https://api.github.com/repos/github/hello-world/subscribers"", ""subscription_url"": ""https://api.github.com/repos/github/hello-world/subscription"", ""commits_url"": ""https://api.github.com/repos/github/hello-world/commits{/sha}"", ""git_commits_url"": ""https://api.github.com/repos/github/hello-world/git/commits{/sha}"", ""comments_url"": ""https://api.github.com/repos/github/hello-world/comments{/number}"", ""issue_comment_url"": ""https://api.github.com/repos/github/hello-world/issues/comments{/number}"", ""contents_url"": ""https://api.github.com/repos/github/hello-world/contents/{+path}"", ""compare_url"": ""https://api.github.com/repos/github/hello-world/compare/{base}...{head}"", ""merges_url"": ""https://api.github.com/repos/github/hello-world/merges"", ""archive_url"": ""https://api.github.com/repos/github/hello-world/{archive_format}{/ref}"", ""downloads_url"": ""https://api.github.com/repos/github/hello-world/downloads"", ""issues_url"": ""https://api.github.com/repos/github/hello-world/issues{/number}"", ""pulls_url"": ""https://api.github.com/repos/github/hello-world/pulls{/number}"", ""milestones_url"": ""https://api.github.com/repos/github/hello-world/milestones{/number}"", ""notifications_url"": ""https://api.github.com/repos/github/hello-world/notifications{?since,all,participating}"", ""labels_url"": ""https://api.github.com/repos/github/hello-world/labels{/name}"", ""releases_url"": ""https://api.github.com/repos/github/hello-world/releases{/id}"", ""deployments_url"": ""https://api.github.com/repos/github/hello-world/deployments"", ""created_at"": ""2018-04-25T20:42:10Z"", ""updated_at"": ""2018-04-25T20:43:34Z"", ""pushed_at"": ""2018-05-04T01:14:47Z"", ""git_url"": ""git://github.com/github/hello-world.git"", ""ssh_url"": ""ssh://git@localhost:3035/github/hello-world.git"", ""clone_url"": ""http://github.com/github/hello-world.git"", ""svn_url"": ""http://github.com/github/hello-world"", ""homepage"": null, ""size"": 0, ""stargazers_count"": 0, ""watchers_count"": 0, ""language"": null, ""has_issues"": true, ""has_projects"": true, ""has_downloads"": true, ""has_wiki"": true, ""has_pages"": false, ""forks_count"": 0, ""mirror_url"": null, ""archived"": false, ""open_issues_count"": 3, ""license"": null, ""forks"": 0, ""open_issues"": 3, ""watchers"": 0, ""default_branch"": ""master"" }, ""organization"": { ""login"": ""github"", ""id"": 340, ""node_id"": ""MDEyOk9yZ2FuaXphdGlvbjM4MzAyODk5"", ""url"": ""https://api.github.com/orgs/github"", ""repos_url"": ""https://api.github.com/orgs/github/repos"", ""events_url"": ""https://api.github.com/orgs/github/events"", ""hooks_url"": ""https://api.github.com/orgs/github/hooks"", ""issues_url"": ""https://api.github.com/orgs/github/issues"", ""members_url"": ""https://api.github.com/orgs/github/members{/member}"", ""public_members_url"": ""https://api.github.com/orgs/github/public_members{/member}"", ""avatar_url"": ""http://alambic.github.com/avatars/u/340?"", ""description"": ""How people build software."" }, ""sender"": { ""login"": ""octocat"", ""id"": 5346, ""node_id"": ""MDQ6VXNlcjIxMDMxMDY3"", ""avatar_url"": ""http://alambic.github.com/avatars/u/5346?"", ""gravatar_id"": """", ""url"": ""https://api.github.com/users/octocat"", ""html_url"": ""http://github.com/octocat"", ""followers_url"": ""https://api.github.com/users/octocat/followers"", ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"", ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"", ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"", ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"", ""organizations_url"": ""https://api.github.com/users/octocat/orgs"", ""repos_url"": ""https://api.github.com/users/octocat/repos"", ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"", ""received_events_url"": ""https://api.github.com/users/octocat/received_events"", ""type"": ""User"", ""site_admin"": false }, ""installation"": { ""id"": 1 } }"; var serializer = new SimpleJsonSerializer(); var payload = serializer.Deserialize <CheckRunEventPayload>(json); Assert.Equal("rerequested", payload.Action); Assert.Equal("d6fde92930d4715a2b49857d24b940956b26d2d3", payload.CheckRun.HeadSha); Assert.Equal(4, payload.CheckRun.Id); Assert.Equal(CheckStatus.Completed, payload.CheckRun.Status); Assert.Equal(CheckConclusion.Neutral, payload.CheckRun.Conclusion); Assert.Equal("dosomeaction", payload.RequestedAction.Identifier); Assert.Equal(5, payload.CheckRun.CheckSuite.Id); Assert.Equal(CheckStatus.Completed, payload.CheckRun.CheckSuite.Status.Value); Assert.Equal(CheckConclusion.Neutral, payload.CheckRun.CheckSuite.Conclusion); }
public void WhenNotFoundTypeDefaultsToUnknown() { const string json = @"{""private"":true}"; var user = new SimpleJsonSerializer().Deserialize<User>(json); Assert.Equal(0, user.Id); Assert.Null(user.Type); }
public void PerformsNewTagSerialization() { var tag = new NewTag { Message = "tag-message", Tag = "tag-name", Object = "tag-object", Type = TaggedType.Tree, Tagger = new Committer("tagger-name", "tagger-email", DateTimeOffset.Parse("2013-09-03T13:42:52Z")) }; var json = new SimpleJsonSerializer().Serialize(tag); const string expectedResult = "{\"tag\":\"tag-name\"," + "\"message\":\"tag-message\"," + "\"object\":\"tag-object\"," + "\"type\":\"tree\"," + "\"tagger\":{" + "\"name\":\"tagger-name\"," + "\"email\":\"tagger-email\"," + "\"date\":\"2013-09-03T13:42:52Z\"" + "}" + "}"; Assert.Equal(expectedResult, json); }
public void DefaultsMissingParameters() { const string json = @"{""private"":true}"; var sample = new SimpleJsonSerializer().Deserialize<Sample>(json); Assert.Equal(0, sample.Id); Assert.Equal(null, sample.FirstName); Assert.False(sample.IsSomething); Assert.True(sample.Private); }
public void PerformsCommitSerialization() { var tree = new GitReference { Sha = "tree-reference", Url = "tree-url" }; var parent1 = new GitReference { Sha = "parent1-reference", Url = "parent1-url" }; var parent2 = new GitReference { Sha = "parent2-reference", Url = "parent2-url" }; var author = new Signature { Name = "author-name", Email = "author-email", Date = new DateTime(2013, 10, 15, 13, 40, 14, DateTimeKind.Utc) }; var committer = new Signature { Name = "committer-name", Email = "committer-email", Date = new DateTime(2013, 06, 29, 10, 12, 50, DateTimeKind.Utc) }; var commit = new Commit { Sha = "commit-reference", Url = "commit-url", Message = "commit-message", Parents = new[] { parent1, parent2 }, Tree = tree, Author = author, Committer = committer, }; var json = new SimpleJsonSerializer().Serialize(commit); const string expectedResult = "{\"message\":\"commit-message\"," + "\"author\":{" + "\"name\":\"author-name\"," + "\"email\":\"author-email\"," + "\"date\":\"2013-10-15T13:40:14Z\"" + "}," + "\"committer\":{" + "\"name\":\"committer-name\"," + "\"email\":\"committer-email\"," + "\"date\":\"2013-06-29T10:12:50Z\"" + "}," + "\"tree\":{" + "\"url\":\"tree-url\"," + "\"sha\":\"tree-reference\"" + "}," + "\"parents\":[{" + "\"url\":\"parent1-url\"," + "\"sha\":\"parent1-reference\"" + "}," + "{" + "\"url\":\"parent2-url\"," + "\"sha\":\"parent2-reference\"" + "}]," + "\"url\":\"commit-url\"," + "\"sha\":\"commit-reference\"" + "}"; Assert.Equal(expectedResult, json); }
static Issue CreateIssue(int issueNumber) { var serializer = new SimpleJsonSerializer(); return serializer.Deserialize<Issue>(@"{""number"": """ + issueNumber + @"""}"); }
public void DeserializesEnum() { const string json = @"{""some_enum"":""unicode""}"; var sample = new SimpleJsonSerializer().Deserialize<ObjectWithEnumProperty>(json); Assert.Equal(SomeEnum.Unicode, sample.SomeEnum); }
static Issue CreateIssue(int issueNumber) { var serializer = new SimpleJsonSerializer(); return(serializer.Deserialize <Issue>(@"{""number"": """ + issueNumber + @"""}")); }
public void RemovesDashFromEnums() { const string json = @"{""some_enum"":""utf-8""}"; var sample = new SimpleJsonSerializer().Deserialize<ObjectWithEnumProperty>(json); Assert.Equal(SomeEnum.Utf8, sample.SomeEnum); }
public async Task <IActionResult> Receive(CancellationToken cancellationToken) { logger.LogTrace("Recieved POST."); if (!Request.Headers.TryGetValue("X-GitHub-Event", out StringValues eventName) || !Request.Headers.TryGetValue("X-Hub-Signature", out StringValues signature) || !Request.Headers.TryGetValue("X-GitHub-Delivery", out StringValues delivery)) { logger.LogDebug("Missing GitHub headers for payload! Found headers: {0}", Request.Headers.Keys); return(BadRequest()); } string json; using (var reader = new StreamReader(Request.Body)) json = await reader.ReadToEndAsync().ConfigureAwait(false); logger.LogTrace("Recieved payload: {0}", json); if (!CheckPayloadSignature(json, signature)) { logger.LogDebug("Payload rejected due to bad signature!"); return(Unauthorized()); } if (eventName == "pull_request") { PullRequestEventPayload payload; logger.LogTrace("Deserializing pull request payload."); try { payload = new SimpleJsonSerializer().Deserialize <PullRequestEventPayload>(json); } catch (Exception e) { logger.LogDebug(e, "Failed to deserialize pull request payload JSON!"); return(BadRequest(e)); } logger.LogTrace("Queuing pull request payload processing job."); pullRequestProcessor.ProcessPayload(payload); } else if (eventName == "check_suite") { CheckSuiteEventPayload payload; logger.LogTrace("Deserializing check suite payload."); try { payload = new SimpleJsonSerializer().Deserialize <CheckSuiteEventPayload>(json); } catch (Exception e) { logger.LogDebug(e, "Failed to deserialize check suite payload JSON!"); return(BadRequest(e)); } logger.LogTrace("Queuing check suite payload processing job."); pullRequestProcessor.ProcessPayload(payload); } else if (eventName == "check_run") { CheckRunEventPayload payload; logger.LogTrace("Deserializing check run payload."); try { payload = new SimpleJsonSerializer().Deserialize <CheckRunEventPayload>(json); } catch (Exception e) { logger.LogDebug(e, "Failed to deserialize check run payload JSON!"); return(BadRequest(e)); } logger.LogTrace("Queuing check run payload processing job."); await pullRequestProcessor.ProcessPayload(payload, gitHubManager, cancellationToken).ConfigureAwait(false); } return(Ok()); }
public void UnderstandsParameterAttribute() { const string json = @"{""some_enum"":""+1""}"; var sample = new SimpleJsonSerializer().Deserialize<ObjectWithEnumProperty>(json); Assert.Equal(SomeEnum.PlusOne, sample.SomeEnum); }