コード例 #1
0
        public async Task <Model> GetModel()
        {
            List <Task> tasks = new List <Task>();

            Task <List <MatchModel> > matches = RESTHelper.GetMatchesAsync();

            tasks.Add(matches);

            Task <List <TeamModel> > teams = RESTHelper.GetTeamsAsync();

            tasks.Add(teams);

            Task <List <LeagueModel> > leagues = RESTHelper.GetLeaguesAsync();

            tasks.Add(leagues);


            await Task.WhenAll(tasks);

            return(new Model
            {
                Matches = matches.Result,
                Teams = teams.Result,
                Leagues = leagues.Result
            });
        }
コード例 #2
0
        //[TestCase("ja", @"私は麺を食べたい")]
        //[TestCase("el", @"Μου αρέσει να τρώω πίτα")]
        public void languageReliabilityTest(string expected, string text)
        {
            //ARRANGE
            Dictionary <string, string> RESTQueryParameters = new Dictionary <string, string>();

            RESTQueryParameters.Add("key", Constants.APIKEY);
            RESTQueryParameters.Add("q", text);


            //ACT
            IRestResponse response = RESTHelper.Query(client, langRequest, RESTQueryParameters);

            RestSharp.Deserializers.JsonDeserializer deserializer = new RestSharp.Deserializers.JsonDeserializer();
            LangIDResult result = deserializer.Deserialize <LangIDResult>(response);

            Detection detection = result.data.detections[0];

            TestContext.Out.WriteLine("Language: {0}", detection.language);
            TestContext.Out.WriteLine("Reliable: {0}", detection.isReliable);
            TestContext.Out.WriteLine("Confidence: {0}", detection.confidence);


            //ASSERT
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual(expected, detection.language, "we expected the language to be en but instead it was {0}", detection.language);
            Assert.Greater(detection.confidence, 5.0);
        }
コード例 #3
0
        /// <summary>
        /// Read key-value pairs
        /// </summary>
        /// <returns>Dictionary, key is string and value is object, it can be any primitive types or fsData</returns>
        public DictionaryCallback <string, object> ReadKeyValuePairs()
        {
            DictionaryCallback <string, object> callbackHandler = new DictionaryCallback <string, object>();

            string route = FirebaseConfig.endpoint + path + ".json" + GetAuthParam();

            RESTHelper.Get(route, res =>
            {
                var resData = fsJsonParser.Parse(res.Text); //in JSON
                Dictionary <string, object> destructuredRes = new Dictionary <string, object>();

                if (resData.IsDictionary)
                {
                    resData.AsDictionary.ToList().ForEach(x => destructuredRes.Add(x.Key, x.Value._value));
                    callbackHandler.successCallback?.Invoke(destructuredRes);
                    return;
                }
                //No collection, single result (key-value pair)
                string[] splittedPaths = path.Split('/');
                destructuredRes.Add(splittedPaths[splittedPaths.Length - 1], resData._value); //last path as key, resData._value as object
                callbackHandler.successCallback?.Invoke(destructuredRes);
            },
                           err =>
            {
                callbackHandler.exceptionCallback?.Invoke(err);
            });

            return(callbackHandler);
        }
コード例 #4
0
        /// <summary>
        /// 1.1 Get all lights
        /// URL: http://<bridgeipaddress>/api/<username>/lights
        /// Method: GET
        /// Version: 1.0
        /// Permission: Whitelist
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task <List <Light> > GetAllLights(string ipAddress, string userName)
        {
            string url = ipBase + ipAddress + apiBase + userName + apiGroup;

            Debug.WriteLine("<Philips Hue - APIs - Lights> GetAllLights - Url to be used: " + url);

            string response = await RESTHelper.Get(url);

            Debug.WriteLine("<Philips Hue - APIs - Lights> GetAllLights - Response recieved: : " + response);

            List <Light> LightList = new List <Light>();
            JToken       token     = JToken.Parse(response);

            if (token.Type == JTokenType.Object)
            {
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Light newLight = JsonConvert.DeserializeObject <Light>(prop.Value.ToString());
                    //newLight.bridgeid = prop.Name;
                    LightList.Add(newLight);
                    Debug.WriteLine("<Philips Hue - APIs - Lights> GetAllLights - Light added to list. Light name: " + prop.Name);
                }
            }
            return(LightList);
        }
コード例 #5
0
        /// <summary>
        /// Read key-value pairs
        /// </summary>
        /// <typeparam name="T">Value type</typeparam>
        /// <returns>Dictionary, key as string, value as specified type. Returns nothing if failed to deserialize.</returns>
        public DictionaryCallback <string, T> ReadKeyValuePairs <T>()
        {
            DictionaryCallback <string, T> callbackHandler = new DictionaryCallback <string, T>();

            string route = FirebaseConfig.endpoint + path + ".json" + GetAuthParam();

            RESTHelper.Get(route, res =>
            {
                var resData = fsJsonParser.Parse(res.Text);

                object deserializedRes = null;

                fsSerializer serializer = new fsSerializer();
                serializer.TryDeserialize(resData, typeof(Dictionary <string, T>), ref deserializedRes);

                Dictionary <string, T> destructuredRes = (Dictionary <string, T>)deserializedRes;

                callbackHandler.successCallback?.Invoke(destructuredRes);
            },
                           err =>
            {
                callbackHandler.exceptionCallback?.Invoke(err);
            });

            return(callbackHandler);
        }
コード例 #6
0
        /// <summary>
        /// Read value of key
        /// </summary>
        /// <returns>Value as Json String, else object</returns>
        public ObjectCallback ReadValue()
        {
            ObjectCallback callbackHandler = new ObjectCallback();

            string route = FirebaseConfig.endpoint + path + ".json" + GetAuthParam();

            RESTHelper.Get(route, res =>
            {
                var resData = fsJsonParser.Parse(res.Text);

                if (resData.IsDictionary)
                {
                    callbackHandler.successCallback?.Invoke(res.Text); //invoke with raw Json, as it's not a key-value pair
                    return;
                }
                //No collection
                object value = resData._value;
                callbackHandler.successCallback?.Invoke(value);
            },
                           err =>
            {
                callbackHandler.exceptionCallback?.Invoke(err);
            });

            return(callbackHandler);
        }
コード例 #7
0
        void ChildEventListen(ChildEventHandler eventHandler)
        {
            RequestHelper req = new RequestHelper
            {
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "text/event-stream" }
                },
                Uri               = FirebaseConfig.endpoint + path + ".json" + GetAuthParam(),
                DownloadHandler   = eventHandler,
                Retries           = int.MaxValue,
                RetrySecondsDelay = 1
            };

            //create an unsubscriber for events
            var unsubscriberGO = GameObject.Find("FirebaseRestUnsubscriber");

            if (unsubscriberGO == null)
            {
                unsubscriberGO = new GameObject("FirebaseRestUnsubscriber");
                unsubscriberGO.AddComponent <EventUnsubscriber>().requestHelper = req;
                MonoBehaviour.DontDestroyOnLoad(unsubscriberGO);
            }
            //Error handling are being handled internally
            RESTHelper.Get(req, err => RequestErrorHelper.ToDictionary(err).ToList().ForEach(x => Debug.LogError(x.Key + " - " + x.Value)));
        }
コード例 #8
0
        /// <summary>
        /// 1.2 Get new lights
        /// URL: http://<bridgeipaddress>/api/<username>/lights/new
        /// Method: GET
        /// Version: 1.0
        /// Permission: Whitelist
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task <List <Light> > GetNewLights(string url)
        {
            url = url + "/lights/new";
            Debug.WriteLine("<Philips Hue - APIs - Lights> GetNewLights - Url to be used: " + url);

            string response = await RESTHelper.Get(url);

            Debug.WriteLine("<Philips Hue - APIs - Lights> GetNewLights - Response recieved: : " + response);

            List <Light> LightList = new List <Light>();
            JToken       token     = JToken.Parse(response);

            if (token.Type == JTokenType.Object)
            {
                var jsonResult = (JObject)token;
                var lastscan   = jsonResult.First;
                jsonResult.First.Remove();

                foreach (var prop in jsonResult.Properties())
                {
                    Light newLight = JsonConvert.DeserializeObject <Light>(prop.Value.ToString());
                    //newLight.bridgeid = prop.Name;
                    LightList.Add(newLight);
                    Debug.WriteLine("<Philips Hue - APIs - Lights> GetNewLights - Light added to list. Light name: " + newLight.name);
                }
            }
            return(LightList);
        }
コード例 #9
0
        public virtual ActionResult Index()
        {
            var model = new AllModel();

            var ListUser      = RESTHelper.Get <ResultModel <List <UsersModel> > >(ConfigurationManager.AppSettings["HostAPIURL"] + ConfigurationManager.AppSettings["GetAllUser"]);
            var ListCatalogue = RESTHelper.Get <ResultModel <List <CatalogueModel> > >(ConfigurationManager.AppSettings["HostAPIURL"] + ConfigurationManager.AppSettings["GetAllCatalague"]);
            var ListInvoice   = RESTHelper.Get <ResultModel <List <InvoiceModel> > >(ConfigurationManager.AppSettings["HostAPIURL"] + ConfigurationManager.AppSettings["GetAllInvoice"]);

            ViewBag.NoInvoice = RESTHelper.Get <ResultModel <string> >(ConfigurationManager.AppSettings["HostAPIURL"] + ConfigurationManager.AppSettings["GenerateNoInvoice"]);
            if (ListCatalogue != null)
            {
                model.ListCatalogues = ListCatalogue.Value;
            }
            if (ListInvoice != null)
            {
                model.ListInvoices = ListInvoice.Value;
            }
            if (ListUser != null)
            {
                model.ListUsers = ListUser.Value;
            }
            if (TempData.ContainsKey("StatusMessage"))
            {
                ViewBag.Message = TempData["StatusMessage"];
            }

            return(View(model));
        }
コード例 #10
0
        /// <summary>
        /// Order results by child value. [Firebase rules must be set]
        /// </summary>
        /// <returns>Raw Json</returns>
        public StringCallback OrderByValue()
        {
            StringCallback callbackHandler = new StringCallback();

            RequestHelper req = new RequestHelper
            {
                Uri    = FirebaseConfig.endpoint + path + ".json" + GetAuthParam(),
                Params = new Dictionary <string, string>
                {
                    { "orderBy", "\"$value\"" }
                }
            };

            //adding filters if there is
            GetFilterCollection(true)?.ToList().ForEach(x => req.Params.Add(x.Key, x.Value));

            RESTHelper.Get(req, res =>
            {
                callbackHandler.successCallback?.Invoke(res.Text);
            },
                           err =>
            {
                callbackHandler.exceptionCallback?.Invoke(err);
            });

            return(callbackHandler);
        }
コード例 #11
0
        public void JoinTeam(HttpListenerContext context)
        {
            string[] parameters = context.Request.RawUrl.Replace("/Join/Team/", "").Split('/');
            int      teamId     = int.Parse(parameters[0]);
            string   token      = parameters[1];


            var session = SessionManager.GetSession(token);

            var personDTO = RESTHelper.GetObject <PersonDTO>(context);

            if (session.user.People.Any(p => p.PersonId == personDTO.Id))
            {
                UnitOfWork unit = new UnitOfWork(session.context);

                var team   = unit.Teams.GetTeamWithMembers(teamId);
                var person = unit.People.Get(personDTO.Id.Value);

                if (team != null && !team.Members.Any(m => m.Id == person.Id))
                {
                    team.Members.Add(person);
                    unit.Complete();
                }



                MyResponder.RespondJson(context, team.ToDTO());
            }
        }
コード例 #12
0
ファイル: Updater.cs プロジェクト: 07101994/FloorballXamarin
        /// <summary>
        /// Get updates from server
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private async Task GetUpdates(DateTime date)
        {
            var updateModel = await RESTHelper.GetUpdatesAsync(date);

            SyncDate       = updateModel.UpdateTime;
            UpdateDataList = updateModel.Updates;
        }
コード例 #13
0
        /// <summary>
        /// Check for child in selected path
        /// </summary>
        /// <param name="child">child name</param>
        /// <returns>Returns true if child exists, else false</returns>
        public BooleanCallback HasChild(string child)
        {
            BooleanCallback callbackHandler = new BooleanCallback();

            string route = FirebaseConfig.endpoint + path + "/" + child + ".json" + GetAuthParam();

            RESTHelper.Get(route, res =>
            {
                //If there is no child, server return "null"
                if (res.Text != "null" && res.Text.Length > 0)
                {
                    callbackHandler.successCallback?.Invoke(true);
                }
                else
                {
                    callbackHandler.successCallback?.Invoke(false);
                }
            },
                           err =>
            {
                callbackHandler.exceptionCallback?.Invoke(err);
            });

            return(callbackHandler);
        }
コード例 #14
0
        /// <summary>
        /// Obtiene los doctores filtrados por su especialidad
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static List <Employee> GetDoctorBySpecialty(int id)
        {
            string     url          = String.Format("/specialty/{0}/doctors", id);
            string     res          = RESTHelper.Execute(url, "", "GET");
            Employe_Tr deserealized = JsonConvert.DeserializeObject <Employe_Tr>(res);

            return(deserealized.doctors);
        }
コード例 #15
0
        public static User LogIn(string usr, string pwd)
        {
            string  url          = String.Format("/login?username={0}&password={1}", usr, pwd);
            string  res          = RESTHelper.Execute(url, "", "GET");
            User_Tr deserealized = JsonConvert.DeserializeObject <User_Tr>(res);

            return(deserealized.user);
        }
コード例 #16
0
        /// <summary>
        /// Horarios que ya tienen una cita, para ser eliminados de los disponibles al agendar una cita
        /// </summary>
        /// <param name="date">Fecha solicitada</param>
        /// <param name="id_doctor">Doctor del cual se van a consultar horarios</param>
        /// <returns></returns>
        public static List <Appointment> ExistentHours(string date, int id_doctor)
        {
            string         url          = String.Format("/appointment/existent?date={0}&id_doctor={1}", date, id_doctor);
            string         res          = RESTHelper.Execute(url, "", "GET");
            Appointment_Tr deserialized = JsonConvert.DeserializeObject <Appointment_Tr>(res);

            return(deserialized.appointments);
        }
コード例 #17
0
        /// <summary>
        /// Obtiene las citas agendadas para el día indicado
        /// </summary>
        /// <param name="date">Día de citas a consultar (hoy)</param>
        /// <param name="id">id de médico</param>
        /// <returns>Cita(nombre_paciente, id, num de cita)</returns>
        public static List <Appointment> GetPacientsAppointments(string date, string id)
        {
            string         url          = String.Format("/appointment/day?date={0}&id_doctor={1}", date, id);
            string         res          = RESTHelper.Execute(url, "", "GET");
            Appointment_Tr deserealized = JsonConvert.DeserializeObject <Appointment_Tr>(res);

            return(deserealized.appointments);
        }
コード例 #18
0
        public void EmployeeCreationWithInvalidAccessTokenIsNotAllowed()
        {
            _sut = new RESTHelper(false);
            var response = _sut.CreateEntityAndGetAStatusCode(_client, ExpectedEmployeeName + _sut.EntityCode);

            Assert.That(response, Is.EqualTo(HttpStatusCode.Unauthorized),
                        "Employee creation with the invalid token was allowed, but should not have been.");
        }
コード例 #19
0
        //{"specialties":[{"opening_time":"08:08:08","name":"lalo","id":1,"extension":"hola","description":"hola","cost":18.89999962,"closing_time":"08:08:08"}]}

        /// <summary>
        /// Obtiene las especialidades disponibles
        /// </summary>
        /// <returns>Objeto especialidad</returns>
        public static List <Specialty> GetSpecialties()
        {
            List <Specialty> lstSpecialties = new List <Specialty>();
            string           url            = String.Format("/specialty");
            string           res            = RESTHelper.Execute(url, "", "GET");
            Specialty_Tr     deserealized   = JsonConvert.DeserializeObject <Specialty_Tr>(res);

            return(deserealized.specialties);
        }
コード例 #20
0
        /// <summary>
        /// Retorna el paciente con el id indicado
        /// </summary>
        /// <param name="id">id de paciente</param>
        /// <returns>Objeto paciente </returns>
        public static Patient GetPatientById(int id)
        {
            Patient    objPatient   = new Patient();
            string     url          = String.Format("/patient/{0}", id);
            string     res          = RESTHelper.Execute(url, "", "GET");
            Patient_Tr deserealized = JsonConvert.DeserializeObject <Patient_Tr>(res);

            return(deserealized.patient);
        }
コード例 #21
0
        /// <summary>
        /// Retorna todos los pacientes en base de datos
        /// </summary>
        /// <returns>Lista de pacientes</returns>
        public static List <Patient> GetAllPatients()
        {
            Patient    objPatient   = new Patient();
            string     url          = String.Format("/patient");
            string     res          = RESTHelper.Execute(url, "", "GET");
            Patient_Tr deserealized = JsonConvert.DeserializeObject <Patient_Tr>(res);

            return(deserealized.patients);
        }
コード例 #22
0
        public void GetAllExistingEmployeesWithInvalidTokenIsNotAllowed()
        {
            CreateANumberOfEmployees();
            _sut = new RESTHelper(false);
            var response = _sut.GetAllEntities(_client);

            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized),
                        "Get all existing Employees with the invalid token was allowed, but should not have been.");
        }
コード例 #23
0
 public void Initialize()
 {
     _sut    = new RESTHelper();
     _client = new RestClient(EmployeesEndpoint);
     if (_sut.DoesAnyEntityExist(_client))
     {
         _sut.DeleteAllEntities(_client);
     }
 }
コード例 #24
0
        /// <summary>
        /// 7.2 Get configuration
        /// URL: http://<bridgeipaddress>/api/<username>/config
        /// Method: GET
        /// Version: 1.0
        /// Permission: Whitelist
        /// </summary>
        /// <param name="url"></param>
        public static async Task <Config> GetConfiguration(string ipAddress)
        {
            string url      = ipBase + ipAddress + apiBase + "/config";
            string response = await RESTHelper.Get(url);

            Config config = JsonConvert.DeserializeObject <Config>(response);

            return(config);
        }
コード例 #25
0
        /// <summary>
        /// Obtiene las medicinas de las que se debe solicitar pedido porque su stock es menor al mínimo solicitado
        /// </summary>
        /// <returns>Lista de medicamentos con stock menor</returns>
        public static List <Drug> GetPending()
        {
            string      res          = RESTHelper.Execute("/drug/status", "", "GET");
            Drug_Tr     deserealized = JsonConvert.DeserializeObject <Drug_Tr>(res);
            List <Drug> lstDrugs     = new List <Drug>();

            lstDrugs.AddRange(deserealized.drugs);
            return(lstDrugs);
        }
コード例 #26
0
ファイル: Manager.cs プロジェクト: 07101994/FloorballXamarin
        public async Task InitDatabaseFromServerAsync()
        {
            List <Task> tasks = new List <Task>();

            Task <List <EventMessageModel> > eventMessagesTask = RESTHelper.GetEventMessagesAsync();

            tasks.Add(eventMessagesTask);
            Task <List <LeagueModel> > leaguesTask = RESTHelper.GetLeaguesAsync();

            tasks.Add(leaguesTask);
            Task <List <RefereeModel> > refereesTask = RESTHelper.GetRefereesAsync();

            tasks.Add(refereesTask);
            Task <List <PlayerModel> > playersTask = RESTHelper.GetPlayersAsync();

            tasks.Add(playersTask);
            Task <List <StadiumModel> > stadiumsTask = RESTHelper.GetStadiumsAsync();

            tasks.Add(stadiumsTask);
            Task <List <TeamModel> > teamsTask = RESTHelper.GetTeamsAsync(true);

            tasks.Add(teamsTask);
            Task <List <MatchModel> > matchesTask = RESTHelper.GetMatchesAsync();

            tasks.Add(matchesTask);
            Task <Dictionary <int, List <int> > > playersAndTeamsTask = RESTHelper.GetPlayersAndTeamsAsync();

            tasks.Add(playersAndTeamsTask);
            Task <Dictionary <int, List <int> > > playersAndMatchesTask = RESTHelper.GetPlayersAndMatchesAsync();

            tasks.Add(playersAndMatchesTask);
            Task <Dictionary <int, List <int> > > refereesAndMatchesTask = RESTHelper.GetRefereesAndMatchesAsync();

            tasks.Add(refereesAndMatchesTask);
            Task <List <EventModel> > eventsTask = RESTHelper.GetEventsAsync();

            tasks.Add(eventsTask);

            await Task.WhenAll(tasks);

            Database db = new Database
            {
                EventMessages      = eventMessagesTask.Result,
                Leagues            = leaguesTask.Result,
                Referees           = refereesTask.Result,
                Players            = playersTask.Result,
                Stadiums           = stadiumsTask.Result,
                Teams              = teamsTask.Result,
                Matches            = matchesTask.Result,
                PlayersAndTeams    = playersAndTeamsTask.Result,
                PlayersAndMatches  = playersAndMatchesTask.Result,
                RefereesAndMatches = refereesAndMatchesTask.Result,
                Events             = eventsTask.Result
            };

            await AddTablesAsync(db);
        }
コード例 #27
0
        // date, type, diagnosis, result, indications, treatment, id_doctor, id_history
        public void CreateStudy(Study Obj)
        {
            string   param   = "/study";
            Study_Tr studyTr = new Study_Tr();

            studyTr.study = Obj;
            string json = JsonConvert.SerializeObject(studyTr);

            RESTHelper.PostJSON(param, json);
        }
コード例 #28
0
        //{"antecedent":{"name":"lalo","description":"descripcion","type":"heredofamiliar","clinical_history_id":"1"}}  return id
        private void CreateAntecedent(Antecedent pAntecedent)
        {
            string        param       = "/antecedent";
            Antecedent_Tr transaction = new Antecedent_Tr();

            transaction.antecedent = pAntecedent;
            string json = JsonConvert.SerializeObject(transaction);

            RESTHelper.PostJSON(param, json);
        }
コード例 #29
0
        public static void OrderDrugs(List <Drug> pDrugs)
        {
            string  param       = "/drug/order";
            Drug_Tr transaction = new Drug_Tr();

            transaction.drugs = pDrugs;
            string json = JsonConvert.SerializeObject(transaction);

            RESTHelper.PostJSON(param, json);
        }
コード例 #30
0
        public void Login(HttpListenerContext context)
        {
            Console.WriteLine("URL: {0}", context.Request.RawUrl);

            var     userDTO = RESTHelper.GetObject <UserDTO>(context);
            Session session = new Session(userDTO.Login, userDTO.Password);

            var respondObject = new UserDTO(session.user);

            MyResponder.RespondJson(context, respondObject);
        }