public void ArticleFromDocumentTest()
        {
            var json        = TestData.ReadmeAttributeTypeResolutionJson();
            var ghostBuster = JsonApi.ResourceFromDocument <GhostBuster>(json);

            Assert.AreEqual("I collect spores, molds, and fungus.", ghostBuster.Quotes[0]);
        }
예제 #2
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);
        }
예제 #4
0
 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()));
     });
 }
예제 #5
0
        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)));
        }
예제 #6
0
        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);
        }
예제 #8
0
    /// <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);
    }
예제 #9
0
        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);
        }
예제 #14
0
        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());
        }
예제 #15
0
        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);
        }
예제 #16
0
        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);
        }
예제 #17
0
        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);
            }
        }
예제 #18
0
    /// <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);
        }
    }
예제 #19
0
        //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"));
        }
예제 #20
0
        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);
        }
예제 #21
0
        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);
        }
예제 #22
0
        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);
        }
예제 #23
0
        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);
        }
예제 #24
0
        //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"));
        }
예제 #25
0
 public void TestMethod1()
 {
     var sessionJson = TestData.ValidDocumentSessioinJson();
     var user        = JsonApi.ResourceFromDocument <Sessions>(sessionJson, ignoreMissingRelationships: true);
 }
예제 #26
0
        public void TestInitialize()
        {
            var json = TestData.ValidDocumentErrorsJson();

            _document = JsonApi.Document(json);
        }
예제 #27
0
 public async Task <IActionResult> SearchUsersByLastName([FromRoute] string lastName)
 {
     return(JsonApi.OkDataObject(await _userOperations.SearchUserByLastName(lastName)));
 }
예제 #28
0
 public async Task <IActionResult> SearchUsersByEmail([FromRoute] string email)
 {
     return(JsonApi.OkDataObject(await _userOperations.SearchUserByEmail(email)));
 }
예제 #29
0
 public async Task <IActionResult> GetUser([FromRoute] string id)
 {
     return(JsonApi.OkDataObject(await _userOperations.GetUser(id)));
 }
예제 #30
0
        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)));
        }