public void ArticleFromDocumentTest() { var json = TestData.ReadmeAttributeTypeResolutionJson(); var ghostBuster = JsonApi.ResourceFromDocument <GhostBuster>(json); Assert.AreEqual("I collect spores, molds, and fungus.", ghostBuster.Quotes[0]); }
public async Task <IActionResult> UpdateUserInfo([Required, FromBody] InfoUpdate newInfo) { var email = GetCurrentUserEmailAddress(); var updatedUser = await _userOperations.UpdateUserInfo(email, newInfo); return(JsonApi.OkDataObject(updatedUser)); }
public void MappedTitleToSubjectTest() { var json = TestData.ReadmeSingleResourceJson(); var article = JsonApi.ResourceFromDocument <Article>(json); Assert.AreEqual("JSON API paints my bikeshed!", article.Subject); }
public TestModule(D1SoccerServiceContext ctx) : base("api") { Get("/", _ => { return("hello there"); }); Get("/db", _ => { return(JsonApi.Response(ctx.Users .Select(x => new User { Id = x.Id.ToString(), FirstName = x.FirstName, LastName = x.LastName, Dob = x.Dob, Gender = x.Gender }) .ToArray())); }); Get("/db2", _ => { return(JsonApi.Response(ctx.Users .Select(x => new User { Id = x.Id.ToString(), FirstName = x.FirstName, LastName = x.LastName, Dob = x.Dob, Gender = x.Gender }) .FirstOrDefault())); }); }
public async Task <IActionResult> Create([Required, FromBody] Commit commit) { var email = GetCurrentUserEmailAddress(); var note = await _noteOperations.CreateNote(email, commit); return(CreatedAtAction(nameof(GetById), new { id = note.Id }, JsonApi.DataObject(note))); }
public string Get() { string t = System.IO.File.ReadAllText(@"./configs.json"); JsonApi json = JsonConvert.DeserializeObject <JsonApi>(t); return(json.ConsulUrl); }
public void CustomPropertyResolverTest() { var json = TestData.ReadmeSingleResourceJson(); var article = JsonApi.ResourceFromDocument <Article>(json, null, new NamingThingsIsHardResolver()); Assert.AreEqual("JSON API paints my bikeshed!", article.ThingYouCallIt); }
/// <summary> /// load and cache data of type T /// </summary> /// <typeparam name="T">Type to deserialize into</typeparam> /// <param name="fileName">name of file under Resources, without extension</param> /// <param name="getKey">key on which to index store</param> public static void Load <T>(string fileName, Func <T, string> getKey) { var asset = Resources.Load <TextAsset>(fileName); var data = JsonApi.Deserialize <T[]>(asset.text); _store[typeof(T)] = data.ToDictionary(x => getKey(x), x => (object)x); }
public void MappedIdAndTypeTest() { var json = TestData.ReadmeSingleResourceJson(); var article = JsonApi.ResourceFromDocument <Article>(json); Assert.AreEqual(Guid.Parse("30cd428f-1a3b-459b-a9a8-0ca87c14dd31"), article.Identifier); Assert.AreEqual("articles", article.ResourceType); }
public void ArticleFromJsonApiDocumentResourceTestWithoutIncludes() { var json = TestData.ReadmeCompoundDocumentWithoutIncludes(); var document = JsonApi.Document <Article>(json, ignoreMissingRelationships: true); var article = document.Resource; Assert.AreEqual("JSON API paints my bikeshed!", article.Title); }
public void CustomResourceTypeResolverTest() { var json = TestData.ReadmeResourceTypeResolutionJson(); var lemonDrop = JsonApi.ResourceFromDocument <LemonDrop>(json, new BarneyTypeResolver()); Assert.IsTrue(lemonDrop.Splatter); }
public void ContainerVsResourceTypeTest() { var json = TestData.ReadmeResourceTypeResolutionJson(); var rainDrop = JsonApi.ResourceFromDocument <object>(json); Assert.IsTrue(((RainDrop)rainDrop).Splatter); }
public void ArticleFromJsonApiDocumentResourceTest() { var json = TestData.ReadmeSingleResourceJson(); var document = JsonApi.Document <Article>(json); var article = document.Resource; Assert.AreEqual("JSON API paints my bikeshed!", article.Title); }
public async Task <StarSystem> GetSystemByNameAsync(string name) { name = WebUtility.UrlEncode(name.ToUpper()); var repsonse = await QuerySystemApi(EndpointSystems, $"filter[name:eq]={name}&include=bodies.stations"); var starSystems = JsonApi.Deserialize <StarSystem[]>(repsonse); return(starSystems.SingleOrDefault()); }
public void ArticlesFromDocumentTest() { var json = TestData.ReadmeMultipleResourcesJson(); var articles = JsonApi.ResourceFromDocument <List <Article> >(json); Assert.IsNotNull(articles); Assert.AreEqual(1, articles.Count); var article = articles[0]; Assert.AreEqual("JSON API paints my bikeshed!", article.Title); }
public void MixedResourcesWithCommonInterfaceTest() { var json = TestData.ReadmeMixedResourcesJson(); var titled = JsonApi.ResourceFromDocument <List <ITitled> >(json); Assert.IsNotNull(titled); Assert.AreEqual(3, titled.Count); Assert.AreEqual("JSON API paints my bikeshed!", titled[0].Title); Assert.AreEqual("and I wrote a book about it...", titled[1].Title); Assert.AreEqual("which was featured in a magazine!", titled[2].Title); }
public void ResourceFromDocumentThrows() { var json = TestData.ValidDocumentErrorsJson(); try { var res = JsonApi.ResourceFromDocument <Article>(json); Assert.Fail("Did not throw JsonApiErrorsException!"); } catch (JsonApiErrorsException e) { Assert.AreEqual("Error Title: Error details go here.", e.Message); } }
/// <summary> /// load and cache data of type T. /// if some data of type T has already been loaded, merges with existing store. /// duplicate keys for a given type are not allowed. /// </summary> /// <typeparam name="T">Type to deserialize into</typeparam> /// <param name="fileName">name of file under Resources, without extension</param> /// <param name="getKey">key on which to index store</param> public static void Load <T>(string fileName, Func <T, string> getKey) { var asset = Resources.Load <TextAsset>(fileName); var data = JsonApi.Deserialize <T[]>(asset.text); var typeKey = typeof(T); if (_store.ContainsKey(typeKey)) // key already exists, add pairs into existing dict { data.ToList().ForEach(x => _store[typeKey].Add(getKey(x), (object)x)); } else // type not loaded yet. create new dictionary { _store[typeKey] = data.ToDictionary(x => getKey(x), x => (object)x); } }
//Nome do Valor Passado Na Action Deve Ter Mesmo Nome Da ViewModel public ActionResult Inserir_Pedido(string CodigoPedido) { /*O bloco seguinte valida os estados do DataAnnotation para caso alguém consiga burlar * se a pessoa colocar CodigoPedido errado e não passar pela validação, então ela é redirecionada * para a view Index!*/ if (!ModelState.IsValid) { return(View("Index")); } object ResultadoApiJson = RequisicaoApiMillennium.GetApiResultadoPedido(CodigoPedido); //Verifica conexão com porta da API do servidor if (ResultadoApiJson != null) { var resultado = JsonApi.FromJson(ResultadoApiJson.ToString()); //Verifica conexão com porta da API do servidor if (resultado.OdataCount > 1) { //Valida se o código do pedido fornecido só retornou um pedido mesmo TempData["JsonDataCountException"] = "Ocorreu um erro, entre em contato com o suporte e descreva o seguinte ocorrido: CodErro 0: O array de pedidos retornou num diferente de '1'"; } //Se tudo der certo, Armazena os pedidos retornados da Api em uma lista else { foreach (var item in resultado.Value) { PedidoViewModel Pedido = new PedidoViewModel(item.Pedido, item.Status, item.DataPedido, item.DataAtualizacao, item.ValorPedido, item.NomeCliente); TempData["Pedido"] = Pedido; } } } //Se a primeira condição for falsa, avisa sobre o erro com a porta de conexão do Server API! else { //Apenas TempDatas sao permitidas passar entre controllers TempData["ServerConnException"] = "O servidor está fora do ar no momento, tente novamente mais tarde."; } return(RedirectToAction("Mostrar_Status_Home", "Statuspedido")); }
public void CompoundDocumentTest() { var json = TestData.ReadmeCompoundDocumentJson(); var articles = JsonApi.ResourceFromDocument <List <Article> >(json); Assert.IsNotNull(articles); Assert.AreEqual(1, articles.Count); var article = articles[0]; Assert.AreEqual("JSON API paints my bikeshed!", article.Title); var author = articles[0].Author; Assert.AreEqual("Gebhardt", author.LastName); var comments = articles[0].Comments; Assert.AreEqual("I like XML better", comments[1].Body); }
public void RemappedRelationshipTest() { var json = TestData.ReadmeCompoundDocumentJson(); var articles = JsonApi.ResourceFromDocument <List <Article> >(json); Assert.IsNotNull(articles); Assert.AreEqual(1, articles.Count); var article = articles[0]; Assert.AreEqual("JSON API paints my bikeshed!", article.Title); var author = articles[0].WrittenBy; Assert.AreEqual("Gebhardt", author.LastName); Assert.AreEqual("Gebhardt", articles[0].WrittenBy.LastName); // this is the actual README line var comments = articles[0].Comments; Assert.AreEqual("I like XML better", comments[1].Body); }
public JSEngineInstance(IRequestApi requestApi, IResponseApi responseApi, IConsoleLogApi consoleLogApi) { _requestApi = requestApi; _responseApi = responseApi; _consoleLogApi = consoleLogApi; _htmlDocumentApi = new HtmlDocumentApi(); _formApi = new FormApi(); _javascriptApi = new JavascriptApi(); _jsonApi = new JsonApi(); _contentApi = new ContentApi(); AddHostObject("request", _requestApi); AddHostObject("response", _responseApi); AddHostObject("log", _consoleLogApi); AddHostObject("document", _htmlDocumentApi); AddHostObject("form", _formApi); AddHostObject("js", _javascriptApi); AddHostObject("json", _jsonApi); AddHostObject("content", _contentApi); }
public static void JsonMain() { var UcsVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); var f = new JsonApi { UCS = new Dictionary <string, string> { { "Codename", Sys.ConfUCS.Codename }, { "StartingLevel", ConfigurationManager.AppSettings["startingLevel"] }, { "StartingExperience", ConfigurationManager.AppSettings["startingExperience"] }, { "StartingGems", ConfigurationManager.AppSettings["startingGems"] }, { "StartingGold", ConfigurationManager.AppSettings["startingGold"] }, { "StartingElixir", ConfigurationManager.AppSettings["startingElixir"] }, { "StartingDarkElixir", ConfigurationManager.AppSettings["startingDarkElixir"] }, { "StartingTrophies", ConfigurationManager.AppSettings["startingTrophies"] }, { "StartingShieldTime", ConfigurationManager.AppSettings["startingShieldTime"] }, { "PatchingServer", ConfigurationManager.AppSettings["patchingServer"] }, { "Maintenance", ConfigurationManager.AppSettings["maintenanceMode"] }, { "MaintenanceTimeLeft", ConfigurationManager.AppSettings["maintenanceTimeLeft"] }, { "ServerPort", ConfigurationManager.AppSettings["serverPort"] }, { "ClientVersion", ConfigurationManager.AppSettings["clientVersion"] }, { "ServerVersion", UcsVersion }, { "LoggingLevel", ConfigurationManager.AppSettings["loggingLevel"] }, { "OldClientVersion", ConfigurationManager.AppSettings["oldClientVersion"] }, { "DatabaseType", ConfigurationManager.AppSettings["databaseConnectionName"] }, { "ExpertPVE", ConfigurationManager.AppSettings["expertPve"] }, { "SaveThreadCount", ConfigurationManager.AppSettings["saveThreadCount"] }, { "OnlinePlayers", Convert.ToString(ResourcesManager.GetOnlinePlayers().Count) }, { "InMemoryPlayers", Convert.ToString(ResourcesManager.GetInMemoryLevels().Count) }, { "InMemoryClans", Convert.ToString(ObjectManager.GetInMemoryAlliances().Count) }, { "TotalPlayer", Convert.ToString(ResourcesManager.GetAllPlayerIds().Count) }, { "TotalClans", Convert.ToString(ObjectManager.GetInMemoryAlliances().Count) }, { "TotalConnectedClients", Convert.ToString(ResourcesManager.GetConnectedClients().Count) } } }; jsonapp = JsonConvert.SerializeObject(f); }
//Nome do Valor Passado Na Action Deve Ter Mesmo Nome Da ViewModel public ActionResult Inserir_Documento(string document) { /*O bloco seguinte valida os estados do DataAnnotation para caso alguém consiga burlar * se a pessoa colocar CodigoPedido errado e não passar pela validação, então ela é redirecionada * para a view Index!*/ if (!ModelState.IsValid) { return(View("Index")); } List <ListaPedidosViewModel> listaPedidos = new List <ListaPedidosViewModel>(); //PessoaFisica if (document.Length == 14) { object JsonResult = RequisicaoApiMillennium.GetApiResultado_CPF(document); //Verifica conexão com porta da API do servidor if (JsonResult != null) { var resultado = JsonApi.FromJson(JsonResult.ToString()); //Verifica se há pedidos if (resultado.OdataCount == 0 && resultado.OdataMetadata != null && resultado.Value != null) { TempData["NoOrderException"] = "Não foram encontrados pedidos no seu CPF."; } //Se encontrado os pedidos, armazena os retornados da Api em uma lista else { foreach (var pv in resultado.Value) { listaPedidos.Add(new ListaPedidosViewModel() { Pedido = pv.Pedido, Status = pv.Status, DataPedido = pv.DataPedido, ValorPedido = pv.ValorPedido, NomeCliente = pv.NomeCliente }); } } } //Se a primeira condição for falsa, avisa sobre o erro de conexão com o servidor else { TempData["ServerConnException"] = "O servidor está fora do ar no momento, tente novamente mais tarde."; } } //PessoaJuridica else if (document.Length == 18) { object JsonResult = RequisicaoApiMillennium.GetApiResultado_CNPJ(document); if (JsonResult != null) { var resultado = JsonApi.FromJson(JsonResult.ToString()); if (resultado.OdataCount == 0 && resultado.OdataMetadata != null && resultado.Value != null) { TempData["NoOrderException"] = "Não foram encontrados pedidos no seu CNPJ."; } else { foreach (var pv in resultado.Value) { listaPedidos.Add(new ListaPedidosViewModel() { Pedido = pv.Pedido, Status = pv.Status, DataPedido = pv.DataPedido, ValorPedido = pv.ValorPedido, NomeCliente = pv.NomeCliente }); } } } else { TempData["ServerConnException"] = "O servidor está fora do ar no momento, tente novamente mais tarde."; } } else { TempData["DocException"] = "Por alguma razão seu documento não foi digitado corretamente, tente novamente ou entre em contato com o Suporte e comunique o erro!\nErro Cod 1: Tamanho Doc Inválido"; } TempData["ListaPedidos"] = listaPedidos; return(RedirectToAction("Mostrar_Pedidos", "Pedidoslista")); }
public void TestMethod1() { var sessionJson = TestData.ValidDocumentSessioinJson(); var user = JsonApi.ResourceFromDocument <Sessions>(sessionJson, ignoreMissingRelationships: true); }
public void TestInitialize() { var json = TestData.ValidDocumentErrorsJson(); _document = JsonApi.Document(json); }
public async Task <IActionResult> SearchUsersByLastName([FromRoute] string lastName) { return(JsonApi.OkDataObject(await _userOperations.SearchUserByLastName(lastName))); }
public async Task <IActionResult> SearchUsersByEmail([FromRoute] string email) { return(JsonApi.OkDataObject(await _userOperations.SearchUserByEmail(email))); }
public async Task <IActionResult> GetUser([FromRoute] string id) { return(JsonApi.OkDataObject(await _userOperations.GetUser(id))); }
public async Task <IActionResult> RegisterUser([Required, FromBody] Registration registration) { var newUser = await _userOperations.CreateUser(registration); return(CreatedAtAction(nameof(GetUser), new { id = registration.Email }, JsonApi.DataObject(newUser))); }